Skip to content

Instantly share code, notes, and snippets.

@jasongrout
Forked from luispedro/load_sparse.py
Created April 18, 2011 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasongrout/925152 to your computer and use it in GitHub Desktop.
Save jasongrout/925152 to your computer and use it in GitHub Desktop.
# Load a sparse matrix.
import numpy as np
from scipy import sparse
def mymethod():
print 'hi'
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)
@jasongrout
Copy link
Author

Test comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment