pymc3 - PyMC3:在模型规范中定义中心协变量
问题描述
早上好,
我正在学习 PyMC3 并开始,我生成了一些合成数据用于估计泊松回归。我很快意识到的一件事是,我需要在拟合模型之前使我的模型协变量为零均值和单位方差,以避免出现数值问题。我在 PyMC3 模型规范之外执行了规范化,这让我想知道是否有某种方法可以集成它?如果没有整合归一化,我就不得不从训练数据中估计协变量的均值和标准差,并确保我将相同的归一化应用于未来的测试数据。如果它可以成为模型本身的一部分,我会很高兴,这样我就不必总是应用这些外部操作。那可能吗?如果是这样,我会喜欢任何关于如何做到这一点的例子的指针。
谢谢!
克里斯
这是我一直在尝试的一个示例,有助于澄清我的问题。我想知道如何将协变量的规范化移动到代码块末尾的 PyMC3 模型规范中。
# Generate synthetic data
N = 10000
tree_height = []
wind_speed = []
event_count = []
for i in range(N):
tree_height.append(np.random.rayleigh(scale=10))
wind_speed.append(np.random.rayleigh(scale=5))
event_count.append(np.random.poisson(tree_height[-1] + wind_speed[-1] + 0.1*tree_height[-1]*wind_speed[-1]))
# Normalize the synthetic covariates to be zero mean, unit variance
mn_tree_height = np.mean(tree_height)
std_tree_height = np.std(tree_height)
mn_wind_speed = np.mean(wind_speed)
std_wind_speed = np.std(wind_speed)
tree_height = (tree_height-mn_tree_height) / std_tree_height
wind_speed = (wind_speed-mn_wind_speed) / mn_wind_speed
# Build the data frame
df = pd.DataFrame.from_dict({'tree_height': tree_height, 'wind_speed': wind_speed, 'event_count': event_count})
# Patsy model specification
fml = 'event_count ~ tree_height * wind_speed'
# Design matrices
(outcome,covars) = pt.dmatrices(fml, df, return_type='dataframe', NA_action='raise')
# Theano shared variables for mini-batch training and testing
wind_speed = shared(covars.wind_speed.values)
tree_height = shared(covars.tree_height.values)
ws_th = shared(covars['tree_height:wind_speed'].values)
# PyMC3 model specification
with pm.Model() as m:
b0 = pm.Normal('b0_intercept', mu=0, sigma=10)
b1 = pm.Normal('b1_wind_speed', mu=0, sigma=10)
b2 = pm.Normal('b2_tree_height', mu=0, sigma=10)
b3 = pm.Normal('b3_tree_height:wind_speed', mu=0, sigma=10)
theta = (b0 +
b1 * wind_speed +
b2 * tree_height +
b3 * ws_th)
y = pm.Poisson('outcome', mu=np.exp(theta), observed=outcome['event_count'].values)
解决方案
推荐阅读
- google-cloud-platform - GCP API 是否支持过滤列表对象?
- for-loop - 避免在 Kotlin 中使用 for 循环计算 Ints 的值
- c# - C#,没有 MemoryBarrier 的易失性读取?
- javascript - 使用 jest 作为 chai 期望样式的模块?
- php - Arcanedev\LaravelNestedSet\NodeTrait appendToNode() 错误
- css - 如何在不使用 React Native 中的 CSS 填充的情况下在 View 元素之间添加额外的空间?
- git - 如何在共享主机(cpanel)上部署私有 git repo
- java - 如何从kotlin接口访问java接口中定义的常量
- javascript - Hichcharts - 自定义图例 css 未显示在打印图表下载功能中
- symfony - 将数据添加到 JWT 刷新响应