首页 > 解决方案 > 使用 PyMC3 的贝叶斯:PatsyError

问题描述


我正在尝试使用 PyMC3 应用贝叶斯线性回归。
我想根据一些测量来预测年龄。
我找到了一个惊人的例子,并想将它与一些数据一起应用。
下面是代码。

import pandas as pd
import numpy as np
import pymc3 as pm
from sklearn.model_selection import train_test_split

data = pd.read_csv('data.csv')
X = data.drop(['User_ID','Gender','Age'], axis = 1)   # the features
Y = data['Age']  
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)
print(X_train.shape)
print(X_test.shape)

Formula = 'Age ~ ' + ' + '.join(['%s' % variable for variable in X_train.columns[0:]])
print(Formula)

with pm.Model() as normal_model:    
   f = pm.glm.families.Normal()    
   pm.GLM.from_formula(Formula, data = X_train, family = f)   
   normal_trace = pm.sample(draws=2000, chains = 2, tune = 500)

当我运行它时,我得到了这个错误

PatsyError: Error evaluating factor: NameError: name 'Age' is not defined
Age ~ Height + Weight + Duration + Heart_Rate + Body_Temp + Calories
^^^

但是,如果我将年龄保留在 X 中,它工作得很好,但在这种情况下,年龄也包含在公式中,这不应该是因为年龄是因变量,而其他是自变量。
知道如何解决吗?
提前致谢

标签: pythonbayesianpymc3pymc

解决方案


要使用该pm.GLM.from_formula()方法,DataFramedata参数必须包含所有变量(预测器和响应)。修改当前代码的一种简单方法是重新附加响应变量:

pm.GLM.from_formula(Formula, data=pd.concat([X_train, y_train], axis=1), family=f)

推荐阅读