将 python 稀疏矩阵 dict 转换为 scipy 稀疏矩阵

2024-03-03

我正在使用Pythonscikit-learn对于文档聚类,我有一个稀疏矩阵存储在dict object:

例如:

doc_term_dict = { ('d1','t1'): 12,             \
                  ('d2','t3'): 10,             \
                  ('d3','t2'):  5              \
                  }                            # from mysql data table 
<type 'dict'>

我想用scikit-learn在输入矩阵类型为的情况下进行聚类scipy.sparse.csr.csr_matrix

Example:

(0, 2164)   0.245793088885
(0, 2076)   0.205702177467
(0, 2037)   0.193810934784
(0, 2005)   0.14547028437
(0, 1953)   0.153720023365
...
<class 'scipy.sparse.csr.csr_matrix'>

我找不到转换的方法dict到这个 csr-matrix (我从未使用过scipy.)


非常简单。首先读取字典并将键转换为适当的行和列。 Scipy 支持(并为此目的推荐)坐标格式 http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html#scipy.sparse.coo_matrix对于稀疏矩阵。

Pass it data, row, and column, where A[row[k], column[k] = data[k](对于所有 k) 定义矩阵。然后让 Scipy 进行到 CSR 的转换。

请检查一下,我的行和列是否按照您想要的方式排列,我可能会将它们转置。我还假设输入是 1 索引的。

我的代码如下打印:

(0, 0)        12
(1, 2)        10
(2, 1)        5

Code:

#!/usr/bin/env python3
#http://stackoverflow.com/questions/26335059/converting-python-sparse-matrix-dict-to-scipy-sparse-matrix

from scipy.sparse import csr_matrix, coo_matrix

def convert(term_dict):
    ''' Convert a dictionary with elements of form ('d1', 't1'): 12 to a CSR type matrix.
    The element ('d1', 't1'): 12 becomes entry (0, 0) = 12.
    * Conversion from 1-indexed to 0-indexed.
    * d is row
    * t is column.
    '''
    # Create the appropriate format for the COO format.
    data = []
    row = []
    col = []
    for k, v in term_dict.items():
        r = int(k[0][1:])
        c = int(k[1][1:])
        data.append(v)
        row.append(r-1)
        col.append(c-1)
    # Create the COO-matrix
    coo = coo_matrix((data,(row,col)))
    # Let Scipy convert COO to CSR format and return
    return csr_matrix(coo)

if __name__=='__main__':
    doc_term_dict = { ('d1','t1'): 12,             \
                ('d2','t3'): 10,             \
                ('d3','t2'):  5              \
                }   
    print(convert(doc_term_dict))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 python 稀疏矩阵 dict 转换为 scipy 稀疏矩阵 的相关文章

随机推荐