Skip to content

Instantly share code, notes, and snippets.

@fannix
Created February 18, 2012 08:34
Show Gist options
  • Save fannix/1858252 to your computer and use it in GitHub Desktop.
Save fannix/1858252 to your computer and use it in GitHub Desktop.

Revisions

  1. fannix revised this gist Feb 18, 2012. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions load_and_save.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    """http://stackoverflow.com/questions/6282432/load-sparse-array-from-npy-file
    """
    import random
    import scipy.sparse as sparse
    import scipy.io
  2. fannix revised this gist Feb 18, 2012. 1 changed file with 9 additions and 9 deletions.
    18 changes: 9 additions & 9 deletions load_and_save.py
    Original file line number Diff line number Diff line change
    @@ -3,17 +3,17 @@
    import scipy.io
    import numpy as np

    def save_sparse_matrix(filename,x):
    x_coo=x.tocoo()
    row=x_coo.row
    col=x_coo.col
    data=x_coo.data
    shape=x_coo.shape
    np.savez(filename,row=row,col=col,data=data,shape=shape)
    def save_sparse_matrix(filename, x):
    x_coo = x.tocoo()
    row = x_coo.row
    col = x_coo.col
    data = x_coo.data
    shape = x_coo.shape
    np.savez(filename, row=row, col=col, data=data, shape=shape)

    def load_sparse_matrix(filename):
    y=np.load(filename)
    z=sparse.coo_matrix((y['data'],(y['row'],y['col'])),shape=y['shape'])
    y = np.load(filename)
    z = sparse.coo_matrix((y['data'], (y['row'], y['col'])), shape=y['shape'])
    return z

    N=20000
  3. fannix created this gist Feb 18, 2012.
    25 changes: 25 additions & 0 deletions load_and_save.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    import random
    import scipy.sparse as sparse
    import scipy.io
    import numpy as np

    def save_sparse_matrix(filename,x):
    x_coo=x.tocoo()
    row=x_coo.row
    col=x_coo.col
    data=x_coo.data
    shape=x_coo.shape
    np.savez(filename,row=row,col=col,data=data,shape=shape)

    def load_sparse_matrix(filename):
    y=np.load(filename)
    z=sparse.coo_matrix((y['data'],(y['row'],y['col'])),shape=y['shape'])
    return z

    N=20000
    x = sparse.lil_matrix( (N,N) )
    for i in xrange(N):
    x[random.randint(0,N-1),random.randint(0,N-1)]=random.randint(1,100)

    save_sparse_matrix('/tmp/my_array',x)
    load_sparse_matrix('/tmp/my_array.npz').tolil()