如何将矩阵作为参数传递给scipy.optimize.minimize?

时间:2015-11-22 17:42:11

标签: python optimization scipy

当我尝试将矩阵作为参数传递给scipy.optimize.minimize时,总会有"形状未对齐"成本函数中的错误。但是当我单独计算Costfunction时,根本就没有错误......我也尝试将ndarrays作为参数传递给scipy.optimize.minimize,也没有错误。

我真的不知道它有什么问题。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

data=np.loadtxt('ex2data1.txt',delimiter=",")

m,n=data.shape

pos=np.nonzero(data[:,2]==1)
neg=np.nonzero(data[:,2]==0)

plt.scatter( data[pos,0], data[pos,1],color='r')
plt.scatter( data[neg,0], data[neg,1])
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.legend('Admitted', 'Not admitted')
plt.show()

X=np.concatenate( (np.ones([m,1]),data[:,0:2]) , axis=1 ) 
y=data[:,2]

def sigmoid(x):
    return 1.0 / (1.0 + np.exp(-x))

X=np.asmatrix(X)
y=(np.asmatrix(y)).T

def Costfunction(theta,X,y):
    Term1 = -y.T*np.log( sigmoid(X.dot(theta)) ) 
    Term2 = (1-y.T)*np.log( 1-sigmoid(X.dot(theta)) )
    return (Term1 - Term2)/m    
#
theta0= np.zeros([3,1]) 
print Costfunction(theta0,X,y)
#
res = minimize(Costfunction,x0=theta0,args=(X,y),method='Nelder-Mead')
print res

部分' ex2data1.txt'。

    34.62365962451697,78.0246928153624,0
    30.28671076822607,43.89499752400101,0
    35.84740876993872,72.90219802708364,0
    60.18259938620976,86.30855209546826,1
    79.0327360507101,75.3443764369103,1
    45.08327747668339,56.3163717815305,0
    61.10666453684766,96.51142588489624,1
    75.02474556738889,46.55401354116538,1
    76.09878670226257,87.42056971926803,1
    84.43281996120035,43.53339331072109,1
    95.86155507093572,38.22527805795094,0
    75.01365838958247,30.60326323428011,0
    82.30705337399482,76.48196330235604,1
    69.36458875970939,97.71869196188608,1
    39.53833914367223,76.03681085115882,0

0 个答案:

没有答案