如何使用scipy.optimize来适应函数而不适合感兴趣的特征?

问题描述 投票:-1回答:1

我正在使用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')

enter image description here

感兴趣的特征在2到2.5之间,所以我不想在该范围内进行曲线拟合。我只想在2之前和2.5之后做曲线拟合。我怎么能用scipy.optimize做到这一点?因为我得到的问题是它在整个频谱中执行拟合。任何帮助,将不胜感激。

python scipy curve-fitting
1个回答
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()

Getting the feature without background

© www.soinside.com 2019 - 2024. All rights reserved.