代码之家  ›  专栏  ›  技术社区  ›  efeatikkan

Python-Numpy逻辑回归

  •  1
  • efeatikkan  · 技术社区  · 8 年前

    我正在尝试使用python实现矢量化逻辑回归 努比。我的成本函数(CF)似乎工作正常。然而,有一个 应返回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 arrray, y 为100x1,并且 theta

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

    错误:“值错误:形状(3100)和(3100)未对齐:100(尺寸1)!=3(尺寸0)”

    1 回复  |  直到 8 年前
        1
  •  2
  •   MB-F    8 年前

    我认为(hypo-y)部分有问题。

    hypo 形状良好 (100,) y 形状良好 (100, 1) . 在元素方面 - 活动 海波 广播到形状 (1, 100) broadcasting rules . 这会导致 (100, 100) 数组,这会导致矩阵乘法产生 (3, 100) 大堆

    通过带来 形状与相同 y :

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

    还有一个问题: scipy.optimize.minimize (k,) 但是功能 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])