[英]Implementing negative log-likelihood function in python
我在 python 中实现负对数似然 function 时遇到了一些困难
我的负对数似然 function 给出为:
这是我的实现,但我不断收到错误: 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 是 dataframe 大小: (2458, 31)
,y 是 dataframe 大小: (31,1)
(2458, 1)
theta 是 Z6A8064B5DF479450500D5534 大小:
我无法弄清楚我错过了什么。 我的实现不正确吗? 任何帮助将非常感激。 谢谢
你不能在这里使用矩阵乘法,你想要的是将具有相同索引的元素相乘,即元素乘法。 为此,正确的运算符是*
。
此外,您必须转置 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!
在对数内,您还应该更新代码以匹配。
如果你看你的方程,你传递的是 yixiθ 是对 i=1 求和到 M 所以这意味着你应该传递相同的 i 到 y 和 x 否则传递单独的 function 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.