# 功能最大化Function Maximisation

``````from scipy.optimize import minimize
from scipy.stats import lognorm, norm
import numpy as np

np.random.seed(123)
obs = np.random.normal(loc=20, scale=3, size=20)

# Log-Posterior optimisation objectiv
def objective(params, y):
mu = params[0]
sigma = params[1]
llikelihood = np.sum(np.log(norm.pdf(y, mu, sigma)))
lpost = llikelihood + np.log(norm.pdf(mu, 0, 100)) + np.log(lognorm.pdf(sigma, loc= 0, s = 4))
return -1*lpost

starting_mu = 0
starting_sigma = 1
optim_res = minimize(fun = objective, x0=(starting_mu, starting_sigma), args=(obs))
``````

``````dert2@ma0phd201803:~\$ python laplace_approx.py
laplace_approx.py:12: RuntimeWarning: divide by zero encountered in log
lpost = llikelihood + np.log(norm.pdf(mu, 0, 100)) + np.log(lognorm.pdf(sigma, loc= 0, s = 4))
laplace_approx.py:12: RuntimeWarning: divide by zero encountered in log
lpost = llikelihood + np.log(norm.pdf(mu, 0, 100)) + np.log(lognorm.pdf(sigma, loc= 0, s = 4))
laplace_approx.py:12: RuntimeWarning: divide by zero encountered in log
lpost = llikelihood + np.log(norm.pdf(mu, 0, 100)) + np.log(lognorm.pdf(sigma, loc= 0, s = 4))
/opt/anaconda3/lib/python3.7/site-packages/numpy/core/fromnumeric.py:83:     RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
``````

1回复

1回复

1回复

1回复

1回复

1回复

1回复

2回复