遍历三行,然后执行线性回归



我想只在两列中迭代三行,然后在迭代函数中,我在那三行中进行线性回归。所以

,迭代三行,做线性回归,迭代三行,做线性回归,等等。

我把数据输入放在这里.我想迭代"年份"和"值"列中的三行,然后进行线性回归,然后迭代"年份"和"值"列中的三行,然后进行线性回归,依此类推。

我已经尝试了此代码,但出现错误

year=data_['Year']
value=data_['Value']
i=0
count=0
for a,b in zip(year,value):
    print(a,b)
    count = count+1
    if count%3 == 0:
        x=np.array([[a]])
        y=np.array([[b]])
        reg=linear_model.LinearRegression()
        x_train,x_test,y_train,y_test=train_test_split(x,y,test_size = 0.2 ,random_state=3)
        reg.fit(x_train,y_train)
        y4=4*reg.coef_ + reg.intercept_
        plt.scatter(x,y)
        plt.show()
        print(reg.coef_)
        print("R^2 : ",reg.score(x, y))
        print("Equation : 4 *", reg.coef_, "+", reg.intercept_)
        print("Y4 : ", y4)
        print("====")

我希望每三行的输出会产生斜率、系数和方程。

如果你想每

组三年做一个简单的线性回归,试试这样的事情:

# Hardcoded input data for clarity
#all_years = data_['Year'].values
#all_values = data_['Value'].values
all_years = np.array([1,2,3,
                      1,2,3,
                      1,2,3,
                      1,2,3,
                      1,2,3])
all_values = np.array([  6.262008,   5.795994,   5.082662,
                       285.433511, 260.436601, 238.713124,
                         2.596145,   2.508278,   2.67997, 
                        90.823952,  91.0962765, 93.821241,
                        19.677544,  18.464335,  18.035489])

w = 3  # window size
for i in range(len(all_years)//w):
    years = all_years[w*i : w*(i+1)].reshape(-1,1)
    values = all_values[w*i : w*(i+1)].reshape(-1,1)
    #print(years, values)
    reg=linear_model.LinearRegression()
    reg.fit(years, values)
    y=(w+1)*reg.coef_ + reg.intercept_
    plt.scatter(years, values)
    plt.show()
    print(reg.coef_)
    print("R^2 : ",reg.score(years, values))
    print("Equation : (w+1) *", reg.coef_, "+", reg.intercept_)
    print("Y4 : ", y)
    print("====")

在这种情况下,长度将是 15 ,因此 for 循环将经过 i= 1, ..., 4 。然后我使用 numpy 的数组切片选择您想要的年份和值。

例如,对于 i=1,这将选择 [3*(1-1) : 3*1] = [0 : 3] ,正好给出前三行。然后,为了确保这适用于期望列向量的线性回归,我将数组重塑为由 1 列组成,.reshape(-1, 1) .

然后是随心所欲的训练和绘图问题。

对于更好阅读并避免手动索引问题的版本,您可能还需要查看more-itertools包。具体来说,在这种情况下,chunked方法可用于将数据拆分为固定长度的块,在本例中为 3:

from more_itertools import chunked
...
w = 3  # window size  
for years, values in zip(chunked(all_years, n=w), chunked(all_values, n=w)):
    years = years.reshape(-1,1)
    values = values.reshape(-1,1)
    #print(years, values)
    ...

最新更新