Python Numpy 逻辑回归

Python Numpy Logistic Regression

我正在尝试在 python 中使用向量化逻辑回归 麻木的。我的成本函数 (CF) 似乎工作正常。但是有一个 梯度计算的问题。它 returns 3x100 数组而它 应该 return 3x1。我认为 (hypo-y) 部分有问题。

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 数组,y 是 100x1,theta 是 3x1 数组。似乎这两个函数都在单独工作,但是这个优化函数给出了一个错误:

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)"

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

正确!

hypo 的形状为 (100,)y 的形状为 (100, 1)。在element-wise -操作中,hypo根据numpy的broadcasting rules被广播到shape (1, 100)。这会产生一个 (100, 100) 数组,这会导致矩阵乘法产生一个 (3, 100) 数组。

通过将 hypo 变为与 y 相同的形状来解决此问题:

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

还有一个问题:scipy.optimize.minimize(我假设你正在使用)期望梯度是一个形状数组 (k,) 但函数 gr returns 形状为 (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])