代码之家  ›  专栏  ›  技术社区  ›  user32882

稀疏矩阵hstack获取关于可订阅性的错误

  •  0
  • user32882  · 技术社区  · 7 年前

    有人能解释一下为什么这不起作用吗?

    from scipy.sparse import coo_matrix, hstack
    row = np.array([0,3,1,0])
    col = np.array([0,3,1,2])
    data = np.array([4,5,7,9])
    
    temp = coo_matrix((data, (row, col)))
    temp_stack = coo_matrix([0, 11,22,33], ([0, 1,2,3], [0, 0,0,0]))
    temp_res = hstack(temp, temp_stack)
    

    我得到一个错误 coo_matrix 是不可下标的,但我不明白为什么,似乎我在连接兼容维的矩阵。

    0 回复  |  直到 7 年前
        1
  •  1
  •   Warren Weckesser    7 年前

    首先要注意的是 hstack 应为包含要堆叠的数组的元组,因此应使用 hstack((temp, temp_stack)) .

    temp 有形状的 (4, 4) 和 temp_stack 有形状的 (1, 4) . 这些形状不可能 hstack公司 埃德。你希望结果是什么样的?如果您试图创建一个具有形状的结果 (5, 4) ,使用 vstack :

    In [28]: result = vstack((temp, temp_stack))
    
    In [29]: result.A
    Out[29]: 
    array([[ 4,  0,  9,  0],
           [ 0,  7,  0,  0],
           [ 0,  0,  0,  0],
           [ 0,  0,  0,  5],
           [ 0, 11, 22, 33]], dtype=int64)
    

    临时烟囱 成形 (4, 1) ,然后通过在 coo_matrix :

    In [38]: temp_stack = coo_matrix(([0, 11, 22, 33], ([0, 1, 2, 3], [0, 0, 0, 0])))
    
    In [39]: temp_stack.shape
    Out[39]: (4, 1)
    
    In [40]: result = hstack((temp, temp_stack))
    
    In [41]: result.A
    Out[41]: 
    array([[ 4,  0,  9,  0,  0],
           [ 0,  7,  0,  0, 11],
           [ 0,  0,  0,  0, 22],
           [ 0,  0,  0,  5, 33]], dtype=int64)
    

    顺便说一句,我认为这是一个神经病

    temp_stack = coo_matrix([0, 11,22,33], ([0, 1,2,3], [0, 0,0,0]))
    

    不会引发错误。相当于打电话

    temp_stack = coo_matrix(arg1=[0, 11,22,33], shape=([0, 1,2,3], [0, 0,0,0]))
    

    还有那个 shape 值显然无效。打电话给 首席运营官矩阵 应该引起 ValueError . 我在SciPy github站点上为此创建了一个问题: https://github.com/scipy/scipy/issues/9919