【问题标题】:Returning values from Gaussian fitting从高斯拟合返回值
【发布时间】: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


    【解决方案1】:

    发生这种情况是因为您的 gaussian 函数返回 3 个值而不是 1 个,所以不妨试试这样的方法:

    def gaussian(x, offset, area, center, width):
      return area * np.exp(-(x - center)**2 / (2 * width**2)) + offset
    

    【讨论】:

    • 嘿,这在我没有得到 ValueError 的意义上是有效的,但我仍然想以某种方式打印宽度和中心(看看我从配件中得到的这些值)。如果它们没有被定义为回报,我怎样才能让代码给我这些值?
    • 也许分开存放然后打印出来?因为 curve_fit 函数需要一个只返回一个值的函数:)
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2012-07-15
    • 2015-07-26
    相关资源
    最近更新 更多