线性回归-如何在python中对站点进行最小二乘排序



我有10个气候站的降水数据和DEM。

我做了一个线性回归如下:

DEM = [200, 300, 400, 500, 600, 300, 200, 100, 50, 200]
Prep = [50, 95, 50, 59, 99, 50, 23, 10, 10, 60]
X = DEM   #independent variable
Y = Prep  #dependent variable
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

但是现在我想给这些站点增加权重,比如:

Weight = [0.3, 0.1, 0.1, 0.1, 0.2, 0.05, 0.05, 0.05, 0.05, 0.05]

图表如下http://ppt.cc/XXrEv

我找到了加权最小二乘法来做这件事,但我想知道它是如何以及为什么工作的,或者它是否错误。

import numpy as np
import statsmodels.api as sm
Y = [1, 3, 4, 5, 2, 3, 4]
X = range(1, 8)
X = sm.add_constant(X)
wls_model = sm.WLS(Y, X, weights=range(1, 8))
results = wls_model.fit()
results.params

答案:

import numpy as np
import statsmodels.api as sm
start_time = time.time()
alist=[2,4,6]
DEM=[200,300,400,500,300,600]
PRE=[20,19,18,20,21,22,30,23]
A_DEM=[]
A_PRE=[]
W=[]
for a in alist:
    A_DEM.append(DEM[a-1])
    A_PRE.append(PRE[a-1])
    W.append(1)
X = sm.add_constant(A_DEM)
Y = A_PRE
wls_model = sm.WLS(Y,X, weights=W).fit()
print wls_model.params[0] #  intercept
print wls_model.params[1] #  slope
print wls_model.rsquared  #rsquared
print wls_model.summary()

我发现WLS会自动归一化。所以你可以直接添加权重

最新更新