【发布时间】:2014-01-09 22:46:42
【问题描述】:
我习惯于在 R 和 python 中对所有外围任务进行统计。只是为了好玩,我尝试了一个 BFGS 优化来将它与普通的 LS 结果进行比较——两者都是在 python 中使用 scipy/numpy。但结果不匹配。我没有看到任何错误。我还附上了 R 中的等效代码(有效)。谁能纠正我对 scipy.optimize.fmin_bfgs 的使用以匹配 OLS 或 R 结果?
import csv
import numpy as np
import scipy as sp
from scipy import optimize
class DataLine:
def __init__(self,row):
self.Y = row[0]
self.X = [1.0] + row[2:len(row)]
# 'Intercept','Food','Decor', 'Service', 'Price' and remove the name
def allDataLine(self):
return self.X + list(self.Y) # return operator.add(self.X,list(self.Y))
def xData(self):
return np.array(self.X,dtype="float64")
def yData(self):
return np.array([self.Y],dtype="float64")
def fnRSS(vBeta, vY, mX):
return np.sum((vY - np.dot(mX,vBeta))**2)
if __name__ == "__main__":
urlSheatherData = "/Hans/workspace/optimsGLMs/MichelinNY.csv"
# downloaded from "http://www.stat.tamu.edu/~sheather/book/docs/datasets/MichelinNY.csv"
reader = csv.reader(open(urlSheatherData), delimiter=',', quotechar='"')
headerTuple = tuple(reader.next())
dataLines = map(DataLine, reader)
Ys = map(DataLine.yData,dataLines)
Xs = map(DataLine.xData,dataLines)
# a check and an initial guess ...
vBeta = np.array([-1.5, 0.06, 0.04,-0.01, 0.002]).reshape(5,1)
print np.sum((Ys-np.dot(Xs,vBeta))**2)
print fnRSS(vBeta,Ys,Xs)
lsBetas = np.linalg.lstsq(Xs, Ys)
print lsBetas[1]
# prints the right numbers
print lsBetas[0]
optimizedBetas = sp.optimize.fmin_bfgs(fnRSS, x0=vBeta, args=(Ys,Xs))
# completely off ..
print optimizedBetas
优化的结果是:
Optimization terminated successfully.
Current function value: 6660.000006
Iterations: 276
Function evaluations: 448
[ 4.51296549e-01 -5.64005114e-06 -3.36618459e-06 4.98821735e-06
9.62197362e-08]
但它确实应该与lsBetas = np.linalg.lstsq(Xs, Ys)中取得的OLS结果相匹配:
[[-1.49209249]
[ 0.05773374]
[ 0.044193 ]
[-0.01117662]
[ 0.00179794]]
如果有用的话,这里是 R 代码(它还具有能够直接从 URL 读取的优点):
urlSheatherData = "http://www.stat.tamu.edu/~sheather/book/docs/datasets/MichelinNY.csv"
dfSheather = as.data.frame(read.csv(urlSheatherData, header = TRUE))
vY = as.matrix(dfSheather['InMichelin'])
mX = as.matrix(dfSheather[c('Service','Decor', 'Food', 'Price')])
mX = cbind(1, mX)
fnRSS = function(vBeta, vY, mX) { return(sum((vY - mX %*% vBeta)^2)) }
vBeta0 = rep(0, ncol(mX))
optimLinReg = optim(vBeta0, fnRSS,mX = mX, vY = vY, method = 'BFGS', hessian=TRUE)
print(optimLinReg$par)
【问题讨论】:
-
顺便说一句,您的模块版本和系统架构是什么?我没有成功地使用您的代码对所有可用组合进行优化(实际上有很多组合)。全部注册
Warning: Desired error not necessarily achieved due to precision loss. -
我正在使用 Enthought Canopy Python 2.7.3 | Mac OSX 10.6.8 上为 64 位,numpy 上为 1.7.1,scipy 上为 0.12.0。
-
This question 是相关的,基本上表明这是vBeta的强制转换问题。
标签: python r numpy scipy mathematical-optimization