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

按索引访问coo_矩阵的类型错误

  •  1
  • Rocketq  · 技术社区  · 6 年前

    我有首席运营官矩阵 X 指标 trn_idx 我想通过它进入麦克斯特里克斯

    print (type(X  ), X.shape)
    print (type(trn_idx), trn_idx.shape)
    
    <class 'scipy.sparse.coo.coo_matrix'> (1503424, 2795253)
    <class 'numpy.ndarray'> (1202739,)
    

    这样打电话:

    X[trn_idx]
    TypeError: only integer scalar arrays can be converted to a scalar index
    

    不管怎样:

     X[trn_idx.astype(int)] #same error
    

    如何通过索引访问?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Warren Weckesser    6 年前

    这个 coo_matrix 类不支持索引。您必须将其转换为其他稀疏格式。

    下面是一个例子 库克矩阵 :

    In [19]: import numpy as np
    
    In [20]: from scipy.sparse import coo_matrix
    
    In [21]: m = coo_matrix([[0, 0, 0, 1], [2, 0, 0 ,0], [0, 0, 0, 0], [0, 3, 4, 0]])
    

    正在尝试索引 m 失败:

    In [22]: m[0,0]
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-22-1f78c188393f> in <module>()
    ----> 1 m[0,0]
    
    TypeError: 'coo_matrix' object is not subscriptable
    
    In [23]: idx = np.array([2, 3])
    
    In [24]: m[idx]
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-24-a52866a6fec6> in <module>()
    ----> 1 m[idx]
    
    TypeError: only integer scalar arrays can be converted to a scalar index
    

    如果你改变信仰 对于CSR矩阵,可以用 idx :

    In [25]: m.tocsr()[idx]
    Out[25]: 
    <2x4 sparse matrix of type '<class 'numpy.int64'>'
        with 2 stored elements in Compressed Sparse Row format>
    

    如果要进行更多的索引,最好将新数组保存在变量中,并根据需要使用它:

    In [26]: a = m.tocsr()
    
    In [27]: a[idx]
    Out[27]: 
    <2x4 sparse matrix of type '<class 'numpy.int64'>'
        with 2 stored elements in Compressed Sparse Row format>
    
    In [28]: a[0,0]
    Out[28]: 0
    
        2
  •  0
  •   Poojan    6 年前

    试试看这个。

    https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.sparse.csr_matrix.todense.html

    在通过索引访问之前,需要转换为密集矩阵。
    尝试稀疏矩阵上的toArray()方法,然后可以通过索引进行访问。