2017-10-05 202 views
0

我想在python中使用 numpy实现向量化逻辑回归。我的成本函数(CF)似乎工作正常。但是梯度计算有一个 问题。它返回3x100阵列,而它的 应该返回3x1。我认为(hypo-y)部分存在问题。Python Numpy逻辑回归

def sigmoid(a): 
    return 1/(1+np.exp(-a))  

def CF(theta,X,y): 
    m=len(y) 
    hypo=sigmoid(np.matmul(X,theta)) 
    J=(-1./m)*((np.matmul(y.T,np.log(hypo)))+(np.matmul((1-y).T,np.log(1-hypo)))) 
    return(J) 

def gr(theta,X,y): 
    m=len(y) 
    hypo=sigmoid(np.matmul(X,theta)) 

    grad=(1/m)*(np.matmul(X.T,(hypo-y))) 

    return(grad) 

X是100x3 arrray,y是100X1和theta是一个3×1 arrray。看来两个功能独立工作,然而,这优化功能提供了一个错误:

optim = minimize(CF, theta, method='BFGS', jac=gr, args=(X,y)) 

The error: "ValueError: shapes (3,100) and (3,100) not aligned: 100 (dim 1) != 3 (dim 0)"

+1

请说明如何用示例输入调用函数。我认为这与形成的形状有很大关系。 – kazemakase

+0

我的X输入是100X3阵列,y输入是100X1,θ输入是3X1阵列。现在看起来两个函数都单独工作,但是这个优化函数给出了一个错误:optim = minimize(CF,theta,method ='BFGS',jac = gr,args =(X,y))错误:“ValueError:shapes(3,100 )和(3,100)不对齐:100(dim 1)!= 3(dim 0)“感谢您的关注! – efeatikkan

回答

0

I think there is a problem with the (hypo-y) part.

点上!

hypo是形状(100,)y是形状(100, 1)。在元素方面-操作中,根据numpy的broadcasting ruleshypo被广播以形成(1, 100)。这导致(100, 100)阵列,这导致矩阵乘法导致(3, 100)阵列。

hypo = sigmoid(np.matmul(X, theta)).reshape(-1, 1) # -1 means automatic size on first dimension 

还有一个问题::scipy.optimize.minimize(我假定您使用)期望梯度为形状(k,)但阵列通过使hypo成相同的形状y

修复此函数gr返回形状为(k, 1)的矢量。这是很容易解决:

return grad.reshape(-1) 

最终的功能变得

def gr(theta,X,y): 
    m=len(y) 
    hypo=sigmoid(np.matmul(X,theta)).reshape(-1, 1) 
    grad=(1/m)*(np.matmul(X.T,(hypo-y))) 
    return grad.reshape(-1) 

和玩具数据工程运行它(我没有检查数学或结果的合理性):

theta = np.reshape([1, 2, 3], 3, 1)  
X = np.random.randn(100, 3) 
y = np.round(np.random.rand(100, 1))  

optim = minimize(CF, theta, method='BFGS', jac=gr, args=(X,y)) 
print(optim) 
#  fun: 0.6830931976615066 
# hess_inv: array([[ 4.51307367, -0.13048255, 0.9400538 ], 
#  [-0.13048255, 3.53320257, 0.32364498], 
#  [ 0.9400538 , 0.32364498, 5.08740428]]) 
#  jac: array([ -9.20709950e-07, 3.34459058e-08, 2.21354905e-07]) 
# message: 'Optimization terminated successfully.' 
#  nfev: 15 
#  nit: 13 
#  njev: 15 
# status: 0 
# success: True 
#  x: array([-0.07794477, 0.14840167, 0.24572182]) 
+0

非常感谢,它现在正常工作! – efeatikkan