首页 > 解决方案 > 在python中实现负对数似然函数

问题描述

我在 python 中实现负对数似然函数时遇到了一些困难

我的负对数似然函数给出为:

负对数似然方程的屏幕截图

这是我的实现,但我不断收到错误:ValueError: shapes (31,1) and (2458,1) not aligned: 1 (dim 1) != 2458 (dim 0)

def negative_loglikelihood(X, y, theta):
    J = np.sum(-y @ X @ theta) + np.sum(np.exp(X @ theta))+ np.sum(np.log(y))
    return J

X 是大小的数据框:(2458, 31), y 是大小的数据框:(2458, 1)theta 是大小的数据框:(31,1)

我无法弄清楚我错过了什么。我的实现不正确吗?任何帮助将非常感激。谢谢

标签: pythongradient-descentlog-likelihood

解决方案


你不能在这里使用矩阵乘法,你想要的是将具有相同索引的元素相乘,即元素乘法。正确的运算符就是*为此目的。

此外,您必须转置 theta 以便 numpy 可以将尺寸为 1 的维度广播到 2458(对于y: 1 广播到 31 也是如此。)

x = np.random.rand(2458, 31)
y = np.random.rand(2458, 1)
theta = np.random.rand(31, 1)

def negative_loglikelihood(x, y, theta):
    J = np.sum(-y * x * theta.T) + np.sum(np.exp(x * theta.T))+ np.sum(np.log(y))
    return J
negative_loglikelihood(x, y, theta)

>>> 88707.699

编辑:您的公式y!在对数内包含 a,您还应该更新代码以匹配。


推荐阅读