如何通过改变次数的多次多项式拟合进行循环

2024-10-07 16:31:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码功能正常,但我正在重复一个块几次,以改变多项式变量degree。我认为这可以而且应该循环以允许更快的迭代,但我不确定如何做到这一点。在下面的代码之前,我生成了我保留用于绘图的train_测试分割

经过几次迭代后,我在y_预测上使用np.vstack来创建单个数组

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

### degree 1 ####
poly1 = PolynomialFeatures(degree=1)
x1_poly = poly1.fit_transform(X_train)
                           
linreg1 = LinearRegression().fit(x1_poly, y_train)
pred_1= poly1.transform(x_prediction_data)
y1_poly_pred=linreg1.predict(pred_1)

### degree 3 #####
poly3 = PolynomialFeatures(degree=3)
x3_poly = poly3.fit_transform(X_train)
                                  
linreg3 = LinearRegression().fit(x3_poly, y_train)
pred_3= poly3.transform(x_prediction_data)
y3_poly_pred=linreg3.predict(pred_3)

#### ect... will make several other degree = 6, 9 ...

Tags: 代码fromimporttransformtrainsklearnfitx1
1条回答
网友
1楼 · 发布于 2024-10-07 16:31:33

我建议你在字典里收集答案,但为了简单起见,我创建了一个列表

代码在i上迭代,i是多项式的阶数。训练模型等,然后收集其答案

prediction_collector = []
for i in [1,3,6,9]:

    poly = PolynomialFeatures(degree=i)
    x_poly = poly.fit_transform(X_train)
                               
    linreg = LinearRegression().fit(x_poly, y_train)
    pred= poly.transform(x_prediction_data)
    y_poly_pred=linreg.predict(pred)

    # to collect the answer after each iteration/increase of degrees
    predictions_collector.append(y_poly_pred)

相关问题 更多 >