- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我们有一个分层模型,其中来自不同站点的数据作为模型中的不同组,那么我们如何预测新组(我们以前没有见过的新站点)?例如使用以下逻辑回归模型:
from pymc3 import Model, sample, Normal, HalfCauchy,Bernoulli
import theano.tensor as tt
with Model() as varying_slope:
mu_beta = Normal('mu_beta', mu=0., sd=1e5)
sigma_beta = HalfCauchy('sigma_beta', 5)
a = Normal('a', mu=0., sd=1e5)
betas = Normal('b',mu=mu_beta,sd=sigma_beta,shape=(n_features,n_site))
y_hat = a + tt.dot(X_shared,betas[:,site_shared])
y_like = Bernoulli('y_like', logit_p=y_hat, observed=train_y)
拟合此模型后,我们可以使用以下方法对来自特定站点的新数据(即后验预测的样本)进行预测:
site_to_predict = 1
samples = 500
x = tt.matrix('X',dtype='float64')
new_site = tt.vector('new_site',dtype='int32')
n_samples = tt.iscalar('n_samples')
x.tag.test_value = np.empty(shape=(1,X.shape[1]))
new_site.tag.test_value = np.empty(shape=(1,1))
_sample_proba = approx.sample_node(varying_slope.y_like.distribution.p,
size=n_samples,
more_replacements={X_shared: x,site_shared:new_site})
sample_proba = theano.function([x,new_site,n_samples], _sample_proba)
pred_test = sample_proba(test_X.reshape(1,-1),np.array(site_to_predict).reshape(-1),samples)
但是如果我们有一个新的未见过的站点,从后验预测分布中采样的正确方法是什么?
最佳答案
我只是从 pymc discourse thread 复制我的答案如果有人偶然遇到这个问题或另一个类似的问题。
首先,请注意您正在使用的居中分层参数化1,它可能会导致拟合时出现分歧和困难。
话虽这么说,您的模型看起来或多或少像 GLM,具有跨功能和站点共享先验随机变量 mu_beta 和 sigma_beta。一旦你获得了这两者的后验分布,你的预测应该类似于
y_hat = a + dot(X_shared, Normal(mu=mu_beta, sigma=sigma_beta))
y_like = Bernoulli('y_like', logit_p=y_hat)
因此,我们的目标是实现这一目标。
我们始终推荐样本外后验预测检查的方式是使用 theano.shared。我将使用一种不同的方法,其灵感来自于作为 pymc4 核心设计理念的函数式 API。我不会讨论 pymc3 和 pymc4 的骨架之间的许多差异,但我开始更多地使用工厂函数来获取模型实例。我没有尝试使用 theano.shared 定义模型内部的内容,而是使用新数据创建一个新模型并从中提取后验预测样本。我最近刚刚在这里发布了相关内容。
这个想法是使用训练数据创建模型并从中采样以获得跟踪。然后,您必须从跟踪中提取与看不见的站点共享的分层部分:mu_beta、sigma_beta 和 a。最后,您使用测试站点的新数据创建一个新模型,并使用保存 mu_beta、sigma_beta 和部分训练轨迹的字典列表从后验预测中进行采样。这是一个独立的示例
import numpy as np
import pymc3 as pm
from theano import tensor as tt
from matplotlib import pyplot as plt
def model_factory(X, y, site_shared, n_site, n_features=None):
if n_features is None:
n_features = X.shape[-1]
with pm.Model() as model:
mu_beta = pm.Normal('mu_beta', mu=0., sd=1)
sigma_beta = pm.HalfCauchy('sigma_beta', 5)
a = pm.Normal('a', mu=0., sd=1)
b = pm.Normal('b', mu=0, sd=1, shape=(n_features, n_site))
betas = mu_beta + sigma_beta * b
y_hat = a + tt.dot(X, betas[:, site_shared])
pm.Bernoulli('y_like', logit_p=y_hat, observed=y)
return model
# First I generate some training X data
n_features = 10
ntrain_site = 5
ntrain_obs = 100
ntest_site = 1
ntest_obs = 1
train_X = np.random.randn(ntrain_obs, n_features)
train_site_shared = np.random.randint(ntrain_site, size=ntrain_obs)
new_site_X = np.random.randn(ntest_obs, n_features)
test_site_shared = np.zeros(ntest_obs, dtype=np.int32)
# Now I generate the training and test y data with a sample from the prior
with model_factory(X=train_X,
y=np.empty(ntrain_obs, dtype=np.int32),
site_shared=train_site_shared,
n_site=ntrain_site) as train_y_generator:
train_Y = pm.sample_prior_predictive(1, vars=['y_like'])['y_like'][0]
with model_factory(X=new_site_X,
y=np.empty(ntest_obs, dtype=np.int32),
site_shared=test_site_shared,
n_site=ntest_site) as test_y_generator:
new_site_Y = pm.sample_prior_predictive(1, vars=['y_like'])['y_like'][0]
# The previous part is just to get some toy data to fit
# Now comes the important parts. First training
with model_factory(X=train_X,
y=train_Y,
site_shared=train_site_shared,
n_site=ntrain_site) as train_model:
train_trace = pm.sample()
# Second comes the hold out data posterior predictive
with model_factory(X=new_site_X,
y=new_site_Y,
site_shared=test_site_shared,
n_site=ntrain_site) as test_model:
# We first have to extract the learnt global effect from the train_trace
df = pm.trace_to_dataframe(train_trace,
varnames=['mu_beta', 'sigma_beta', 'a'],
include_transformed=True)
# We have to supply the samples kwarg because it cannot be inferred if the
# input trace is not a MultiTrace instance
ppc = pm.sample_posterior_predictive(trace=df.to_dict('records'),
samples=len(df))
plt.figure()
plt.hist(ppc['y_like'], 30)
plt.axvline(new_site_Y, linestyle='--', color='r')
当然,我不知 Prop 体应该把什么样的数据作为你的X_shared、site_shared或train_y,所以我只是在代码开头编造了一些无意义的玩具数据,你应该用你的实际数据替换它.
关于python - 我们如何在 PyMC3 的分层模型中预测新的看不见的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54295691/
我正在使用 R 预测包拟合模型,如下所示: fit <- auto.arima(df) plot(forecast(fit,h=200)) 打印原始数据框和预测。当 df 相当大时,这
我正在尝试预测自有住房的中位数,这是一个行之有效的例子,给出了很好的结果。 https://heuristically.wordpress.com/2011/11/17/using-neural-ne
type="class"函数中的type="response"和predict有什么区别? 例如: predict(modelName, newdata=testData, type = "class
我有一个名为 Downloaded 的文件夹,其中包含经过训练的 CNN 模型必须对其进行预测的图像。 下面是导入图片的代码: import os images = [] for filename i
关于预测的快速问题。 我尝试预测的值是 0 或 1(它设置为数字,而不是因子),因此当我运行随机森林时: fit , data=trainData, ntree=50) 并预测: pred, data
使用 Python,我尝试使用历史销售数据来预测产品的 future 销售数量。我还试图预测各组产品的这些计数。 例如,我的专栏如下所示: Date Sales_count Department It
我是 R 新手,所以请帮助我了解问题所在。我试图预测一些数据,但预测函数返回的对象(这是奇怪的类(因子))包含低数据。测试集大小为 5886 obs。 160 个变量,当预测对象长度为 110 时..
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 6 年前。 Improve this qu
下面是我的神经网络代码,有 3 个输入和 1 个隐藏层和 1 个输出: #Data ds = SupervisedDataSet(3,1) myfile = open('my_file.csv','r
我正在开发一个 Web 应用程序,它具有全文搜索功能,可以正常运行。我想对此进行改进并向其添加预测/更正功能,这意味着如果用户输入错误或结果为 0,则会查询该输入的更正版本,而不是查询结果。基本上类似
我对时间序列还很陌生。 这是我正在处理的数据集: Date Price Location 0 2012-01-01 1771.0
我有许多可变长度的序列。对于这些,我想训练一个隐马尔可夫模型,稍后我想用它来预测(部分)序列的可能延续。到目前为止,我已经找到了两种使用 HMM 预测 future 的方法: 1) 幻觉延续并获得该延
我正在使用 TensorFlow 服务提供初始模型。我在 Azure Kubernetes 上这样做,所以不是通过更标准和有据可查的谷歌云。 无论如何,这一切都在起作用,但是我感到困惑的是预测作为浮点
我正在尝试使用 Amazon Forecast 进行一些测试。我现在尝试了两个不同的数据集,它们看起来像这样: 13,2013-03-31 19:25:00,93.10999 14,2013-03-3
使用 numpy ndarray大多数时候我们不需要担心内存布局的问题,因为结果并不依赖于它。 除非他们这样做。例如,考虑这种设置 3x2 矩阵对角线的稍微过度设计的方法 >>> a = np.zer
我想在同一个地 block 上用不同颜色绘制多个预测,但是,比例尺不对。我对任何其他方法持开放态度。 可重现的例子: require(forecast) # MAKING DATA data
我正在 R 中使用 GLMM,其中混合了连续变量和 calcategories 变量,并具有一些交互作用。我使用 MuMIn 中的 dredge 和 model.avg 函数来获取每个变量的效果估计。
我能够在 GUI 中成功导出分类器错误,但无法在命令行中执行此操作。有什么办法可以在命令行上完成此操作吗? 我使用的是 Weka 3.6.x。在这里,您可以右键单击模型,选择“可视化分类器错误”并从那
我想在同一个地 block 上用不同颜色绘制多个预测,但是,比例尺不对。我对任何其他方法持开放态度。 可重现的例子: require(forecast) # MAKING DATA data
我从 UCI 机器学习数据集库下载了一个巨大的文件。 (~300mb)。 有没有办法在将数据集加载到 R 内存之前预测加载数据集所需的内存? Google 搜索了很多,但我到处都能找到如何使用 R-p
我是一名优秀的程序员,十分优秀!