scipy.optimize.curve_fit设置“固定"范围 [英] scipy.optimize.curve_fit setting a "fixed" parameter

查看:820
本文介绍了scipy.optimize.curve_fit设置“固定"范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 scipy.optimize.curve_fit 使用高斯函数估算我的数据中的峰值.这对于强峰来说效果很好,但是对于弱峰则更加困难.但是,我认为固定参数(例如,高斯宽度)将对此有所帮助.我知道我可以设置初始的估计",但是有一种方法可以轻松地定义单个参数,而无需更改适合的功能吗?

I'm using scipy.optimize.curve_fit to approximate peaks in my data with Gaussian functions. This works well for strong peaks, but it is more difficult with weaker peaks. However, I think fixing a parameter (say, width of the Gaussian) would help with this. I know I can set initial "estimates" but is there a way that I can easily define a single parameter without changing the function I'm fitting to?

推荐答案

如果您要修复" fit函数的参数,则可以定义一个新的fit函数,该函数利用原始的fit函数,但需要进行设置一个参数为固定值:

If you want to "fix" a parameter of your fit function, you can just define a new fit function which makes use of the original fit function, yet setting one argument to a fixed value:

custom_gaussian = lambda x, mu: gaussian(x, mu, 0.05)

这是将高斯函数sigma固定为0.05的完整示例. (而不是最佳值0.1).当然,这在这里并没有真正意义,因为该算法在寻找最佳值时没有问题.但是,您可以看到在固定sigma的情况下仍如何找到mu.

Here's a complete example of fixing sigma of a Gaussian function to 0.05 (instead of optimal value 0.1). Of course, this doesn't really make sense here because the algorithm has no problem in finding optimal values. Yet, you can see how mu is still found despite the fixed sigma.

import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize 

def gaussian(x, mu, sigma):
    return 1 / sigma / np.sqrt(2 * np.pi) * np.exp(-(x - mu)**2 / 2 / sigma**2)

# Create sample data
x = np.linspace(0, 2, 200)
y = gaussian(x, 1, 0.1) + np.random.rand(*x.shape) - 0.5
plt.plot(x, y, label="sample data")

# Fit with original fit function
popt, _ = scipy.optimize.curve_fit(gaussian, x, y)
plt.plot(x, gaussian(x, *popt), label="gaussian")

# Fit with custom fit function with fixed `sigma`
custom_gaussian = lambda x, mu: gaussian(x, mu, 0.05)
popt, _ = scipy.optimize.curve_fit(custom_gaussian, x, y)
plt.plot(x, custom_gaussian(x, *popt), label="custom_gaussian")

plt.legend()
plt.show()

这篇关于scipy.optimize.curve_fit设置“固定"范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆