我正在尝试使用fmin进行逻辑回归,但是由于数组的形状不同,出现了一个错误。这是密码。
import numpy as np
import scipy.optimize as sp
data= #an array of dim (188,3)
X=data[:,0:2]
y=data[:,2]
m,n=np.shape(X)
y=y.reshape(m,1)
x=np.c_[np.ones((m,1)),X]
theta=np.zeros((n+1,1))
def hypo(x,theta):
return np.dot(x,theta)
def sigmoid(z):
return 1/(1+np.exp(-z))
def gradient(x,y,theta):#calculating Gradient
m=np.shape(x)[0]
t=hypo(x,theta)
hx=sigmoid(t)
J=-(np.dot(np.transpose(np.log(hx)),y)+np.dot(np.transpose(np.log(1-hx)),(1-y)))/m
grad=np.dot(np.transpose(x),(hx-y))/m
J= J.flatten()
grad=grad.flatten()
return J,grad
def costFunc(x,y,theta):
return gradient(x,y,theta)[0]
def Grad():
return gradient(x,y,theta)[1]
sp.fmin( costFunc, x0=theta, args=(x, y), maxiter=500, full_output=True)
File "<ipython-input-3-31a0d7ca38c8>", line 35, in costFunc
return gradient(x,y,theta)[0]
File "<ipython-input-3-31a0d7ca38c8>", line 25, in gradient
t=hypo(x,theta)
File "<ipython-input-3-31a0d7ca38c8>", line 16, in hypo
return np.dot(x,theta)
ValueError: shapes (3,) and (118,1) not aligned: 3 (dim 0) != 118 (dim 0)
任何帮助都将不胜感激
所以在这之后
这个
x
和theta
可以dotted
-np.dot(x,theta)
,并且(188,3)与(3,1)匹配但这不是你的
costFunc
得到的。从错误消息中回溯,看起来x
是(3,)
,而theta
是(118,1)
。显然不能是dotted
。您需要检查
fmin
如何调用您的函数。参数的顺序对吗?例如,也许costFunc(theta, x, y)
是正确的顺序(假设costFunc
中的x
和y
与args=(x,y)
匹配。fmin
的文档包括:看起来
fmin
正在提供costFunc
3个参数,它们的大小与(theta, x, y)
对应,即(3,)
、(118,3)
、(118,1)
。数字不太吻合,但我想你知道了。consFunc
的第一个参数是fmin
将变化的参数,其余参数将在args
中提供。相关问题 更多 >
编程相关推荐