首页 > 解决方案 > 如何修复此错误 IndexError: too many indices for array

问题描述

我正在尝试将分段函数拟合到我拥有的时间序列中,其中第一部分是指数衰减,第二部分是线性的,我查找了很多示例,但我不断收到该错误。这是一个python程序。

这是我的代码

def piece_wise(t, t0, a, b, c, d):

return np.piecewise(t, [t <= t0, t > t0], [lambda t:a*np.exp(b*-t) + d, lambda t:c*t + d])

t = filtered["Time (s)"]

y = filtered["Average"]

p, e = optimize.curve_fit(piece_wise, t, y)

过滤后的数据框有 2187 行

这是完整的错误

  File "/opt/anaconda3/lib/python3.8/site-packages/numpy/lib/function_base.py", line 626, in piecewise
    vals = x[condlist[k]]

IndexError: too many indices for array

现在查看程序 function_base.py,k 是一个循环变量,循环遍历传递给 np.piecewise 的条件列表中的元素数量。我在这里做错了什么?

谢谢!

标签: pythoncurve-fittingpiecewise

解决方案


首先,在做一些复杂的事情之前,比如将你的函数传递给 scipy.optimize,你要检查它是否有效。

您可以使用一些任意数据和参数简单地调用它:

t = filtered["Time (s)"]
t0 = 5; a = 0; b = 0; c = 0; d = 0;
piece_wise(t, t0, a, b, c, d)

这会产生回溯:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-24-e4aa1198c545> in <module>
----> 1 piece_wise(t, t0, a, b, c, d)

<ipython-input-16-d251be3d390b> in piece_wise(t, t0, a, b, c, d)
      1 def piece_wise(t, t0, a, b, c, d):
----> 2     return np.piecewise(t, [t <= t0, t > t0], [lambda t:a*np.exp(b*-t) + d, lambda t:c*t + d])
      3 

<__array_function__ internals> in piecewise(*args, **kwargs)

~/anaconda3/envs/torch/lib/python3.9/site-packages/numpy/lib/function_base.py in piecewise(x, condlist, funclist, *args, **kw)
    612             y[cond] = func
    613         else:
--> 614             vals = x[cond]
    615             if vals.size > 0:
    616                 y[cond] = func(vals, *args, **kw)

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

这证实了该问题与 scipy.optimize 无关。

此外,它告诉我们错误发生在这一行:

return np.piecewise(t, [t <= t0, t > t0], [lambda t:a*np.exp(b*-t) + d, lambda t:c*t + d])

让我们分解一下...

f1, f2 = lambda t:a*np.exp(b*-t) + d, lambda t:c*t + d
f1(0)
f2(0)

没有报错,所以这两个功能就ok了……

让我们看一下 np.piecewise 的文档

piecewise(x, condlist, funclist, *args, **kw)
    Evaluate a piecewise-defined function.
    
    Given a set of conditions and corresponding functions, evaluate each
    function on the input data wherever its condition is true.
    
    Parameters
    ----------
    x : ndarray or scalar
        The input domain.
    condlist : list of bool arrays or bool scalars
        ....
    funclist : list of callables, f(x,*args,**kw), or scalars
        ....

啊看!它说 x 应该是一个 ndarray 或标量。

我们正在通过熊猫系列。

尝试这个:

t = filtered["Time (s)"].to_numpy()
t0 = 5; a = 0; b = 0; c = 0; d = 0;
piece_wise(t, t0, a, b, c, d)

Out: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

现在它似乎工作了。我想这可能是你的问题。

希望我能帮助您在将来调试此类问题。始终将问题分解成更小的部分,并分别测试每一部分。


推荐阅读