本文整理汇总了Python中pymc3.Metropolis方法的典型用法代码示例。如果您正苦于以下问题:Python pymc3.Metropolis方法的具体用法?Python pymc3.Metropolis怎么用?Python pymc3.Metropolis使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymc3
的用法示例。
在下文中一共展示了pymc3.Metropolis方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sample_color
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Metropolis [as 别名]
def sample_color(image, samples=5000, tune=1000, nchains=4):
"""Run MCMC on a color image. EXPERIMENTAL!
Parameters
----------
image : numpy.ndarray
Image array from `load_image`. Should have `image.ndims == 2`.
samples : int
Number of samples to draw from the image
tune : int
All chains start at the same spot, so it is good to let them wander
apart a bit before beginning
Returns
-------
pymc3.MultiTrace of samples from the image. Each sample is an (x, y) float
of indices that were sampled, with three variables named 'red',
'green', 'blue'.
"""
with pm.Model():
pm.DensityDist('red', ImageLikelihood(image[:, :, 0]), shape=2)
pm.DensityDist('green', ImageLikelihood(image[:, :, 1]), shape=2)
pm.DensityDist('blue', ImageLikelihood(image[:, :, 2]), shape=2)
trace = pm.sample(samples, chains=nchains, tune=tune, step=pm.Metropolis())
return trace
示例2: sample_grayscale
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Metropolis [as 别名]
def sample_grayscale(image, samples=5000, tune=100, nchains=4, threshold=0.2):
"""Run MCMC on a 1 color image. Works best on logos or text.
Parameters
----------
image : numpy.ndarray
Image array from `load_image`. Should have `image.ndims == 2`.
samples : int
Number of samples to draw from the image
tune : int
Number of tuning steps to take. Note that this adjusts the step size:
if you want smaller steps, make tune closer to 0.
nchains : int
Number of chains to sample with. This will later turn into the number
of colors in your plot. Note that you get `samples * nchains` of total
points in your final scatter.
threshold : float
Float between 0 and 1. It looks nicer when an image is binarized, and
this will do that. Use `None` to not binarize. In theory you should get
fewer samples from lighter areas, but your mileage may vary.
Returns
-------
pymc3.MultiTrace of samples from the image. Each sample is an (x, y) float
of indices that were sampled, with the variable name 'image'.
"""
# preprocess
image_copy = image.copy()
if threshold != -1:
image_copy[image < threshold] = 0
image_copy[image >= threshold] = 1
# need an active pixel to start on
active_pixels = np.array(list(zip(*np.where(image_copy == image_copy.max()))))
idx = np.random.randint(0, len(active_pixels), nchains)
start = active_pixels[idx]
with pm.Model():
pm.DensityDist('image', ImageLikelihood(image_copy), shape=2)
trace = pm.sample(samples,
tune=tune,
chains=nchains, step=pm.Metropolis(),
start=[{'image': x} for x in start],
)
return trace
示例3: fit_pymc3_model
# 需要导入模块: import pymc3 [as 别名]
# 或者: from pymc3 import Metropolis [as 别名]
def fit_pymc3_model(self, sampler, draws, tune, vi_params, **kwargs):
callbacks = vi_params.get("callbacks", [])
for i, c in enumerate(callbacks):
if isinstance(c, CheckParametersConvergence):
params = c.__dict__
params.pop("_diff")
params.pop("prev")
params.pop("ord")
params["diff"] = "absolute"
callbacks[i] = CheckParametersConvergence(**params)
if sampler == "variational":
with self.model:
try:
self.trace = pm.sample(chains=2, cores=8, tune=5, draws=5)
vi_params["start"] = self.trace[-1]
self.trace_vi = pm.fit(**vi_params)
self.trace = self.trace_vi.sample(draws=draws)
except Exception as e:
if hasattr(e, "message"):
message = e.message
else:
message = e
self.logger.error(message)
self.trace_vi = None
if self.trace_vi is None and self.trace is None:
with self.model:
self.logger.info(
"Error in vi ADVI sampler using Metropolis sampler with draws {}".format(
draws
)
)
self.trace = pm.sample(
chains=1, cores=4, tune=20, draws=20, step=pm.NUTS()
)
elif sampler == "metropolis":
with self.model:
start = pm.find_MAP()
self.trace = pm.sample(
chains=2,
cores=8,
tune=tune,
draws=draws,
**kwargs,
step=pm.Metropolis(),
start=start,
)
else:
with self.model:
self.trace = pm.sample(
chains=2, cores=8, tune=tune, draws=draws, **kwargs, step=pm.NUTS()
)