【问题标题】:Bayesian using PyMC3: PatsyError使用 PyMC3 的贝叶斯:PatsyError
【发布时间】:2020-02-01 09:36:08
【问题描述】:


我正在尝试使用 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 中,它工作得很好,但在这种情况下,年龄也包含在公式中,这不应该是因为年龄是因变量而其他是自变量。
知道如何解决吗?
提前致谢

【问题讨论】:

    标签: python bayesian pymc3 pymc


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2018-12-01
    • 1970-01-01
    • 2016-09-15
    • 2020-09-25
    • 2020-08-09
    相关资源
    最近更新 更多