scipy interp1d中的错误

Don*_*beo 1 python scipy

我不明白interp1d报告的结果.我收到NAN,我应该收到号码.

In [131]: bb
Out[131]: 
array([ 0.        ,  1.80286595,  1.87443683,  2.70410611,  3.02764722,
        3.11305985,  3.11534355,  3.18695351,  3.20693444])

In [132]: alphas1
Out[134]: 
array([  3.80918778e+00,   2.06547222e+00,   1.99234191e+00,
         7.55942418e-01,   2.56971574e-01,   1.05144676e-01,
         9.30852046e-02,   1.52574183e-02,   1.23664407e-07])

In [135]: bb.shape
Out[135]: (9,)

In [136]: alphas1.shape
Out[140]: (9,)

In [141]: pol = interp1d(alphas1, bb, bounds_error=False)

In [149]: pol(pol.x)
Out[149]: array([ nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan]) # I was expecting to receive nan only at the borders.
Run Code Online (Sandbox Code Playgroud)

小智 8

我想,如果你检查一下这个类的源代码,那就可以看出问题interp1d_check_bounds:

def _check_bounds(self, x_new):

    ...

    below_bounds = x_new < self.x[0]
    above_bounds = x_new > self.x[-1]

    # !! Could provide more information about which values are out of bounds
    if self.bounds_error and below_bounds.any():
        raise ValueError("A value in x_new is below the interpolation "
            "range.")
    if self.bounds_error and above_bounds.any():
        raise ValueError("A value in x_new is above the interpolation "
            "range.")
Run Code Online (Sandbox Code Playgroud)

该方法检查您尝试放入的x的值是否小于(在您的情况下)self.x[0]的第一个元素.由于是列表中最大的元素,因此此后的每个元素都将"超出范围",即小于第一个元素.xalphas1alphas1[0]x

解决这个问题的方法是扭转你的xy列出:

bb = bb[::-1]
alphas1 = alphas[::-1]
pol = interp1d(alphas1, bb, bounds_error=False)
Run Code Online (Sandbox Code Playgroud)

现在alphas1将随着scipy的预期而增加,并将按预期pol(pol.x)返回bb(现在逆转).