Skip to content

Instantly share code, notes, and snippets.

@luispedro
Created September 21, 2010 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luispedro/589685 to your computer and use it in GitHub Desktop.
Save luispedro/589685 to your computer and use it in GitHub Desktop.
Load a scipy.sparse.csr_matrix
# Load a sparse matrix.
import numpy as np
from scipy import sparse
def load_sparse(filename, dtype=np.float32):
with file(filename) as input:
ny,nx = input.readline().strip().split()
nelems = int(input.readline().strip())
data = np.empty(nelems, dtype=dtype)
indices = []
indptr = []
for line in input:
y,x,val = line.strip().split()
data[len(indices)] = float(val)
while int(y) >= len(indptr):
indptr.append(len(indices))
indices.append(int(x))
indptr.append(len(indices))
if len(indices) != len(data): raise IOError('Not enough data')
if len(indptr) != int(ny)+1: raise IOError('Not enough rows')
return sparse.csr_matrix((data,indices,indptr), dtype=dtype)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment