问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import optimize
import sys
def main_1():
# 设置随机数种子
np.random.seed(123)
alpha = 1
sigma = 1
beta = [1, 2.5]
N = 100
X1 = np.random.randn(N)
X2 = np.random.randn(N)
Y = alpha + beta[0] * X1 + beta[1] * X2 + np.random.randn(N) * sigma
basic_model = pm.Model()
with basic_model:
alpha = pm.Normal('alpha', mu=0, sd=10)
beta = pm.Normal('beta', mu=0, sd=10, shape=2)
sigma = pm.HalfNormal('sigma', sd=1)
mu = alpha + beta[0] * X1 + beta[1] * X2
Y_obs = pm.Normal('Y_obs', mu=mu, sd=sigma, observed=Y)
with basic_model:
# 用MAP获得初始点
start = pm.find_MAP(method='BFGS')
# 实例化采样器
step = pm.Slice(vars=[sigma])
# 对后验分布进行5000次采样
trace = pm.sample(5000, step=step, start=start)
pm.traceplot(trace)
if name == 'main':
sys.exit(main_1())