如果您用sqrt(weight)乘以X和y,则可以计算加权最小二乘。您可以通过以下链接获取公式:
http://en.wikipedia.org/wiki/Linear_least_squares_%28mathematics%29#Weighted_linear_least_squares
这是一个例子:
准备数据:
import numpy as npnp.random.seed(0)N = 20X = np.random.rand(N, 3)w = np.array([1.0, 2.0, 3.0])y = np.dot(X, w) + np.random.rand(N) * 0.1
OLS:
from scipy import linalgw1 = linalg.lstsq(X, y)[0]print w1
输出:
[ 0.98561405 2.0275357 3.05930664]
WLS:
weights = np.linspace(1, 2, N)Xw = X * np.sqrt(weights)[:, None]yw = y * np.sqrt(weights)print linalg.lstsq(Xw, yw)[0]
输出:
[ 0.98799029 2.02599521 3.0623824 ]
通过统计模型检查结果:
import statsmodels.api as smmod_wls = sm.WLS(y, X, weights=weights)res = mod_wls.fit()print res.params
输出:
[ 0.98799029 2.02599521 3.0623824 ]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)