【问题标题】:Statsmodels API OLS regression: ValueError -> shapes (95, 3) and (4,) are not alignedStatsmodels API OLS 回归:ValueError -> 形状 (95, 3) 和 (4,) 未对齐
【发布时间】:2022-08-03 11:09:50
【问题描述】:
def fit_linear_regression(X, y):
    X = sm.add_constant(X)
    est = sm.OLS(y, X)
    est = est.fit()
    return est

print(X_train.shape) // outputs (604, 41)
print(X_test.shape) // outputs (95, 41)

model = fit_linear_regression(X_train.iloc[:, [0, 1, 2]], y_train)

model.predict(X_test.iloc[:, [0, 1, 2]])

当我运行此脚本时,出现以下错误

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

当我不选择任何列而只包含整个数据框时,它与 shapes(95, 41) and (42,) 未对齐时相同。这到底是怎么回事?

X_train、y_train 和 y_test 是熊猫数据帧。

  • 问题是在将X_test 数据传递给predict() 函数之前,您没有向其添加常量。请参阅文档中的 this 示例,展示如何正确执行此操作。

标签: pandas statsmodels


【解决方案1】:

正如@AlexK 在 cmets 中指出的那样,您需要将截距(或常数)添加到您的测试数据中。在您的函数中,您执行了以下步骤:

X = sm.add_constant(X)

这用于拟合模型,因此模型需要 4 列而不是 3 列。

使用示例:

import pandas as pd
import numpy as np
import statsmodels.api as sm

X_train = pd.DataFrame(
    np.random.normal(0,1,(604,41)),
    columns = ["v" + str(i) for i in range(41)]
    )

X_test = pd.DataFrame(
    np.random.normal(0,1,(95,41)),
    columns = ["v" + str(i) for i in range(41)]
)

y_train = np.random.normal(0,1,(604,))
y_test = np.random.normal(0,1,(95,))

拟合和预测:

def fit_linear_regression(X, y):
    X = sm.add_constant(X)
    est = sm.OLS(y, X)
    est = est.fit()
    return est

model = fit_linear_regression(X_train.iloc[:, [0, 1, 2]], y_train)

model.predict(sm.add_constant(X_test.iloc[:, [0, 1, 2]]))

由于您使用的是数据框,我希望有正确的列名,因此您可以考虑使用公式界面(请参阅the help page),只需添加一个调整以将所有列包含在您的输入中,请参阅此post

import statsmodels.formula.api as smf

def formula_linear_regression(X, y):
    formula = "y ~ " + "+".join(X.columns)
    df = X.copy()
    df['y'] = y
    est = smf.ols(formula=formula, data=X)
    est = est.fit()
    return est

model2 = formula_linear_regression(X_train.iloc[:, [0, 1, 2]], y_train)

model.predict(X_test.iloc[:, [0, 1, 2]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2017-05-07
    • 2016-05-04
    • 2022-12-07
    相关资源
    最近更新 更多