-1

我想使用 for-loop 和 count 对每三行进行线性回归,但我无法做到,因为我对线性回归的输入 (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

请帮我解决这个问题。

4

1 回答 1

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

于 2019-05-31T06:02:07.647 回答