【问题标题】:Fitting a model using Polynomial Regression doesn't allow to predict because of the shape issue由于形状问题,使用多项式回归拟合模型不允许进行预测
【发布时间】:2018-03-27 12:01:17
【问题描述】:

我写了下面的代码来使用多项式回归。能够拟合模型,但无法预测!!

def polynomial_function(power=5, random_state=9):
    global X_train
    global y_train

    X_train =  X_train[['item_1','item_2','item_3','item_4']]
    rng = np.random.RandomState(random_state)
    poly = PolynomialFeatures(degree=power, include_bias=False)
    linreg = LinearRegression(normalize=True)
    new_X_train = poly.fit_transform(X_train)
    linreg.fit(new_X_train, y_train)
    new_x_test  = np.array([4, 5, 6, 7]).reshape(1, -1)
    print linreg.predict(new_x_test)
    return linreg

linreg = polynomial_function()

收到以下错误消息:

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

错误发生在这里,

new_x_test  = np.array([4, 5, 6, 7]).reshape(1, -1)
print linreg.predict(new_x_test)

我找到了 new_X_train = (923, 125) 的形状 和 new_x_test 的形状 = (1, 4)

这有什么关系?

当我尝试使用 (1, 4) 的形状进行预测时,算法是否会尝试将其转换为不同的形状?

它是否试图找出测试数据的 5 次多项式?

我正在尝试学习多项式回归,谁能解释发生了什么?

【问题讨论】:

    标签: python machine-learning scikit-learn data-science


    【解决方案1】:
    from sklearn.pipeline import Pipeline
    from sklearn.linear_model import LinearRegression
    from sklearn.preprocessing import PolynomialFeatures
    
    pipeline = Pipeline([
        ('poly', PolynomialFeatures(degree=5, include_bias=False)),
        ('linreg', LinearRegression(normalize=True))
        ])
    
    pipeline.fit(X_train, y_train)
    pipeline.predict(np.array([4, 5, 6, 7]).reshape(1, -1))
    

    【讨论】:

    • 拟合模型后实际上返回“linreg”。其他人使用 model=polynomial_function(); 调用我的模型model.predict(np.array([4, 5, 6, 7]).reshape(1, -1)); , 我怎样才能在我的函数中处理这个?有什么解决办法吗?
    • 为什么new_x_test 在你的函数中?如果您的目标是返回模型然后用于预测,为什么您的示例显示您在函数内部进行预测?
    • 为了简单起见,我放了 new_x_test。我正在测试该功能。我认为当“new_x_test”在函数之外时我可以应用该解决方案。但现在我不能。如果“new_x_test”来自外部,您能否提出一个解决方案,例如:model.predict(np.array([4, 5, 6, 7]).reshape(1, -1))
    • 为什么会给出不同的输出!!我们如何在这里使用 RandomState()?
    猜你喜欢
    • 2021-12-26
    • 2018-12-15
    • 2014-11-27
    • 2021-11-04
    • 2019-03-27
    • 2017-12-23
    • 2018-08-03
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多