聚合最小化器

时间:2016-02-27 16:50:27

标签: python minimize

下面的代码假设给出了函数达到最小值的2个变量的最小值。但是当我运行它时,我经常无法获得正确的值和以下错误:

  

tnc:达到的最大功能评估数

我猜问题是该程序收敛速度不够快。我怎么解决这个问题? (我给出的值尽可能接近我期望的初始参数)

import numpy as np
from scipy.optimize import minimize
from random import gauss
from matplotlib import pyplot as plt
from scipy.stats import norm
import math

values = []
while len(values) < 10000:
    value = gauss(10, 20)
    if -100 < value < 100:
        values.append(value)

n, bins, patches = plt.hist(values, 50, facecolor='green')
x=np.arange(-100,100,0.01)
binWidth=bins[5]-bins[4]
centre=[]
error=[]
for i in range(len(n)):
    centre=centre+[(2 * bins[i] + binWidth) / 2]
    error = error + [np.sqrt(n[i])]

def gauss(x, mu, sigma, norm):
    f = norm * 1 / np.sqrt(2 * np.pi) * 1 / sigma * np.exp(-(x - mu) ** 2 / 2 / sigma ** 2)
    return f

def like(x):
    f = 0
    for i in range(len(n)):
        f = f - (np.log(1 / np.sqrt(2 * np.pi)) + 0.5 * np.log(1 / (x[1] ** 2)) - (n[i] - gauss(centre[i], x[0], x[1], x[2])) ** 2 / (2 * x[1] **2))
    return f

initial_val = np.array([10, 20, 159681])

res = minimize (like,initial_val, method='TNC', bounds=((1, None), (1, None),(1, None)), options={'xtol': 1e-8, 'disp': True})

mu = res.x[0]
sigma = res.x[1]
norm = res.x[2]
x_axis = np.arange(-100, 100, 0.01)
y = norm * 1 / np.sqrt(2 * np.pi) * 1 / sigma * np.exp(-(x - mu) ** 2 / 2 / sigma ** 2)
plt.plot(x, y)

if(res.success):
    print "YES"
else:
    print "NO"
print res.x
plt.show()

0 个答案:

没有答案