我应该在scikitlearn中使用多项式回归的特征缩放吗?

2024-09-29 17:54:53 发布

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

我一直在玩套索回归多项式函数使用下面的代码。我的问题是,我是否应该将特征缩放作为套索回归的一部分(当试图拟合多项式函数时)。我在下面粘贴的代码中列出的R^2结果和绘图表明没有。感谢任何关于为什么不是这样的建议,或者我是否从根本上塞住了什么东西。提前谢谢你的建议。在

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


np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10


X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

def answer_regression():
    from sklearn.preprocessing import PolynomialFeatures
    from sklearn.linear_model import Lasso, LinearRegression
    from sklearn.metrics.regression import r2_score
    from sklearn.preprocessing import MinMaxScaler
    import matplotlib.pyplot as plt
    scaler = MinMaxScaler()
    global X_train, X_test, y_train, y_test

    degrees = 12
    poly = PolynomialFeatures(degree=degrees)
    X_train_poly = poly.fit_transform(X_train.reshape(-1,1))
    X_test_poly = poly.fit_transform(X_test.reshape(-1,1))

    #Lasso Regression Model
    X_train_scaled = scaler.fit_transform(X_train_poly)
    X_test_scaled = scaler.transform(X_test_poly)

    #No feature scaling
    linlasso = Lasso(alpha=0.01, max_iter = 10000).fit(X_train_poly, y_train)
    y_test_lassopredict = linlasso.predict(X_test_poly)
    Lasso_R2_test_score = r2_score(y_test, y_test_lassopredict)

    #With feature scaling
    linlasso = Lasso(alpha=0.01, max_iter = 10000).fit(X_train_scaled, y_train)
    y_test_lassopredict_scaled = linlasso.predict(X_test_scaled)
    Lasso_R2_test_score_scaled = r2_score(y_test, y_test_lassopredict_scaled)

    %matplotlib notebook
    plt.figure()

    plt.scatter(X_test, y_test, label='Test data')
    plt.scatter(X_test, y_test_lassopredict, label='Predict data - No Scaling')
    plt.scatter(X_test, y_test_lassopredict_scaled, label='Predict data - With Scaling')

    return (Lasso_R2_test_score, Lasso_R2_test_score_scaled)

answer_regression()```

Tags: fromtestimportnptransformtrainpltrandom

热门问题