我试图预测波士顿住房价格。当我选择多项式回归度1或2时,R2分数还可以。但是3度会降低R2分数。

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
from sklearn.datasets import load_boston
boston_dataset = load_boston()
dataset = pd.DataFrame(boston_dataset.data, columns = boston_dataset.feature_names)
dataset['MEDV'] = boston_dataset.target

X = dataset.iloc[:, 0:13].values
y = dataset.iloc[:, 13].values.reshape(-1,1)

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 2)   # <-- Tuning to 3
X_poly = poly_reg.fit_transform(X_train)
poly_reg.fit(X_poly, y_train)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y_train)

y_pred = lin_reg_2.predict(poly_reg.fit_transform(X_test))

from sklearn.metrics import r2_score
print('Prediction Score is: ', r2_score(y_test, y_pred))


输出(度= 2):

Prediction Score is:  0.6903318065831567


输出(度= 3):

Prediction Score is:  -12898.308114085281

最佳答案

这就是所谓的过拟合模型。您正在做的是将模型完美地拟合到训练集上,这会导致较大的方差。当您将假设很好地拟合到训练集上时,它将在测试集上失败。您可以使用r2_score(X_train,y_train)检查r2_score以获取训练集。会很高。您需要在偏差和方差之间权衡取舍。

您可以尝试使用其他回归模型(例如套索和山脊),并可以使用它们的alpha值,以防您需要较高的r2_score。为了更好地理解,我正在制作一张图像,该图像将显示假设线如何在增加多项式的阶数上受到影响。
python - 多项式回归度增加误差-LMLPHP

关于python - 多项式回归度增加误差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57234927/

10-12 16:42
查看更多