【发布时间】:2012-10-08 00:32:49
【问题描述】:
我正在尝试开始使用 scipy,但在使用“线性”以外的其他类型(我尝试了“零”和“立方”)时,似乎无法从 interpolation.interp1d 获取示例。
我在 Google 中搜索时找不到遇到同样问题的人,所以我想这是我的愚蠢行为。
我在 python 2.73 和 OSX 10.8 上使用 scipy 0.11
代码不工作:
from scipy import interpolate
import numpy as np
x = np.arange(0, 10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y, kind="zero")
xnew = np.arange(0,9, 0.1)
ynew = f(xnew) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', xnew, ynew, '-')
plt.show()
IndexError Traceback (most recent call last)
<ipython-input-1-23bb96a1589b> in <module>()
4 f = interpolate.interp1d(x, y, kind="zero")
5 xnew = np.arange(0,9, 0.1)
----> 6 ynew = f(xnew) # use interpolation function returned by `interp1d`
7 plt.plot(x, y, 'o', xnew, ynew, '-')
8 plt.show()
/usr/local/lib/python2.7/site-packages/scipy/interpolate/interpolate.pyc in __call__(self, x_new)
394 out_of_bounds = self._check_bounds(x_new)
395
--> 396 y_new = self._call(x_new)
397
398 # Rotate the values of y_new back so that they correspond to the
/usr/local/lib/python2.7/site-packages/scipy/interpolate/interpolate.pyc in _call_spline(self, x_new)
370 def _call_spline(self, x_new):
371 x_new =np.asarray(x_new)
--> 372 result = spleval(self._spline,x_new.ravel())
373 return result.reshape(x_new.shape+result.shape[1:])
374
/usr/local/lib/python2.7/site-packages/scipy/interpolate/interpolate.pyc in spleval((xj, cvals, k), xnew, deriv)
833 res[sl].imag = _fitpack._bspleval(xx,xj,cvals.imag[sl],k,deriv)
834 else:
--> 835 res[sl] = _fitpack._bspleval(xx,xj,cvals[sl],k,deriv)
836 res.shape = oldshape + sh
837 return res
IndexError: too many indices
在这里启动调试控制台时,我可以将其缩小到 cvals[sl] 导致错误
sl = (slice(None, None, None), 0) # <-- I don't really get the slice part here...
cvals = array([ 1. , 0.71653131, 0.51341712, 0.36787944, 0.26359714,
0.1888756 , 0.13533528, 0.09697197, 0.06948345])
有人可以重现这个还是我的机器有问题?
【问题讨论】:
-
尝试将代码作为脚本运行,而不是从您的 python 解释器中运行。如果可行,请尝试退出/重新启动您的解释器。
-
我刚试过。我将上面的代码编辑为可以作为脚本执行。结果在我的系统上是一样的。
-
在您的调试控制台中,尝试打印
cvals.shape。应该是(9,)。出于某种原因,您的似乎是(9,0),因为sl在元组末尾得到了错误的0。sl应该是(slice(None, None, None),)。 -
那么 sl 从第 830 行附加了索引: sl = (slice(None),)+index 调试控制台状态:ipdb> cvals.shape (9,)
-
sh 好像是一个空元组:ipdb> sh ()
标签: python numpy matplotlib scipy