形状未对齐:Scipy的fmin_tnc函数

问题描述

我正在尝试自己解决第二个练习的第一部分(逻辑回归):https://github.com/jdwittenauer/ipython-notebooks

在计算result变量时,我陷入了困境。这是错误消息的最后一部分:

File "<ipython-input-51-39288db7a045>",line 55,in ComputeCost
    h=sigmoid(np.dot(X,theta))

  File "<__array_function__ internals>",line 6,in dot

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

这是我的一段代码(很抱歉,我的编程技能很差,我是新手):

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.optimize as opt
data=pd.read_csv('ex2data1.txt',names=['exam1','exam2','admitted'])
def sigmoid(z):
    g=1/(1+np.exp(-z))
    return g
def whichisy(data,col):
    if not isinstance(data,pd.DataFrame):
        raise ValueError('Data is not a pandas DataFrame')
    y=data.iloc[:,col]
    X=data.drop(columns=data.columns[col])
    X.insert(0,'Ones',1)
    X=np.array(X)
    y=np.array(y)
    y=np.reshape(y,(len(y),1))
    return X,y
X,y=whichisy(data,2)

def ComputeCost(X,y,theta):
    h=sigmoid(np.dot(X,theta))
    cost=1/len(y)*np.sum(-y*np.log(h)-(1-y)*np.log(1-h))
    return cost

def Gradient(X,theta):
    g=np.zeros(len(theta))
    prodotto=sigmoid(np.dot(X,theta))-y
    for k in range(len(theta)):
        g[k]=1/len(y)*np.sum(prodotto*np.reshape(X[:,k],(len(X),1)))
    return g

theta=np.zeros([np.shape(X)[1],1])
result=opt.fmin_tnc(ComputeCost,theta,fprime=Gradient,args=(X,y))

我看过并理解了本练习的解决方案中的代码,但是我想使用自己的版本来解决它,但是我不会弄错我的地方。

我尝试将我的梯度函数(如此处matrices are not aligned Error: Python SciPy fmin_bfgs所示)和'y'数组(How to get dimensions right using fmin_cg in scipy.optimize)的返回值展平,但未成功。

谢谢!

编辑1:在定义thetaComputeCost函数时,将Gradient作为第一个参数之后,fmin_tnc函数会运行,但会导致最小化失败。

result=opt.fmin_tnc(ComputeCost,Gradient,y))

并返回:(array([4.60628149e-05,5.53178320e-03,5.18798215e-03]),45,4)。 因此rc(返回码)不是应该的1。

我还尝试运行result=opt.minimize(ComputeCost,method='TNC',jac=Gradient,y))来检查问题是否出在fmin_tnc函数中,但是返回的值是相同的。

解决方法

尝试将defComputeCostGradient中的'theta'移到'X'和'y'之前 例如

def ComputeCost(theta,X,y):
    # adjust the parameters in your code accordingly
    ...