【问题标题】:scipy optimization error for logistic regression with regularization带有正则化的逻辑回归的 scipy 优化错误
【发布时间】:2014-07-22 07:35:15
【问题描述】:

当我尝试使用 CG 最小化以下功能时出现以下错误:

def costFunctionReg(theta, X, y, labda):
    import numpy as np
    import sigmoid as sg

    grad=np.zeros((28,1),dtype=float)

    #setting predictions
    m=len(y)
    #calculating predictions using the sigmoid function
    predictions=sg.sigmoid(np.dot(X,theta))
    predictions=predictions.reshape(np.size(predictions),1)
    y=y.reshape(np.size(y),1)
    predictionsminusy=predictions-y
    #predictionsminusyr=predictionsminusy.reshape(np.size(predictionsminusy),1)
    #calculating the cost of using theta as per logistic regression equation
    logistic=(-y*np.array(np.log(predictions)))-((1-y)*np.array(np.log(1-predictions)))
    endr=np.size(theta)
    J=1./m * np.sum(logistic)+(labda/(2*m))*np.sum(theta[0:endr]**2)
    #computing partial derivatives w.r.t to parameters
    endg=np.size(grad)
    endx,end=np.shape(X)
    grad[0,:]= 1.0/m * np.sum(np.dot((X[:,0]) ,(predictionsminusy) ));

    grad[1:endg,:]=((((1./m )* (np.dot(((predictionsminusy.conj().T)), (X[:,1:end]))))).conj().T)


    return [J,grad]

我得到错误:

ValueError: matrices are not aligned

/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.py(1151)_minimize_cg() 1150 而(gnorm > gtol)和(k 1151 deltak = numpy.dot(gfk,gfk) 第1152章

【问题讨论】:

  • 缩进计数,尤其是在 python 中。请重新格式化您的代码(每行以 4 个空格开始代码显示)
  • @andi import 函数内部的语句在 Python 中是完全合法的。重新格式化其他人的代码时不要进行语义更改。
  • @Craig van Wilson:您能否给出theta, X, y, labda 的规范,以便我可以尝试重现错误?
  • @AndrewMedico:这绝对不是故意的,对此我深表歉意。

标签: python numpy scipy


【解决方案1】:

尝试return J, grad.flatten() 而不是return J, grad

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2020-10-11
    • 2015-01-31
    • 2021-04-10
    • 2020-09-23
    • 2020-09-27
    • 2013-11-18
    • 2013-03-15
    相关资源
    最近更新 更多