【问题标题】:Sklearn: Linear Regression with Polyfeature yields shapes not alignedSklearn:具有多特征的线性回归产生未对齐的形状
【发布时间】:2019-08-27 20:39:30
【问题描述】:

我想用sklearn中的Linear RegressionPoly Features来预测100个数据点的y值,即np.linspace(0, 10, 100)

数据:

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

好的,所以到目前为止我所做的实际上在正常的Linear Regression 下效果很好,但是当我尝试使用Polynomial Features 来尝试一些新模型时,效果并不好。

效果很好:

pre_result = []
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)
linreg = LinearRegression().fit(X_train.reshape(-1, 1), y_train)
pre_result.append(linreg.predict(np.linspace(0, 10, 100).reshape(-1, 1)))

这会产生错误:

third = PolynomialFeatures(degree=3)
X_third = third.fit_transform(x.reshape(-1, 1))
X_train, X_test, y_train, y_test = train_test_split(X_third, y, random_state=0)
polyreg = LinearRegression().fit(X_train, y_train)
pre_result.append(polyreg.predict(np.linspace(0, 10, 100).reshape(-1, 1)))

错误:

ValueError: shapes (100,1) and (4,) not aligned: 1 (dim 1) != 4 (dim 0)

如果我使用PolynomialFeatures(degree=6) 而不是degree=3,它将显示ValueError: shapes (100,1) and (7,) not aligned: 1 (dim 1) != 7 (dim 0)。这完全让我感到困惑。

尽管如此,以下示例运行良好:

X_F1, y_F1 = make_friedman1(n_samples = 100,
                       n_features = 7, random_state=0)
poly = PolynomialFeatures(degree=2)
X_F1_poly = poly.fit_transform(X_F1)

X_train, X_test, y_train, y_test = train_test_split(X_F1_poly, y_F1,
                                               random_state = 0)
linreg = LinearRegression().fit(X_train, y_train)
predict = linreg.predict(X_test)

感谢有人对此提供任何见解。提前致谢。

【问题讨论】:

    标签: python scikit-learn linear-regression


    【解决方案1】:

    问题出在你的 sn-p 的最后一行。这里

    polyreg.predict(np.linspace(0, 10, 100).reshape(-1, 1))
    

    您传递一些“原始”输入的地方 - x 变量:形状为 (100,1) 的东西。这意味着您有 100 个观测值,每个观测值都有一个变量。

    您的模型 (polyreg) 预计每个观测值都有 4 个变量(3 次多项式的系数)。

    解决方案 1

    你可以这样做:

    polyreg.predict( third.transform( np.linspace(0, 10, 100).reshape(-1, 1) ))
    

    可能更好的解决方案:

    但可能更好的是this example 中的方法,它使用Pipeline

    poly3_model = Pipeline(
        [('poly', PolynomialFeatures(degree=3)), 
         ('linear', LinearRegression())])
    
    X_train, X_test, y_train, y_test = train_test_split(x.reshape(-1, 1), y.reshape(-1, 1), random_state=0)
    
    poly3_model.fit( X_train, y_train )
    test_prediction = poly3_model.predict( X_test )
    another_prediction = poly3_model.predict( np.linspace(0, 10, 100).reshape(-1, 1))
    

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2018-01-02
      • 2021-05-14
      • 2020-05-19
      • 2017-05-07
      • 2020-03-09
      • 2020-05-27
      • 2017-10-24
      • 2020-02-19
      相关资源
      最近更新 更多