如何从多项式拟合中排除值?

2024-03-28 14:53:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我将多项式拟合到数据中,如图所示:enter image description here

使用脚本:

from scipy.optimize import curve_fit
import scipy.stats
from scipy import asarray as ar,exp

xdata = xvalues
ydata = yvalues

fittedParameters = numpy.polyfit(xdata, ydata + .00001005 , 3)
modelPredictions = numpy.polyval(fittedParameters, xdata) 

axes.plot(xdata, ydata,  '-')
xModel = numpy.linspace(min(xdata), max(xdata))
yModel = numpy.polyval(fittedParameters, xModel)

axes.plot(xModel, yModel)

我想排除3.4到3.55之间的区域。我怎么能在我的脚本中做到这一点?此外,我还试图在原始的.fits文件中删除NaN。帮助是有价值的


Tags: 数据fromimportnumpy脚本plotscipyoptimize
1条回答
网友
1楼 · 发布于 2024-03-28 14:53:17

您可以屏蔽排除区域内的值,并在以后将此屏蔽应用于拟合函数

# Using random data here, since you haven't provided sample data
xdata = numpy.arange(3,4,0.01)
ydata = 2* numpy.random.rand(len(xdata)) + xdata

# Create mask (boolean array) of values outside of your exclusion region
mask = (xdata < 3.4) | (xdata > 3.55)

# Do the fit on all data (for comparison)
fittedParameters = numpy.polyfit(xdata, ydata + .00001005 , 3)
modelPredictions = numpy.polyval(fittedParameters, xdata) 
xModel = numpy.linspace(min(xdata), max(xdata))
yModel = numpy.polyval(fittedParameters, xModel)

# Do the fit on the masked data (i.e. only that data, where mask == True)
fittedParameters1 = numpy.polyfit(xdata[mask], ydata[mask] + .00001005 , 3)
modelPredictions1 = numpy.polyval(fittedParameters1, xdata[mask]) 
xModel1 = numpy.linspace(min(xdata[mask]), max(xdata[mask]))
yModel1 = numpy.polyval(fittedParameters1, xModel1)

# Plot stuff
axes.plot(xdata, ydata,  '-')
axes.plot(xModel, yModel)        # orange
axes.plot(xModel1, yModel1)      # green

给予

enter image description here

绿色曲线现在是排除了3.4 < xdata 3.55的拟合。橙色曲线是没有排除的装饰(用于比较)

如果您想在xdata中排除可能的NAN,您可以通过numpy.isnan()函数来增强mask,如

# Create mask (boolean array) of values outside of your exclusion AND which ar not nan
xdata < 3.4) | (xdata > 3.55) & ~numpy.isnan(xdata)

相关问题 更多 >