fitting the sum of exponentials in python.. error: operands could not be broadcast together with shapes (11,) (0,)

fitting the sum of exponentials in python.. error: operands could not be broadcast together with shapes (11,) (0,)

我正在尝试用两个指数之和来拟合我的数据。但是,我总是会遇到一些错误。当我尝试 运行 这段代码时,我得到一个错误,操作数不能一起广播......任何人都可以查看这段代码吗?我是python新手

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
old_settings = np.seterr(all='ignore')

x=[0.21, 0.43, 0.50, 0.65, 0.86, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0]
y=[43, 33, 30, 24, 18, 16, 14, 13, 14, 13, 13]
yerr= [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
xerr=[0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01, 0.01,0.01,0.01]

def func(x, a, b, c, d):
    return a * np.exp(b * x) + c * np.exp(d * x)


# Here you give the initial parameters for a,b,c which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,x,y,p0=(2.0, -7.0, 2.0, 0.1))

print(popt) # This contains your three best fit parameters

p1 = popt[0] # This is your a
p2 = popt[1] # This is your b
p3 = popt[2] # This is your c
p4 = popt[3] # This is your d

residuals = y - func(x,p1,p2,p3,p4)
fres = sum( (residuals**2)/func(x,p1,p2,p3,p4) ) # The chi-sqaure of your fit

print(fres)

""" Now if you need to plot, perform the code below """
curvey = func(x,p1,p2,p3,p4) # This is your y axis fit-line

plt.plot(x, curvey, 'red', label='The best-fit line')
plt.scatter(x,y, c='b',label='The data points')
plt.legend(loc='best')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

错误是:

Warning (from warnings module):
  File "/home/manisha/Desktop/Moessbauer effect/countsvsd.py", line 13
    return a * np.exp(b * x) + c * np.exp(d * x)
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future

Traceback (most recent call last):
  File "/home/manisha/Desktop/Moessbauer effect/countsvsd.py", line 27, in <module>
    residuals = y - func(x,p1,p2,p3,p4)
ValueError: operands could not be broadcast together with shapes (11,) (0,) 

感谢您的任何意见。

您将 x 定义为普通 python 列表。如果将其定义为 numpy 数组,它会起作用:

x=np.array([0.21, 0.43, 0.50, 0.65, 0.86, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0])

然后func()中的操作应用于x的每个元素,函数returns另一个numpy数组。