优化.最小化行搜索失败。Python中的机器学习Andrew Ng赋值

2024-10-03 19:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在练习5中

我做了LinearRegCostFunction。你知道吗

但是optimize.minimize行搜索失败。你知道吗

我只放了一些相关的代码行。你知道吗

data = loadmat('ex5data1.mat')
X, y = data['X'],data['y']
m = y.size

def linearRegCostFunction(X,y,theta,lambda_=0.0):
    m = y.size
    J = 0
    theta=theta.reshape((2,1))
    grad = np.zeros(theta.shape)

    X = np.concatenate([np.ones(X.shape),X],axis=1)    
    prediction = X.dot(theta)

    temp = theta
    temp[0] = 0
    J = 1.0/(2.0*m)*(np.sum((prediction-y)**2))+lambda_/(2.0*m)*(np.sum(temp**2))
    grad = 1.0/m*X.T.dot(prediction-y)+lambda_/m*temp

    return J, grad

itheta = np.zeros((2,1))      #I also tried np.array([0, 0])


costgradF = lambda t: linearRegCostFunction(X,y,t,lambda_)
lambda_=0

res = optimize.minimize(costgradF,itheta,jac=True,method='tnc',options={'maxiter':100})
res

结果是

     fun: 26.62891562770855
     jac: array([[-12.57079675],
       [-19.76251528]])
 message: 'Linear search failed'
    nfev: 363
     nit: 12
  status: 4
 success: False
       x: array([0., 0.26609518])

我不明白为什么线性搜索失败了。你知道吗

因为Jgrad返回正确, 它和其他成功的代码都很相似。你知道吗


Tags: lambda代码datasizenpzerosarraytemp