我正在自学机器学习,当我尝试用 python 编写逻辑回归代码时出现错误。这是来自 Standford 在线类(class)。我已经尝试了很多次,包括将 grad 更改为 grad.ravel()/grad.fatten(),但都没有用。
输入:
import numpy as np
data=np.loadtxt(r'E:\ML\machine-learning-ex2\ex2\ex2data1.txt',delimiter=',')
X=data[:,:2]
y=data[:,2].reshape(-1,1)
def sigmoid(z):
return 1/(np.exp(-1*z)+1)
def costFunction(theta,X,y):
m=len(y)
h=sigmoid(np.dot(X,theta))
J=-1/m*np.sum((np.dot(y.T,np.log(h))+np.dot((1-y).T,np.log(1-h))))
grad=1/m*np.dot(X.T,(h-y))
return J,grad
m,n=np.shape(X)
X=np.hstack((np.ones([m,1]),X))
initial_theta=np.zeros([n+1,1])
import scipy.optimize as opt
result = opt.fmin_tnc(func=costFunction, x0=initial_theta, args=(X, y))
输出:
ValueError:
---> 25 result = opt.fmin_tnc(func=costFunction, x0=initial_theta, args=(X, y))
ValueError: tnc: invalid gradient vector from minimized function.
最佳答案
好吧,我忘了复制这些代码: m,n=np.shape(X) initial_theta=np.zeros(n+1) 我得到了答案。 x0 参数需要是一维数组,但我给了它一个二维数组。所以只需将 initial_theta 更改为 1D,然后在 costFunction
中将其 reshape 为 2D关于python - 值错误 : tnc: invalid gradient vector from minimized function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57455207/