Fastest way to convert a Numpy array into a sparse

2020-07-13 08:48发布

I'm interested in converting a numpy array into a sparse dictionary as quickly as possible. Let me elaborate:

Given the array:

numpy.array([12,0,0,0,3,0,0,1])

I wish to produce the dictionary:

{0:12, 4:3, 7:1}

As you can see, we are simply converting the sequence type into an explicit mapping from indices that are nonzero to their values.

In order to make this a bit more interesting, I offer the following test harness to try out alternatives:

from timeit import Timer

if __name__ == "__main__":
  s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector =         numpy.random.poisson(0.1, size=10000);"

  ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )"
             , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )"
             , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )"
             , "n = vector > 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))"
             , "i = flatnonzero(vector); v = vector[vector > 0]; dict(izip(i,v))"
             , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )"
             , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )"
             , "dict( (i, x) for i,x in enumerate(vector) if x > 0);"
             ]
  for m in ms:
    print "  %.2fs" % Timer(m, s).timeit(1000), m

I'm using a poisson distribution to simulate the sort of arrays I am interested in converting.

Here are my results so far:

   0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) )
   0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) )
   0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) )
   0.67s n = vector > 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))
   0.81s i = flatnonzero(vector); v = vector[vector > 0]; dict(izip(i,v))
   1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )
   1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )
   4.90s dict( (i, x) for i,x in enumerate(vector) if x > 0);

As you can see, the fastest solution I have found is

n = vector > 0;
i = numpy.arange(len(vector))[n]
v = vector[n]
dict(izip(i,v))

Any faster way?

Edit: The step

i = numpy.arange(len(vector))[n]

Seems particularly clumsy- generating an entire array before selecting only some elements, particularly when we know it might only be around 1/10 of the elements getting selected. I think this might still be improved.

5条回答
ら.Afraid
2楼-- · 2020-07-13 09:30

The following seems to be a significant improvement:

i = np.flatnonzero(vector)
dict.fromkeys(i.tolist(), vector[i].tolist())

Timing:

import numpy as np
from itertools import izip

vector = np.random.poisson(0.1, size=10000)

%timeit f = np.flatnonzero(vector); dict( izip( f, vector[f] ) )
# 1000 loops, best of 3: 951 µs per loop

%timeit f = np.flatnonzero(vector); dict.fromkeys(f.tolist(), vector[f].tolist())
# 1000 loops, best of 3: 419 µs per loop

I also tried scipy.sparse.dok_matrix and pandas.DataFrame.to_dict but in my testing they were slower than the original.

查看更多
淡お忘
3楼-- · 2020-07-13 09:31
>>> a=np.array([12,0,0,0,3,0,0,1])
>>> {i:a[i] for i in np.nonzero(a)[0]}
{0: 12, 4: 3, 7: 1}
查看更多
We Are One
4楼-- · 2020-07-13 09:38

You could use np.unique with return_index=True:

>>> import numpy as np

>>> arr = np.array([12,0,0,0,3,0,0,1])

>>> val, idx = np.unique(arr, return_index=True)
>>> mask = val != 0                                # exclude zero
>>> dict(zip(idx[mask], val[mask]))                # create the dictionary
{0: 12, 4: 3, 7: 1}

It's generally faster to iterate over lists than numpy.arrays so you could be faster when you convert them to lists with tolist:

>>> dict(zip(idx[mask].tolist(), val[mask].tolist()))

Timing

For short arrays this approach may be slower but it's according to my timings faster than the other approaches for big arrays:

import numpy as np
from scipy.sparse import csr_matrix

arr = np.random.randint(0, 10, size=10000)  # 10k items
arr[arr < 7] = 0                            # make it sparse

# ----------

%timeit {i:arr[i] for i in np.nonzero(arr)[0]}
# 3.7 ms ± 51 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# ----------

%%timeit

val, idx = np.unique(arr, return_index=True)
mask = val != 0
dict(zip(idx[mask].tolist(), val[mask].tolist()))

# 844 µs ± 42.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# ----------

%%timeit

m=csr_matrix(a)

d={}
for i in m.nonzero()[1]:
    d[i]=m[0,i]

# 1.52 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
查看更多
够拽才男人
5楼-- · 2020-07-13 09:39

use the sparse matrix in scipy as bridge:

from scipy.sparse import *
import numpy
a=numpy.array([12,0,0,0,3,0,0,1])
m=csr_matrix(a)

d={}
for i in m.nonzero()[1]:
  d[i]=m[0,i]
print d
查看更多
Rolldiameter
6楼-- · 2020-07-13 09:40

Tried this?

from numpy import where

i = where(vector > 0)[0]

查看更多
登录 后发表回答