python - 为什么 scipy.optimize.fmin_tnc 没有收敛到我的代码中的最佳解决方案?
问题描述
我正在尝试用 Python 实现 Coursera 的机器学习课程。我希望你使用 scipy.optimize.fmin_tnc 找到最佳 theta 值以最小化下面的 logregcost 函数。
import numpy as np
import scipy.optimize as op
def sigmoid(z):
return 1/(1+np.exp(-z))
def logregcost(theta,X,y):
m=len(y)
h_theta=sigmoid(np.dot(X,theta))
J_theta=((1/m)*sum(-y*np.log(h_theta)-(1-y)*np.log(1-h_theta)))[0]
return J_theta
def logreggrad(theta,X,y):
m=len(y)
h_theta=sigmoid(np.dot(X,theta[:,np.newaxis]))
grad_theta=(((1/m)*np.dot(X.T,h_theta-y)).T)[0,:]
return grad_theta
#Initialize theta
initial_theta=np.zeros([n,1])
initial_cost = logregcost(initial_theta, X_train, y_train)
print('Initial cost :',initial_cost)
#Try with a "manual" theta
test_theta=np.array([[-24],[0.2],[0.2]])
test_cost= logregcost(test_theta, X_train, y_train)
print('test cost :',test_cost)
#Train logistic regression
result=op.fmin_tnc(func=logregcost,x0=initial_theta.flatten(),fprime=logreggrad,args=(X_train,y_train))
theta_opt=result[0]
cost_opt= logregcost(theta_opt,X_train,y_train)
print('opt cost :',cost_opt,'opt theta :',theta_opt)
代码运行没有错误,但没有找到最佳值。与 fmin_tnc 找到的 theta 相比,手动实现的 test_theta 得到了更好的结果(见下面的结果)
初始成本:0.693147180559946
测试费用:0.218330193826598
选择成本:0.676346827187955 选择θ:[4.42735721e-05 5.31690927e-03 4.98646266e-03]
我已经验证了 logregcost 和 logreggrad 函数给出了一些 theta 值的预期结果。
谢谢你的帮助。
解决方案
推荐阅读
- python - Kivy 应用程序大小固定在全屏窗口中
- arrays - 删除列时,连接或 TextJoin 不起作用 - 解决方法是什么?
- c - Windows 需要 fflush,但 Linux 不需要
- python - EventFilter 中的问题,来自 QLineEdit 的 Alt / Shift 修饰符
- r - 从 r 中的两个独立数据库计算每个重叠的日期范围
- javascript - 在 Heroku 上部署 create-react-app 的应用程序错误
- perl - 无法在 Windows 中安装 MSWin32-x64-multi-thread perl
- azure-active-directory - 结合自定义注册和 Azure AD?
- python - 基于两种不同的损失函数进行更新,但在每个损失函数之后使用不同的优化器学习率(pytorch)?
- dynamic - Blue Prism 上表格元素的动态检查