如何使用 statsmodels.formula.api (python) 预测新值

How to predict new values using statsmodels.formula.api (python)

我使用以下方法从乳腺癌数据中训练逻辑模型,并且只使用一个特征 'mean_area'

from statsmodels.formula.api import logit
logistic_model = logit('target ~ mean_area',breast)
result = logistic_model.fit()

训练模型中有一个内置的预测方法。然而,这给出了所有训练样本的预测值。如下

predictions = result.predict()

假设我想要预测一个新值,例如 30 我如何使用训练模型来输出值? (而不是手动读取系数和计算)

您可以向 .predict() 模型提供新值,如本 notebook from the docs for a single observation. You can provide multiple observations as 2d array, for instance a DataFrame - see docs 中的输出 #11 所示。

由于您使用的是公式 API,您的输入需要采用 pd.DataFrame 的形式,以便列引用可用。在你的情况下,你可以使用类似 .predict(pd.DataFrame({'mean_area': [1,2,3]}).

statsmodels .predict() 在没有提供替代方案时仅将用于拟合的观察值用作默认值。

import statsmodels.formula.api as smf


model = smf.ols('y ~ x', data=df).fit()

# Predict for a list of observations, list length can be 1 to many..**
prediction = model.get_prediction(exog=dict(x=[5,10,25])) 
prediction.summary_frame(alpha=0.05)

我很难使用新的 pandas 数据框预测值。 所以我将要预测的数据添加到原始数据集post拟合

   y = data['price']
   x1 = data[['size', 'year']]
   data.columns
   #Index(['price', 'size', 'year'], dtype='object')
   x=sm.add_constant(x1)
   results = sm.OLS(y,x).fit()
   results.summary()
   ## predict on unknown data
   data = data.append(pd.DataFrame({'size': [853.0,777], 'year': [2012.0,2013], 'price':[None, None]}))
   data.tail()
   new_x = data.loc[data.price.isnull(), ['size', 'year']]
   results.predict(sm.add_constant(new_x))

此问题已得到解答,但希望对您有所帮助。

根据文档,第一个参数是“exog”。

exog : array_like, optional The values for which you want to predict

进一步说,

"If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object that contains numpy arrays.

If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array.

Row indices as in pandas data frames are supported, and added to the returned prediction"

from statsmodels.formula.api import logit

logistic_model = logit('target ~ mean_area',breast)
result = logistic_model.fit()

因此,您可以为 exog 参数提供一个 pandas 数据框(例如:df),该数据框应包含 mean_area 作为列。因为 'mean_area' 是预测变量或自变量。

predictions = logistic_model.predict(exog=df)