【问题标题】:FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`FutureWarning:不推荐使用非元组序列进行多维索引;使用 `arr[tuple(seq)]` 而不是 `arr[seq]`
【发布时间】:2021-03-02 02:53:22
【问题描述】:
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.

我试图使用 numpy 创建一个混淆矩阵,但我得到了上一个错误。我该如何解决?

【问题讨论】:

    标签: numpy future-warning


    【解决方案1】:

    如果我们提供一个数组而不是一个列表,我们不会收到未来的警告:

    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]])
    

    根据文档,

    indices : array_like 或 tuple 数组,如索引对象或切片对象,用于索引到第一个 操作数。如果第一个操作数有多个维度,则索引可以是 数组的元组,如索引对象或切片对象。

    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])
    

    最近的numpy 版本已经收紧了索引规则。在过去,有时允许在真正需要元组或数组的上下文中使用列表。这个未来的警告是紧缩政策的一部分。

    ===

    如评论:

    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]])
    

    【讨论】:

    • 只是说:如果你使用tuple()numpy.array()dW会有所不同。
    猜你喜欢
    • 2019-02-06
    • 2019-03-06
    • 2019-10-27
    • 2021-05-29
    • 2019-04-14
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多