Python 3.x 如何在Python中对每三行进行线性回归?
我想使用for循环和count为每三行做一个线性回归,但我做不到,因为我对线性回归的输入(x&y)感到困惑 这是代码:Python 3.x 如何在Python中对每三行进行线性回归?,python-3.x,for-loop,count,linear-regression,Python 3.x,For Loop,Count,Linear Regression,我想使用for循环和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): prin
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
请帮我解决这个问题。如果我正确理解您的问题,您可以先查阅
确保您的输入
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.534075333335
实际上我不是这个意思。老实说,我每三排要找不同的y4。因此,我可以看到每三行中的模式。
x
和y
在循环中似乎没有变化。因此,回归的结果总是相同的。您的意思是使用a和b从数据中进行选择吗?但是很难测试这一点,因为在代码段数据中没有定义。@balleveryday是的,我想更改x和y,因此Y4的结果总是每三行不同。数据或输入为-->我认为,如果您创建以在不使用外部数据集的情况下重现问题,那么会更容易。