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

3

给定一个这样的结构文件:

  • 单列行是键
  • 键的非零值

例如:

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

使用嵌套字典结构不如使用scipy的稀疏矩阵结构方便。

是否有一种方法可以将上述给定格式的文件轻松地读入任何scipy稀疏矩阵对象中?


1
Scipy稀疏矩阵的所有格式都具有简单的数字索引。因此,第一步是将字符串映射为唯一数字,例如'abc'=>0,'cldex'=>1,'ef'=>0等。然后创建'coo'输入样式——'data'、'row'、'col'。 - hpaulj
3个回答

5

将@hpaulj的评论转化为答案,您可以迭代地添加行和列索引列表。之后,使用pd.factorize、np.unique或sklearn的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)

如果需要的话,您可以使用rinvcinv来执行反向映射(将索引转换为字符串)。

1

目前,pandas在0.23版本中已经实现了Series和Data-Frames的稀疏版本。恰巧,您的数据可以被视为带有多级索引的Series,因此您可以利用这一事实来构建稀疏矩阵。此外,如果格式一致,您的格式可以使用几行pandas代码进行读取,例如:

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


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接