Created
September 21, 2010 13:28
-
-
Save luispedro/589685 to your computer and use it in GitHub Desktop.
Load a scipy.sparse.csr_matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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