nan在interp1d scipy

2024-05-16 20:42:16 发布

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

我在python中使用interp1d编写了以下代码,interp1d的输出乘以查询点将数组的起始值输出为NaN。为什么?在

Freq_Vector = np.arange(0,22051,1)
Freq_ref = np.array([20,25,31.5,40,50,63,80,100,125,160,200,250,315,400,500,630,750,800,1000,1250,1500,1600,2000,2500,3000,3150,4000,5000,6000,6300,8000,9000,10000,11200,12500,14000,15000,16000,18000,20000])   
W_ref=-1*np.array([39.6,32,25.85,21.4,18.5,15.9,14.1,12.4,11,9.6,8.3,7.4,6.2,4.8,3.8,3.3,2.9,2.6,2.6,4.5,5.4,6.1,8.5,10.4,7.3,7,6.6,7,9.2,10.2,12.2,10.8,10.1,12.7,15,18.2,23.8,32.3,45.5,50])
if FreqVector[-1] > Freq_ref[-1]:
    Freq_ref[-1] = FreqVector[-1]
WdB = interpolate.interp1d(Freq_ref,W_ref,kind='cubic',axis=-1, copy=True, bounds_error=False, fill_value=np.nan)(FreqVector)

WdB中的前20个值是:

^{pr2}$

以下是前20个值在maltab中输出的相同值:

-58.0424562952059
-59.2576965087483
-60.1150845850336
-60.6367649499501
-60.8448820293863
-60.7615802492306
-60.4090040353715
-59.8092978136973
-58.9846060100965
-57.9570730504576
-56.7488433606689
-55.3820613666188
-53.8788714941959
-52.2614181692886
-50.5518458177851
-48.7722988655741
-46.9449217385440
-45.0918588625830
-43.2352546635798
-41.3972535674226
-39.6000000000000
-37.8656383872004    

我怎样才能避免这种情况,并且像matlab对interp1d那样有实际的值呢?在


Tags: 代码refnp数组nanarraywdbvector
2条回答

我不知道确切的原因,但在查看绘制的数据时,拟合实际上是有效的。在

from scipy import interpolate
import numpy as np
from matplotlib import pyplot as plt

Freq_Vector = np.arange(0,22051.0,1)
Freq_ref = np.array([20,25,31.5,40,50,63,80,100,125,160,200,250,315,\
400,500,630,750,800,1000,1250,1500,1600,2000,2500,3000,3150,\
4000,5000,6000,6300,8000,9000,10000,11200,12500,14000,15000,\
16000,18000,20000])
W_ref=-1*np.array([39.6,32,25.85,21.4,18.5,15.9,14.1,12.4,11,\
9.6,8.3,7.4,6.2,4.8,3.8,3.3,2.9,2.6,2.6,4.5,5.4,6.1,8.5,10.4,7.3,7,\
6.6,7,9.2,10.2,12.2,10.8,10.1,12.7,15,18.2,23.8,32.3,45.5,50])
if Freq_Vector[-1] > Freq_ref[-1]:
    Freq_ref[-1] = Freq_Vector[-1]
WdB = interpolate.interp1d(Freq_ref.tolist(),W_ref.tolist(),\
kind='cubic', bounds_error=False)(Freq_Vector)

plt.plot(Freq_ref,W_ref,'..',color='black',label='Reference')
plt.plot(Freq_ref,W_ref,'-.',color='blue',label='Interpolated')
plt.legend()

情节如下:

Data-Plot

插值实际上正在进行,但拟合效果不如预期的好。但如果你的目的是为了拟合你的数据,为什么不使用样条插值器呢?它仍然是立方的,但不太容易过载。在

^{pr2}$

enter image description here

数据和绘图非常顺利。在

WdB
Out[34]: 
array([-114.42984432, -108.43602531, -102.72381906, ...,  -50.00471866,
        -50.00236016,  -50.        ])

interp1d“将数组的起始值输出为NaN。为什么?”在

因为您给它的一组采样点(Freq_ref)有一个下界20interp1d将为样本集之外的点赋值,如果bounds_errorFalsedocs),那么{}的值将被赋值。 由于您请求了从0到{}的频率值的插值,所以该方法将它们分配给NaN。 这与Matlab的默认设置不同,后者使用请求的插值方法(docs)进行外推。在

这就是说,我会谨慎地将Matlab(或任何程序)的默认外推值称为“实际值”,因为外推法非常困难,而且很容易产生异常行为。对于您引用的值,Matlab的'cubic'/'pchip'外推法生成图形:

y vs x interpolation in low frequency range

外推法表明y-值翻转过来了。这也许是正确的,但在把它当作福音之前应该仔细考虑。在


如果你想给interp1d方法添加外推能力,see this answer(因为我是一个Matlab的人,而不是Python的人)。在

相关问题 更多 >