[英]How can I do a better curve fitting with a gaussian function like this?
I have data and I am fitting the data with a gaussian curve fitting. 我有数据,我用高斯曲线拟合拟合数据。 The blue bullets are my data.
蓝色子弹是我的数据。 The gaussian starts at zero and look like the red curve.
高斯从零开始,看起来像红色曲线。 But I want something, that looks more like the green curve.
但我想要的东西,看起来更像绿色曲线。 All gaussian curve fitting examples I found at the internet starts at zero.
我在互联网上找到的所有高斯曲线拟合示例都从零开始。 Maybe there is another function that can change the starting y value or something like that?
也许有另一个函数可以改变起始y值或类似的东西?
Here's my code so far: 到目前为止,这是我的代码:
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import os
import csv
path = 'Proben Bilder v06 results'
filename = '00_sumListe.csv'
# read csv file with scale data
x = []
y = []
with open(os.path.join(path, filename), 'r') as csvfile:
sumFile = csv.reader(csvfile, delimiter=',')
for row in sumFile:
id = float(row[0])
sumListe = -float(row[1])
x = np.append(x, id)
y = np.append(y, sumListe)
y = y-min(y)
# x = np.arange(10)
# y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1])
# weighted arithmetic mean (corrected - check the section below)
mean = sum(x * y) / sum(y)
sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))
def gauss(x, a, x0, sigma): # x0 = mü
return a * np.exp(-(x - x0)**2 / (2 * sigma**2))
popt, pcov = curve_fit(gauss, x, y, p0=[max(y), mean, sigma])
# plt.gca().invert_yaxis()
plt.plot(x, y, 'b+:', label='data')
plt.plot(x, gauss(x, *popt), 'r-', label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('steps')
plt.ylabel('mean value')
plt.show()
My data is a bit to big to write it here... I can't load it up or can I? 我的数据在这里写得有点大......我无法加载它或者我可以吗?
Does anyone have a better idea? 有没有人有更好的主意?
You could modify your gauss function so that there is an offset in the y axis to potentially give you a better fit. 您可以修改您的高斯函数,以便有在y轴的偏移潜在地给你一个更好的选择。 This requires you to add an extra initial guess in
p0
这要求您在
p0
添加额外的初始猜测
# your code here
def gauss2(x, b, a, x0, sigma):
return b + (a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)))
popt, pcov = curve_fit(gauss2, x, y, p0=[10, max(y), mean, sigma])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.