【问题标题】:How to get a quick predict value in OLS model?如何在 OLS 模型中快速获得预测值?
【发布时间】:2021-11-13 04:13:05
【问题描述】:

如何从我的 ols 模型中快速获得预测值。例如

import statsmodels.formula.api as sm

model = sm.ols(formula="price ~ size + year", data=df_c).fit()

model.predict([25,1990]) #(should return predicted price value)

当我运行 model.predict([25,1990]) 时如何获得预测值,其中 25 是大小,1990 是年份?

编辑:

我得到的错误是“PatsyError: predict 要求您在从模型进行预测时使用 DataFrame 使用公式 api 创建的。

patsy 返回的原始错误信息是: 错误评估因素:TypeError:列表索引必须是整数或切片,而不是 str'

有没有办法只运行 model.predict([25,1990]) 的简单代码

提前谢谢你!

【问题讨论】:

  • 运行model.predict([25,1990])时遇到什么错误?
  • 谢谢。在问题中更新了它。但它的 'PatsyError: predict 要求您在从使用公式 api 创建的模型进行预测时使用 DataFrame。 patsy 返回的原始错误信息是:Error evaluation factor: TypeError: list indices must be integers or slices, not str'

标签: python numpy regression linear-regression statsmodels


【解决方案1】:

您不能使用您提供的代码执行此操作,因为您使用的是statsmodels.formula.api。我能提供的最简单的解决方案是使用快速字典:

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

df_c = pd.DataFrame(np.random.randn(10, 3))
df_c.columns = ['price','size','year']
model = sm.ols(formula='price ~ size + year', data=df_c).fit()

model.predict({'size':25,'year':1990})[0]
-165.2345445772976

我创建了一个模拟数据框来证明它可以工作,但您只需要最后一行:model.predict({'size':25,'year':1990})[0]

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 2021-04-30
    • 2013-08-17
    • 2020-05-11
    • 2020-12-08
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多