numpyfuture-warning

FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`


In [57]: dW = np.zeros((2,2), int)                                              

In [58]: x = [[0,1,1,0,1, 0], [1, 1, 1, 1, 0, 0]]                               

In [59]: np.add.at(dW,x,1)                                                      
/home/infinity/anaconda3/bin/ipython:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.

I was trying to create a confusion matrix using numpy, but I got the previous error. How can I fix that?


Solution

  • If we supply an array rather than a list, we don't get the future warning:

    In [11]: In [57]: dW = np.zeros((2,2), int)
        ...: 
        ...: In [58]: x = [[0,1,1,0,1, 0], [1, 1, 1, 1, 0, 0]]
    In [12]: dW
    Out[12]: 
    array([[0, 0],
           [0, 0]])
    In [13]: x
    Out[13]: [[0, 1, 1, 0, 1, 0], [1, 1, 1, 1, 0, 0]]
    In [14]: np.add.at(dW,np.array(x),1)
    In [15]: dW
    Out[15]: 
    array([[5, 5],
           [7, 7]])
    

    According to the docs,

    indices : array_like or tuple Array like index object or slice object for indexing into first operand. If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects.

    In [17]: np.add.at(dW,tuple(x),1)
    In [18]: dW
    Out[18]: 
    array([[6, 7],
           [8, 9]])
    In [19]: tuple(x)
    Out[19]: ([0, 1, 1, 0, 1, 0], [1, 1, 1, 1, 0, 0])
    

    Recent numpy versions have been tightening the indexing rules. In the past lists were sometimes allowed in contexts that really expected tuples or arrays. This futurewarning is part of that tightening.

    ===

    As commented:

    In [22]: In [57]: dW = np.zeros((2,2), int)
        ...: 
    In [23]: np.add.at(dW,tuple(x),1)
    In [24]: dW
    Out[24]: 
    array([[1, 2],
           [1, 2]])