求曲线曲线的最大值 [英] Finding the maximum of a curve scipy
问题描述
我已将曲线拟合到一组数据点.我想知道如何找到曲线的最大点,然后我想注释该点(我不想使用数据中的最大 y 值来执行此操作).我不能完全编写我的代码,但这里是我的代码的基本布局.
I have fitted curve to a set of data points. I would like to know how to find the maximum point of my curve and then I would like to annotate that point (I don't want to use by largest y value from my data to do this). I cannot exactly write my code but here is the basic layout of my code.
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
x = [1,2,3,4,5]
y = [1,4,16,4,1]
def f(x, p1, p2, p3):
return p3*(p1/((x-p2)**2 + (p1/2)**2))
p0 = (8, 16, 0.1) # guess perameters
plt.plot(x,y,"ro")
popt, pcov = curve_fit(f, x, y, p0)
plt.plot(x, f(x, *popt))
还有找到峰宽的方法吗?
Also is there a way to find the peak width?
我是否缺少一个可以执行此操作的简单内置函数?我可以区分函数并找到它为零的点吗?如果是这样怎么办?
Am I missing a simple built in function that could do this? Could I differentiate the function and find the point at which it is zero? If so how?
推荐答案
在您拟合找到最佳参数以最大化您的函数后,您可以使用 minimize_scalar
(或其他方法之一)找到峰值 scipy.optimize
中的方法).
After you fit to find the best parameters to maximize your function, you can find the peak using minimize_scalar
(or one of the other methods from scipy.optimize
).
请注意,在下面,我已经移动了 x[2]=3.2
以便曲线的峰值不会落在数据点上,我们可以确定我们正在找到达到曲线的峰值,而不是数据.
Note that in below, I've shifted x[2]=3.2
so that the peak of the curve doesn't land on a data point and we can be sure we're finding the peak to the curve, not the data.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, minimize_scalar
x = [1,2,3.2,4,5]
y = [1,4,16,4,1]
def f(x, p1, p2, p3):
return p3*(p1/((x-p2)**2 + (p1/2)**2))
p0 = (8, 16, 0.1) # guess perameters
plt.plot(x,y,"ro")
popt, pcov = curve_fit(f, x, y, p0)
# find the peak
fm = lambda x: -f(x, *popt)
r = minimize_scalar(fm, bounds=(1, 5))
print "maximum:", r["x"], f(r["x"], *popt) #maximum: 2.99846874275 18.3928199902
x_curve = np.linspace(1, 5, 100)
plt.plot(x_curve, f(x_curve, *popt))
plt.plot(r['x'], f(r['x'], *popt), 'ko')
plt.show()
当然,除了优化功能外,我们还可以针对一堆x值计算并获得接近值:
Of course, rather than optimizing the function, we could just calculate it for a bunch of x-values and get close:
x = np.linspace(1, 5, 10000)
y = f(x, *popt)
imax = np.argmax(y)
print imax, x[imax] # 4996 2.99859985999
这篇关于求曲线曲线的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!