本文整理汇总了Python中pymc3.Model方法的典型用法代码示例。如果您正苦于以下问题:Python pymc3.Model方法的具体用法?Python pymc3.Model怎么用?Python pymc3.Model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymc3
的用法示例。
在下文中一共展示了pymc3.Model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: model
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def model(profiles, comparisons, selections, sample=2500, alpha_prior_std=10):
all_attributes = pd.get_dummies(profiles).columns
profiles_dummies = pd.get_dummies(profiles, drop_first=True)
choices = pd.concat({profile: profiles_dummies.loc[comparisons[profile]].reset_index(drop=True) for profile in comparisons.columns}, axis=1)
respondants = selections.columns
n_attributes_in_model = profiles_dummies.shape[1]
n_participants = selections.shape[1]
with pm.Model():
# https://www.sawtoothsoftware.com/download/ssiweb/CBCHB_Manual.pdf
# need to include the covariance matrix as a parent of `partsworth`
alpha = pm.Normal('alpha', 0, sd=alpha_prior_std, shape=n_attributes_in_model, testval=np.random.randn(n_attributes_in_model))
partsworth = pm.MvNormal("partsworth", alpha, tau=np.eye(n_attributes_in_model), shape=(n_participants, n_attributes_in_model))
cs = [_create_observation_variable(selection, choices, partsworth[i, :]) for i, (_, selection) in enumerate(selections.iteritems())]
trace = pm.sample(sample)
return transform_trace_to_individual_summary_statistics(trace, respondants, profiles_dummies.columns, all_attributes)
示例2: fit
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def fit(self, X, Y, n_samples=10000, tune_steps=1000, n_jobs=4):
with pm.Model() as self.model:
# Priors
std = pm.Uniform("std", 0, self.sps, testval=X.std())
beta = pm.StudentT("beta", mu=0, lam=self.sps, nu=self.nu)
alpha = pm.StudentT("alpha", mu=0, lam=self.sps, nu=self.nu, testval=Y.mean())
# Deterministic model
mean = pm.Deterministic("mean", alpha + beta * X)
# Posterior distribution
obs = pm.Normal("obs", mu=mean, sd=std, observed=Y)
## Run MCMC
# Find search start value with maximum a posterior estimation
start = pm.find_MAP()
# sample posterior distribution for latent variables
trace = pm.sample(n_samples, njobs=n_jobs, tune=tune_steps, start=start)
# Recover posterior samples
self.burned_trace = trace[int(n_samples / 2):]
示例3: test_spec
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def test_spec(spec, kwargs):
with Model():
assert (
spec(**kwargs)((1, 1)).tag.test_value.shape
==
(1, 1)
)
assert (
spec(**kwargs)((10, 1)).tag.test_value.shape
==
(10, 1)
)
assert (
spec(**kwargs)((10, 1, 10)).tag.test_value.shape
==
(10, 1, 10)
)
示例4: main
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def main():
#load data
returns = data.get_data_google('SPY', start='2008-5-1', end='2009-12-1')['Close'].pct_change()
returns.plot()
plt.ylabel('daily returns in %');
with pm.Model() as sp500_model:
nu = pm.Exponential('nu', 1./10, testval=5.0)
sigma = pm.Exponential('sigma', 1./0.02, testval=0.1)
s = pm.GaussianRandomWalk('s', sigma**-2, shape=len(returns))
r = pm.StudentT('r', nu, lam=pm.math.exp(-2*s), observed=returns)
with sp500_model:
trace = pm.sample(2000)
pm.traceplot(trace, [nu, sigma]);
plt.show()
plt.figure()
returns.plot()
plt.plot(returns.index, np.exp(trace['s',::5].T), 'r', alpha=.03)
plt.legend(['S&P500', 'stochastic volatility process'])
plt.show()
示例5: __subclasshook__
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def __subclasshook__(cls, C):
if lasagne.layers.Layer in C.__mro__ or pm.Model in C.__mro__:
return True
else:
return False
示例6: bayes
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def bayes(layercls, stack=1):
try:
issubcls = issubclass(layercls, lasagne.layers.base.Layer)
except TypeError:
raise TypeError('{} needs to be a Layer subclass'
.format(layercls))
if issubcls:
if type(layercls) is LayerModelMeta:
raise TypeError('{} is already bayesian'
.format(layercls))
else:
@six.add_metaclass(LayerModelMeta)
class BayesianAnalog(layercls, pm.Model):
pass
frm = inspect.stack()[stack]
mod = inspect.getmodule(frm[0])
if mod is None:
modname = '__main__'
else:
modname = mod.__name__
BayesianAnalog.__module__ = modname
BayesianAnalog.__doc__ = layercls.__doc__
BayesianAnalog.__name__ = layercls.__name__
return BayesianAnalog
else:
raise TypeError('{} needs to be a Layer subclass'
.format(layercls))
示例7: find_parent
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def find_parent(layer):
candidates = get_all_layers(layer)[::-1]
found = None
for candidate in candidates:
if isinstance(candidate, pm.Model):
found = candidate
break
return found
示例8: test_shape
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def test_shape(self):
spec = DistSpec(Normal, mu=0, sd=1)
spec2 = DistSpec(Normal, mu=0, sd=DistSpec(Lognormal, 0, 1))
with Model('layer'):
var = spec((100, 100), 'var')
var2 = spec2((100, 100), 'var2')
assert (var.init_value.shape == (100, 100))
assert (var.name.endswith('var'))
assert (var2.init_value.shape == (100, 100))
assert (var2.name.endswith('var2'))
示例9: built_model
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def built_model(self):
"""
Initialise :class:`pymc3.Model` depending on problem composites,
geodetic and/or seismic data are included. Composites also determine
the problem to be solved.
"""
logger.info('... Building model ...\n')
pc = self.config.problem_config
with Model() as self.model:
self.rvs, self.fixed_params = self.get_random_variables()
self.init_hyperparams()
total_llk = tt.zeros((1), tconfig.floatX)
for datatype, composite in self.composites.items():
if datatype in bconfig.modes_catalog[pc.mode].keys():
input_rvs = weed_input_rvs(
self.rvs, pc.mode, datatype=datatype)
fixed_rvs = weed_input_rvs(
self.fixed_params, pc.mode, datatype=datatype)
else:
input_rvs = self.rvs
fixed_rvs = self.fixed_params
total_llk += composite.get_formula(
input_rvs, fixed_rvs, self.hyperparams, pc)
# deterministic RV to write out llks to file
like = Deterministic('tmp', total_llk)
# will overwrite deterministic name ...
llk = Potential(self._like_name, like)
logger.info('Model building was successful! \n')
示例10: plant_lijection
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def plant_lijection(self):
"""
Add list to array bijection to model object by monkey-patching.
"""
if self.model is not None:
lordering = ListArrayOrdering(
self.model.unobserved_RVs, intype='tensor')
lpoint = [var.tag.test_value for var in self.model.unobserved_RVs]
self.model.lijection = ListToArrayBijection(lordering, lpoint)
else:
raise AttributeError('Model needs to be built!')
示例11: built_hyper_model
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def built_hyper_model(self):
"""
Initialise :class:`pymc3.Model` depending on configuration file,
geodetic and/or seismic data are included. Estimates initial parameter
bounds for hyperparameters.
"""
logger.info('... Building Hyper model ...\n')
pc = self.config.problem_config
if len(self.hierarchicals) == 0:
self.init_hierarchicals()
point = self.get_random_point(include=['hierarchicals', 'priors'])
if self.config.problem_config.mode == bconfig.geometry_mode_str:
for param in pc.priors.values():
point[param.name] = param.testvalue
with Model() as self.model:
self.init_hyperparams()
total_llk = tt.zeros((1), tconfig.floatX)
for composite in self.composites.values():
if hasattr(composite, 'analyse_noise'):
composite.analyse_noise(point)
composite.init_weights()
composite.update_llks(point)
total_llk += composite.get_hyper_formula(self.hyperparams)
like = Deterministic('tmp', total_llk)
llk = Potential(self._like_name, like)
logger.info('Hyper model building was successful!')
示例12: fit
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def fit(self, X, y):
"""
Fits a Gaussian Process regressor using MCMC.
Parameters
----------
X: np.ndarray, shape=(nsamples, nfeatures)
Training instances to fit the GP.
y: np.ndarray, shape=(nsamples,)
Corresponding continuous target values to `X`.
"""
self.X = X
self.n = self.X.shape[0]
self.y = y
self.model = pm.Model()
with self.model as model:
l = pm.Uniform('l', 0, 10)
log_s2_f = pm.Uniform('log_s2_f', lower=-7, upper=5)
s2_f = pm.Deterministic('sigmaf', tt.exp(log_s2_f))
log_s2_n = pm.Uniform('log_s2_n', lower=-7, upper=5)
s2_n = pm.Deterministic('sigman', tt.exp(log_s2_n))
f_cov = s2_f * covariance_equivalence[type(self.covfunc).__name__](1, l)
Sigma = f_cov(self.X) + tt.eye(self.n) * s2_n ** 2
y_obs = pm.MvNormal('y_obs', mu=np.zeros(self.n), cov=Sigma, observed=self.y)
with self.model as model:
if self.step is not None:
self.trace = pm.sample(self.niter, step=self.step())[self.burnin:]
else:
self.trace = pm.sample(self.niter, init=self.init)[self.burnin:]
示例13: fit
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def fit(self, X, y):
"""
Fits a Student-t regressor using MCMC.
Parameters
----------
X: np.ndarray, shape=(nsamples, nfeatures)
Training instances to fit the GP.
y: np.ndarray, shape=(nsamples,)
Corresponding continuous target values to `X`.
"""
self.X = X
self.n = self.X.shape[0]
self.y = y
self.model = pm.Model()
with self.model as model:
l = pm.Uniform('l', 0, 10)
log_s2_f = pm.Uniform('log_s2_f', lower=-7, upper=5)
s2_f = pm.Deterministic('sigmaf', tt.exp(log_s2_f))
log_s2_n = pm.Uniform('log_s2_n', lower=-7, upper=5)
s2_n = pm.Deterministic('sigman', tt.exp(log_s2_n))
f_cov = s2_f * covariance_equivalence[type(self.covfunc).__name__](1, l)
Sigma = f_cov(self.X) + tt.eye(self.n) * s2_n ** 2
y_obs = pm.MvStudentT('y_obs', nu=self.nu, mu=np.zeros(self.n), Sigma=Sigma, observed=self.y)
with self.model as model:
if self.step is not None:
self.trace = pm.sample(self.niter, step=self.step())[self.burnin:]
else:
self.trace = pm.sample(self.niter, init=self.init)[self.burnin:]
示例14: fit
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def fit(self, X, y):
"""Fit the Imputer to the dataset by fitting bayesian model.
Args:
X (pd.Dataframe): dataset to fit the imputer.
y (pd.Series): response, which is eventually imputed.
Returns:
self. Instance of the class.
"""
_not_num_series(self.strategy, y)
nc = len(X.columns)
# initialize model for bayesian linear reg. Default vals for priors
# assume data is scaled and centered. Convergence can struggle or fail
# if not the case and proper values for the priors are not specified
# separately, also assumes each beta is normal and "independent"
# while betas likely not independent, this is technically a rule of OLS
with pm.Model() as fit_model:
alpha = pm.Normal("alpha", self.am, sd=self.asd)
beta = pm.Normal("beta", self.bm, sd=self.bsd, shape=nc)
sigma = pm.HalfCauchy("σ", self.sig)
mu = alpha+beta.dot(X.T)
score = pm.Normal("score", mu, sd=sigma, observed=y)
self.statistics_ = {"param": fit_model, "strategy": self.strategy}
return self
示例15: fit
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Model [as 别名]
def fit(self, X, y):
"""Fit the Imputer to the dataset by fitting bayesian and LS model.
Args:
X (pd.Dataframe): dataset to fit the imputer.
y (pd.Series): response, which is eventually imputed.
Returns:
self. Instance of the class.
"""
_not_num_series(self.strategy, y)
nc = len(X.columns)
# get predictions for the data, which will be used for "closest" vals
y_pred = self.lm.fit(X, y).predict(X)
y_df = DataFrame({"y": y, "y_pred": y_pred})
# calculate bayes and use appropriate means for alpha and beta priors
# here we specify the point estimates from the linear regression as the
# means for the priors. This will greatly speed up posterior sampling
# and help ensure that convergence occurs
if self.am is None:
self.am = self.lm.intercept_
if self.bm is None:
self.bm = self.lm.coef_
# initialize model for bayesian linear reg. Default vals for priors
# assume data is scaled and centered. Convergence can struggle or fail
# if not the case and proper values for the priors are not specified
# separately, also assumes each beta is normal and "independent"
# while betas likely not independent, this is technically a rule of OLS
with pm.Model() as fit_model:
alpha = pm.Normal("alpha", self.am, sd=self.asd)
beta = pm.Normal("beta", self.bm, sd=self.bsd, shape=nc)
sigma = pm.HalfCauchy("σ", self.sig)
mu = alpha+beta.dot(X.T)
score = pm.Normal("score", mu, sd=sigma, observed=y)
params = {"model": fit_model, "y_obs": y_df}
self.statistics_ = {"param": params, "strategy": self.strategy}
return self