我正在使用scipy.optimize进行曲线拟合。我只想适合频谱的第一部分和最后一部分。频谱的中间部分具有所有有趣的功能,因此我显然不想适合该区域。你怎么能做到这一点?
例如:
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
from numpy.polynomial.polynomial import polyfit
%matplotlib inline
import matplotlib.pyplot as pl
def func(x, a, b, c):
return a * np.exp(-b * x) + c
xdata = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3, 0.5)
np.random.seed(1729)
y_noise = 0.2 * np.random.normal(size=xdata.size)
ydata = y + y_noise
plt.plot(xdata, ydata, 'b-', label='data')
感兴趣的特征在2到2.5之间,所以我不想在该范围内进行曲线拟合。我只想在2之前和2.5之后进行曲线拟合。我如何使用scipy.optimize做到这一点?因为我遇到的问题是它在整个光谱范围内都适合。任何帮助,将不胜感激。
答案 0 :(得分:1)
此任务非常简单(假设我正确理解了这个问题,并且正如James Phillips在他的评论中指出的那样)。但是,有几种方法可以实现它。这是一个:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def decay( x, a, b, c ):
return a + b * np.exp( - c * x )
xList = np.linspace( 0, 5, 121 )
yList = np.fromiter( ( .6 * np.exp( -( x - 2.25 )**2 / .05 ) + decay( x, .3, 1, .6) + .05 * np.random.normal() for x in xList ), np.float )
takeList = np.concatenate( np.argwhere( np.logical_or(xList < 2., xList > 2.5) ) )
featureList = np.concatenate( np.argwhere( np.logical_and(xList >= 2., xList <= 2.5) ) )
xSubList = xList[ takeList ]
ySubList = yList[ takeList ]
xFtList = xList[ featureList ]
yFtList = yList[ featureList ]
myFit, _ = curve_fit( decay, xSubList, ySubList )
fitList = np.fromiter( ( decay( x, *myFit) for x in xList ), np.float )
cleanY = np.fromiter( ( y - decay( x, *myFit) for x,y in zip( xList, yList ) ), np.float )
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.plot( xList, yList )
ax.plot( xSubList, ySubList - .1, '--' ) ## -0.1 offset for visibility
ax.plot( xFtList, yFtList + .1, ':' ) ## +0.1 offset for visibility
ax.plot( xList, fitList, '-.' )
ax.plot( xList, cleanY ) ## feature without background
plt.show()