How to load a sparse matrix efficiently?

Viewed 704

Given a file with this structure:

  • Single column lines are keys
  • Non-zero values of the keys

For example:

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

How to create a sparse matrix, csr_matrix?

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

I've tried:

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

[out]

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

Having the nested dict structure isn't as convenient as the scipy sparse matrix structure.

Is there a way to read the file in the given format above easily into any of the scipy sparse matrix object?

3 Answers

Converting @hpaulj's comment into answer, you can iteratively add to lists of row and column indices. Later, factorise these using pd.factorize, np.unique, or sklearn's LabelEncoder, and convert to a sparse 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)

If required, you can use rinv and cinv to perform an inverse mapping (convert indices to strings).

Currently, in version 0.23, pandas have implemented sparse versions of Series and Data-Frames. Coincidentally your data can be seen as a Series with multi-level index, so you could exploit this fact to build the sparse matrix. In addition, if consistent, your format can be read using a few lines of pandas, for example:

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

Output

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

The to_coo method not only returns the matrix, but also the columns and row labels, hence doing also the inverse mapping. In the above example returns the following:

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

Where 'ef' corresponds to index 0 of the rows and 'abc' corresponds to index 0 of the columns.

Given that you have the dict

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

this should help you take it to a sparsematrix:

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)

This utilizes scipy's example for an incremental matrix build. Here is the output:

mat.todense()

enter image description here

Related