简体   繁体   English

如何循环多个多项式拟合改变度数

[英]How to loop through multiple polynomial fits changing the degree

My code functions properly but I am repeating a block several times to vary the polynomial variable, degree.我的代码运行正常,但我多次重复一个块来改变多项式变量度。 I assume this can and should be looped to allow quicker iterations, but I'm not sure how to do it.我认为这可以而且应该循环以允许更快的迭代,但我不确定如何做到这一点。 Prior to the code below I generate the train_test split which I keep for plotting.在下面的代码之前,我生成了我保留用于绘图的 train_test 分割。

After several iterations, I use np.vstack on the y_predictions to create a single array.经过多次迭代,我在 y_predictions 上使用 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 ...

I would recommend collecting your answers in a dictionary, but I created a list for simplicity.我建议在字典中收集你的答案,但为了简单起见,我创建了一个列表。

The code iterates over i, which is the degree of your polynomials.代码迭代 i,这是多项式的次数。 Trains the model, etc..., then collects its answers.训练模型等等,然后收集它的答案。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM