【发布时间】:2016-02-17 05:00:06
【问题描述】:
在statsmodels 0.6.1 版中,我无法从least squares fits 获得合理的预测行为。它似乎没有提供合理的价值。
考虑以下数据
import numpy as np
xx = np.array([1.1,2.2,3.3,4.4]) # Independent variable
XX = sm.add_constant(xx) # Include constant for matrix fitting in statsmodels
yy = np.array([2,1,5,6]) # Dependent variable
ww = np.array([0.1,1,3,0.5]) # Weights to try
wn = ww/ww.sum() # Normalized weights
zz = 1.9 # Independent variable value to predict for
我们可以使用numpy 进行加权拟合和预测
np_unw_value = np.polyval(np.polyfit(xx, yy, deg=1, w=1+0*ww), zz)
print("Unweighted fit prediction from numpy.polyval is {sp}".format(sp=np_unw_value))
我们发现预测值为 2.263636。
作为健全性检查,我们还可以查看 R 对此事的看法
import pandas as pd
import rpy2.robjects
from rpy2.robjects.packages import importr
import rpy2.robjects.pandas2ri
rpy2.robjects.pandas2ri.activate()
pdf = pd.DataFrame({'x':xx, 'y':yy, 'w':wn})
pdz = pd.DataFrame({'x':[zz], 'y':[np.Inf]})
rfit = rpy2.robjects.r.lm('y~x', data=pdf, weights=1+0*pdf['w']**2)
rpred = rpy2.robjects.r.predict(rfit, pdz)[0]
print("Unweighted fit prediction from R is {sp}".format(sp=rpred))
我们再次找到 2.263636 的预测。我的问题是我们确实没有从 statmodels OLS 获得该结果
import statsmodels.api as sm
from statsmodels.sandbox.regression.predstd import wls_prediction_std
owls = sm.OLS(yy, XX).fit()
sm_value_u, iv_lu, iv_uu = wls_prediction_std(owls, exog=np.array([[1,zz]]))
sm_unw_v = sm_value_u[0]
print("Unweighted OLS fit prediction from statsmodels.wls_prediction_std is {sp}".format(sp=sm_unw_v))
相反,我获得了一个值 1.695814(WLS() 发生了类似的事情)。要么存在错误,要么使用statsmodels 进行预测有一些太晦涩难懂的技巧,我无法找到。怎么回事?
【问题讨论】:
-
使用
predict进行预测:owls.predict(np.array([[1,zz]]))2.26363636 -
wls_prediction_std的第一个返回值是预测的标准误差,而不是预测本身。 -
搞定了......把它放在答案中,我会接受它。
标签: python pandas statsmodels