scipy.optimize.fmin错误:使用序列设置数组元素

时间:2018-05-16 10:45:29

标签: python numpy scipy

我尝试通过查找具有最低错误值的参数来拟合sin函数。

以下是我的代码:

import numpy as np
import scipy.optimize as opt
from scipy.optimize import leastsq
import matplotlib.pyplot as plt

def func_model(x, para):
    ''' Model: y = a*sin(2*k*pi*x+theta)'''
    a, k, theta = para
    return a*np.sin(2*k*np.pi*x+theta)

def func_noise(x, para):
    a, k, theta = para
    return a*np.sin(2*k*np.pi*x+theta) + np.random.randn(100)

def func_error(para_guess):
    '''error_func'''
    error_sum = 0
    x_seq = np.linspace(-2*np.pi, 0, 100)
    para_fact = [10, 0.34, np.pi/6]
    for x in x_seq:
        error_value = (func_noise(x, para_fact)-func_model(x, para_guess))**2
        error_sum = error_sum + error_value
    return error_sum

para_guess_init = np.array([7, 0.2, 0])
solution = opt.fmin(func_error, para_guess_init) 
print(solution)

但它不起作用,并说错误:设置一个带序列的数组

回溯:

  File "", line 26, in <module>
    solution = opt.fmin(func_error, para_guess_init)
  File "C:\Users\sun\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 408, in fmin
    res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
  File "C:\Users\sun\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 532, in _minimize_neldermead
    fsim[k] = func(sim[k])
ValueError: setting an array element with a sequence.

有人可以帮助我,提前谢谢

1 个答案:

答案 0 :(得分:2)

此最小化器期望标量函数评估最小化。

您的函数func_error会返回大小为(100,)的向量。

比较你的专栏:

error_value = (func_noise(x, para_fact)-func_model(x, para_guess))**2

例如:

error_value = np.sum(np.square(
                               func_noise(x, para_fact)-func_model(x, para_guess)))

虽然我更喜欢(客观的变化!):

error_value = np.linalg.norm(
                             func_noise(x, para_fact)-func_model(x, para_guess))