python - 使用 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 中,它工作得很好,但在这种情况下,年龄也包含在公式中,这不应该是因为年龄是因变量,而其他是自变量。
知道如何解决吗?
提前致谢
解决方案
要使用该pm.GLM.from_formula()
方法,DataFramedata
参数必须包含所有变量(预测器和响应)。修改当前代码的一种简单方法是重新附加响应变量:
pm.GLM.from_formula(Formula, data=pd.concat([X_train, y_train], axis=1), family=f)
推荐阅读
- sdn - 哪个 dpdk 版本适合 --- Intel Corporation "82541PI" (NIC) Gigabit Ethernet Controller (rev 05) 我在 ubuntu 18.04 上运行 dpdk
- apache-spark - 为什么火花重新分区会增加大小(数据量)
- html - 在 Bootstrap 3 中,如何每行只有五个图标?
- python - 如何更改matplotlib图的颜色条上大小的字体大小
- node.js - 无法让 NodeJS 将任何内容写入可写流
- python - 将 Google 搜索结果过滤为 Python 中的相关内容
- javascript - 我们可以在 a 上使用类吗