【发布时间】:2021-10-10 11:45:07
【问题描述】:
我正在尝试将高斯函数拟合到某些数据,但我想返回“中心”和“宽度”值并打印它们。但是,代码返回 ValueError,因此没有绘图。从高斯函数的返回线中删除“中心”和“宽度”可以解决问题,但我不知道如何从拟合中获取这些值(以及如何获取代码以在拟合后将它们打印为输出)。有什么建议吗?
代码&错误:
import matplotlib.pyplot as plt
import pathlib
import os
from scipy.optimize import curve_fit
#Data
data = np.loadtxt('....file.hst')
x = data[:,0]
y1 = data[:,1]
y2 = data[:,2]
n_gauss = 1
offset = 0
def gaussian(x, offset, area, center, width):
y = area * np.exp(-(x - center)**2 / (2 * width**2)) + offset
return y, center, width
def multi_gaussian(x, *gaussians):
y = gaussians[0] * np.ones_like(x)
n_gauss = (len(gaussians)-1) // 3
for gauss in range(n_gauss):
y += gaussian(x, offset, gaussians[3*gauss+1], gaussians[3*gauss+2],
gaussians[3*gauss+3])
return y
#Plots:
plt.plot(x, y1, label="sync1")
plt.plot(x, y2, label="sync2")
popt, pcov = curve_fit(gaussian, x, y1, p0=[0, max(y1), 900, 120])
#popt, pcov = curve_fit(gaussian, x, y2, p0=[5000, max(y2), center, width])
#plt.plot(x, gaussian(y1, -2100, 3200, center, width),
# lw=1, c='m', ls='--', label='Gaussian')
plt.plot(x, multi_gaussian(y1, -210, 270, 900, 120),
lw=1, c='r', ls='--', label='multi-Gaussian')
#plt.plot(x, gaussian(y2, 0, 2250, 900, 120),
# lw=1, c='r', ls='--', label='Gaussian')
#plt.xlim([850, 980])
#plt.ylim([30, 600])
plt.legend()
#Outputs
#print("Center: ", center)
#print("Width: ", width)```
The ValueError is:
return func(xdata, *params) - ydata
ValueError: operands could not be broadcast together with shapes (3,) (1201,),
【问题讨论】:
标签: python plot gaussian valueerror data-fitting