首页 > 解决方案 > 为什么 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 值的预期结果。

谢谢你的帮助。

标签: pythonmachine-learninglogistic-regression

解决方案


推荐阅读