如何有效地加载稀疏矩阵?

时间:2018-12-28 07:59:12

标签: python pandas numpy scipy sparse-matrix

给出具有以下结构的文件:

  • 单列线为键
  • 键的非零值

例如:

abc
ef 0.85
kl 0.21
xyz 0.923
cldex 
plax 0.123
lion -0.831

如何创建稀疏矩阵csr_matrix

('abc', 'ef') 0.85
('abc', 'kl') 0.21
('abc', 'xyz') 0.923
('cldex', 'plax') 0.123
('cldex', 'lion') -0.31

我尝试过:

from collections import defaultdict

x = """abc
ef  0.85
kl  0.21
xyz 0.923
cldex 
plax    0.123
lion    -0.831""".split('\n')

k1 = ''
arr = defaultdict(dict)
for line in x:
    line = line.strip().split('\t')
    if len(line) == 1:
        k1 = line[0]
    else:
        k2, v = line
        v = float(v)
        arr[k1][k2] = v

[出]

>>> arr
defaultdict(dict,
            {'abc': {'ef': 0.85, 'kl': 0.21, 'xyz': 0.923},
             'cldex': {'plax': 0.123, 'lion': -0.831}})

拥有dict嵌套结构并不像scipy稀疏矩阵结构那样方便。

是否可以轻松地将上述给定格式的文件读取到任何scipy稀疏矩阵对象中?

3 个答案:

答案 0 :(得分:5)

将@hpaulj的注释转换为答案,您可以迭代地添加到行和列索引的列表中。稍后,使用pd.factorizenp.uniquesklearn的{​​{1}}将它们分解,然后转换为稀疏的LabelEncoder

coo_matrix

from scipy import sparse
import numpy as np
import pandas as pd

rows, cols, values = [], [], []
for line in x.splitlines():
   if ' ' not in line.strip():
       ridx = line
   else:
       cidx, value = line.strip().split()       
       rows.append(ridx)
       cols.append(cidx)
       values.append(value)

rows, rinv = pd.factorize(rows)
cols, cinv = pd.factorize(cols)

sp = sparse.coo_matrix((values, (rows, cols)), dtype=np.float32)
# sp = sparse.csr_matrix((np.array(values, dtype=np.float), (rows, cols)))

如果需要,可以使用sp.toarray() array([[ 0.85 , 0.21 , 0.923, 0. , 0. ], [ 0. , 0. , 0. , 0.123, -0.831]], dtype=float32) rinv进行逆映射(将索引转换为字符串)。

答案 1 :(得分:1)

当前,在0.23版中,熊猫已经实现了系列和数据框的稀疏版本。巧合的是,您的数据可以看作是具有多级索引的系列,因此您可以利用这一事实来构建稀疏矩阵。另外,如果一致,则可以使用几行熊猫来读取格式,例如:

import numpy as np
import pandas as pd
from io import StringIO

lines = StringIO("""abc
ef  0.85
kl  0.21
xyz 0.923
cldex
plax    0.123
lion    -0.831""")

# load Series
s = pd.read_csv(lines, delim_whitespace=True, header=None, names=['k', 'v'])
s = s.assign(k2=pd.Series(np.where(np.isnan(s.v), s.k, np.nan)).ffill())
result = s[~np.isnan(s.v)].set_index(['k2', 'k']).squeeze()

# convert to sparse matrix (csr)
ss = result.to_sparse()
coo, rows, columns = ss.to_coo(row_levels=['k'], column_levels=['k2'], sort_labels=True)
print(coo.tocsr())

输出

  (0, 0)    0.85
  (1, 0)    0.21
  (2, 1)    -0.831
  (3, 1)    0.12300000000000001
  (4, 0)    0.9229999999999999

to_coo方法不仅返回矩阵,还返回列和行标签,因此也进行逆映射。在上面的示例中,返回以下内容:

['ef', 'kl', 'lion', 'plax', 'xyz']
['abc', 'cldex']

'ef'对应于行的索引0'abc'对应于列的索引0

答案 2 :(得分:0)

鉴于您有字典

dox = {'abc': {'ef': 0.85, 'kl': 0.21, 'xyz': 0.923},'cldex': {'plax': 0.123, 'lion': -0.831}}

这应该可以帮助您将其带到稀疏性皮肤上:

indptr = [0]
indices = []
data = []
vocabulary = {}

for d in dox:
     for term in dox[d]:
         index = vocabulary.setdefault(term, len(vocabulary))
         indices.append(index)
         data.append(dox[d][term])
         indptr.append(len(indices))

mat = csr_matrix((data, indices, indptr), dtype=float)

这利用scipy的example进行增量矩阵构建。输出如下:

mat.todense()

enter image description here

相关问题