【发布时间】:2021-11-19 14:04:15
【问题描述】:
我已经编写了一个代码来通过 scipy curve_fit 在数据集中拟合高斯函数。有几个不同的数据集。一个有 19 个点,一个有 21 个点,它们都包含 0.5-0.7、1.0-1.2 和 1.5-1.7 范围内的不同数据集。 令人惊讶的是,当我在 19 个点数据集中运行代码时,它们三个都成功执行了,但在 21 个点数据集的情况下,只有 1.5-1.7 个范围数据具有正确的拟合度。所有其他人的穿着都非常不合适。 这是代码。
#function declaration
def gauss(x, amp, mu, sigma):
y = amp*np.exp(-(x-mu)**2/(2*sigma**2))
return y
#fitting
popt, pcov = curve_fit(f = gauss, xdata = x, ydata = y)
#print(popt)
amp = popt[0]
mu = popt[1]
sigma = popt[2]
print(amp,mu,sigma)
#krypton value
krypton_y = amp/((math.exp(1))**2)
#print(krypton_y)
krypton_x1 = mu + math.sqrt((-2*(sigma**2))*math.log(krypton_y/amp))
krypton_x2 = mu - math.sqrt((-2*(sigma**2))*math.log(krypton_y/amp))
print(krypton_x1-krypton_x2)
#print(gauss([krypton_x1, krypton_x2], popt[0], popt[1], popt[2]))
#horizontal line
horizontal_x = np.arange(min(x)-0.01, max(x)+0.02, 0.01)
horizontal_y = np.repeat(0, len(horizontal_x))
#build fit set
x_test = np.arange(min(x), max(x), 0.0000001)
y_test = gauss(x_test, popt[0], popt[1], popt[2])
y_krypton = []
for i in horizontal_x:
y_krypton.append(krypton_y)
#Vertical lines
vertical_y = np.arange(-20, amp+20, 0.01)
l = len(vertical_y)
vertical_mean = np.repeat(mu, l)
#fit data
fig = plt.figure()
fig = plt.scatter(x,y, label ='original data', color = 'red', marker = 'x')
fig = plt.plot(x_test, y_test, label = 'Gaussian fit curve')
fig = plt.plot(horizontal_x, y_krypton, color = '#830000', linewidth = 1)
fig = plt.plot(vertical_mean, vertical_y, color = '#0011ed')
fig = plt.xlabel('Distance in mm')
fig = plt.ylabel('Current in nA')
fig = plt.title('Intensity Profile for '+gas+' laser | Z = '+str(z)+'cm')
fig = plt.scatter(mu, amp, s = 25, color = '#0011ed')
fig = plt.scatter(krypton_x1, krypton_y, s = 25, color = '#830000')
fig = plt.scatter(krypton_x2, krypton_y, s = 25, color = '#830000')
plt.annotate('('+"{:.4f}".format(mu)+','+"{:.4f}".format(amp)+')', (mu, amp), xytext = (mu+0.002,amp+0.5))
plt.annotate('('+"{:.4f}".format(krypton_x1)+','+"{:.4f}".format(krypton_y)+')', (krypton_x1, krypton_y), xytext = (krypton_x1+0.002,krypton_y+0.5))
plt.annotate('('+"{:.4f}".format(krypton_x2)+','+"{:.4f}".format(krypton_y)+')', (krypton_x2, krypton_y), xytext = (krypton_x2+0.002,krypton_y+0.5))
plt.legend()
plt.margins(0)
plt.show()
【问题讨论】:
-
从图片上看不清楚,但这是真的吗,原来的 21 点数据包含离预期中心很远的点?你可以只打印 21 个点,或者在没有拟合曲线的情况下单独绘制它们吗?所以我的猜测是有一个大纲点。
-
你能添加代码来生成3个数据集吗?
-
不,先生,因为它是一个非常小的数据集,很明显没有轮廓点。 1 0,1.01 0,1.02 0,1.03 0,1.04 0,1.05 0.043,1.06 1.88,1.07 16.059,1.08 60.125,1.09 132.756,1.1143.096,1.11 79.476,1.12 25.415,1.13 3.626,1.14 0.558,1.15 0.001,111.15 0 , 1.17 0, 1.18 0, 1.19 0, 1.2 0,
-
是的,我当然可以,但是先生,这是在给定数据中拟合曲线的代码。我们为什么要从中生成数据集?
-
典型的猜测可能是一个不错的猜测。三件事:起始值、起始值和最终起始值。
标签: python machine-learning scipy curve-fitting gaussian