如何在Python中对每三行进行线性回归?

时间:2019-05-31 04:26:26

标签: python-3.x for-loop count linear-regression

我想使用for循环和计数对每三行进行线性回归,但由于与线性回归的输入(x&y)混淆,我无法做到。

这是代码:

from sklearn.metrics import mean_squared_error, r2_score
import statsmodels.api as sm
import numpy as np

year=data_['Year']
value=data_['Value']
count=0
for a,b in zip(year,value):
    print(a,b) 
    count = count+1[input][1]
    window_type='rolling'

    if count%3 == 0 :
        x=data_.loc[0:3,['Year']]
        y=data_.loc[0:3,['Value']]

        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,y)

        y4=4*reg.coef_ + reg.intercept_

        print("Equation : 4 *", reg.coef_, "+", reg.intercept_)
        print("Y4 : ", y4)
        print("====")

实际结果:

1 6.262008
2 5.795994
3 5.082562
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
1 285.433511
2 260.43560099999996
3 238.71312400000002
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
1 2.595145
2 2.508278
3 2.67997
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====

我想要的输出是: 每三行得出不同的Y4

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则可以先查阅'sklearn.linear_model.LinearRegression.fit'的正式文档
确保您的输入reg.fit(X, y)是numpy.ndarray类型。明确一点,

X = np.array([1, 2, 3]).reshape(3,1)
y = np.array([6.262008, 5.795994, 5.082562])
reg=linear_model.LinearRegression()
reg.fit(X,y)
y4=4*reg.coef_ + reg.intercept_
print(np.squeeze(y4))

应该返回,

  

4.534075333333335