我正在尝试使用scipy中的共轭梯度算法(fmin_cg)来寻找线性模型中最佳拟合的参数theta。
数据文件HouseData.csv(例如,房屋面积,房屋价格):
120, 250200, 467250, 5001200, 25981500, 3000
代码如下:
from scipy import optimizeimport numpy as npdata=np.genfromtxt('HouseData.csv',delimiter=',')X=np.c_[np.ones(len(data)),data[:,:-1]]Y=data[:,[-1]]def cost_Function(theta): theta1=theta[np.newaxis].T #print('theta: ',theta1) cost = Y-np.dot(X, theta1) return (cost*cost).sum()# 梯度函数def gradf(theta): theta1 = theta[np.newaxis].T cost = Y - np.dot(X, theta1) #print('cost*X.sum(0) is', np.sum(cost*X,axis=0)) return np.sum(cost*X,axis=0)x0 = np.asarray((0,1)) #初始猜测result = optimize.fmin_cg(cost_Function,x0,fprime=gradf)print(result)
如果不使用fprime=gradf,代码会返回正确的结果,但是梯度函数有什么问题呢?当包含上述代码时,算法返回的theta值与输入值完全相同。你会如何改进以提升性能?这只是一个简单的例子,但算法也应该能处理X有许多列和行的数据。
(python 3.5.1, scipy和numpy使用最新版本)
回答:
你的梯度显然是错误的。
由于你的成本函数是二次的,我们可以用gradf(x) = (f(x + eps) - f(x - eps)) / (2 eps)
来合理地近似梯度。让我们试试这个方法:
e0 = np.array([1, 0])e1 = np.array([0, 1])eps = 1e-5x0 = np.array([1, 1])df_yours = gradf(x0)# array([ 3.54000000e+03, 4.05583000e+06])df_approx = np.array([ cost_Function(x0 + eps*e0) - cost_Function(x0 - eps*e0), cost_Function(x0 + eps*e1) - cost_Function(x0 + eps*e1) - cost_Function(x0 - eps*e1)]) / (2 * eps)# array([ -7.07999999e+03, -8.11166000e+06])
在不进行数学分析的情况下(顺便说一下,你绝对应该进行数学分析而不是猜测),你的梯度函数偏差了-0.5
的因子。这个负号非常关键。