python - 在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)
我无法弄清楚我错过了什么。我的实现不正确吗?任何帮助将非常感激。谢谢
解决方案
你不能在这里使用矩阵乘法,你想要的是将具有相同索引的元素相乘,即元素乘法。正确的运算符就是*
为此目的。
此外,您必须转置 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,您还应该更新代码以匹配。
推荐阅读
- c - AES128 和 CryptoAPI
- javascript - JS Set.has() 方法是否进行浅层检查?
- amazon-ec2 - AWS EC2 RHEL 7 auditd 服务正在运行但无法连接到远程服务器
- ruby-on-rails - 邪恶的 PDF 标题在本地正确显示,但在服务器上不正确
- java - 将 double 转换为 32 位表示(和相反的过程)
- javascript - 无法从那里的网站复制确切的引导模板
- angularjs - 如何使用 Sinatra 和 AngularJS 将对象从 AWS S3 流式传输到浏览器
- php - 为什么 phpmailer->send() 返回 true 但我没有收到电子邮件?
- laravel - Laravel 从数据库中获取路由
- c# - C# 移动文件并重命名它,如果它已经存在