使用Python进行多元多项式回归

时间:2019-02-26 18:31:39

标签: python scikit-learn regression

最近,我开始学习sklearn,numpy和pandas,并制作了用于多元线性回归的函数。我想知道,是否可以进行多元多项式回归?

这是我的多元多项式回归代码,它显示此错误:

in check_consistent_length " samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of samples: [8, 3]

你知道出什么问题吗?

import numpy as np
import pandas as pd
import xlrd
from sklearn import linear_model
from sklearn.model_selection import train_test_split

def polynomial_prediction_of_future_strenght(input_data, cement, blast_fur_slug,fly_ash,
                                              water, superpl, coarse_aggr, fine_aggr, days):

    variables = prediction_accuracy(input_data)[4]
    results = prediction_accuracy(input_data)[5]

    var_train, var_test, res_train, res_test = train_test_split(variables, results, test_size = 0.3, random_state = 4)

    Poly_Regression = PolynomialFeatures(degree=2)
    poly_var_train = Poly_Regression.fit_transform(var_train)
    poly_var_test = Poly_Regression.fit_transform(var_test)

    input_values = [cement, blast_fur_slug, fly_ash, water, superpl, coarse_aggr, fine_aggr, days]

    regression = linear_model.LinearRegression()
    model = regression.fit(poly_var_train, res_train)

    predicted_strenght = regression.predict([input_values])
    predicted_strenght = round(predicted_strenght[0], 2)

    score = model.score(poly_var_test, res_test)
    score = round(score*100, 2)


    print(prediction, score)

a = polynomial_prediction_of_future_strenght(data_less_than_28days, 260.9, 100.5, 78.3, 200.6, 8.6, 864.5, 761.5, 28)

1 个答案:

答案 0 :(得分:3)

您可以使用this sklearn模块将特征转换为多项式,然后在线性回归模型中使用这些特征。

from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model

poly = PolynomialFeatures(degree=2)
poly_variables = poly.fit_transform(variables)

poly_var_train, poly_var_test, res_train, res_test = train_test_split(poly_variables, results, test_size = 0.3, random_state = 4)

model = regression.fit(poly_var_train, res_train)
score = model.score(poly_var_test, res_test)

此外,在代码中,您正在整个数据集中训练模型,然后将其拆分为训练和测试。这意味着您的模型在训练时已经看到了您的测试数据。您需要先拆分,然后仅根据训练数据训练模型,然后在测试集上测试分数。我也包括了这些更改。 :)