2017-07-23 5 views
1

a, b sind 1D numpyndarray gleicher Größe mit ganzzahligem Datentyp.Numpy (spärlich) wiederholtes Indexinkrement

C ist ein 2D scipy.sparse.lil_matrix.

Wenn die Indizierung [a, b] wiederholten Index enthält, wird C[a, b] += np.array([1]) immer C erhöht genau einmal für jede eindeutige Indizierung von C von [a, b]?

Hat die Dokumentation das erwähnt?

Beispiel:

import scipy.sparse as ss 
import numpy as np 
C = ss.lil_matrix((3,2), dtype=int) 
a = np.array([0, 1, 2] * 4) 
b = np.array([0, 1] * 6) 
C[a, b] += np.array([1]) 
print(C.todense(), '\n') 
C[a, b] += np.array([1]) 
print(C.todense()) 

Ergebnis:

[[1 1] 
[1 1] 
[1 1]] 

[[2 2] 
[2 2] 
[2 2]] 

Antwort

1

Ich weiß nicht, dass es

dokumentiert ist

Es gut ist bekannt, dass dichte Anordnungen nur einmal pro eindeutigen Index aufgrund Pufferung eingestellt . Wir müssen add.at verwenden, um ungepufferte Addition zu erhalten.

In [966]: C=sparse.lil_matrix((3,2),dtype=int) 
In [967]: Ca=C.A 
In [968]: Ca += 1 
In [969]: Ca 
Out[969]: 
array([[1, 1], 
     [1, 1], 
     [1, 1]]) 

In [970]: Ca=C.A 
In [973]: np.add.at(Ca,(a,b),1) 
In [974]: Ca 
Out[974]: 
array([[2, 2], 
     [2, 2], 
     [2, 2]]) 

Ihr Beispiel zeigt, dass die lil indiziert Einstellung als auch im gepufferten Sinne verhält. Aber ich müsste mir den Code ansehen, um genau zu sehen, warum.

Es ist dokumentiert, dass coo Stil-Eingaben über Duplikate summiert werden.

In [975]: M=sparse.coo_matrix((np.ones_like(a),(a,b)), shape=(3,2)) 
In [976]: print(M) 
    (0, 0) 1 
    (1, 1) 1 
    (2, 0) 1 
    (0, 1) 1 
    (1, 0) 1 
    (2, 1) 1 
    (0, 0) 1 
    (1, 1) 1 
    (2, 0) 1 
    (0, 1) 1 
    (1, 0) 1 
    (2, 1) 1 
In [977]: M.A 
Out[977]: 
array([[2, 2], 
     [2, 2], 
     [2, 2]]) 
In [978]: M 
Out[978]: 
<3x2 sparse matrix of type '<class 'numpy.int32'>' 
    with 12 stored elements in COOrdinate format> 
In [979]: M.tocsr() 
Out[979]: 
<3x2 sparse matrix of type '<class 'numpy.int32'>' 
    with 6 stored elements in Compressed Sparse Row format> 
In [980]: M.sum_duplicates() 
In [981]: M 
Out[981]: 
<3x2 sparse matrix of type '<class 'numpy.int32'>' 
    with 6 stored elements in COOrdinate format> 

Punkte werden in coo Format gespeichert, wie es eingegeben wird, aber wenn für die Anzeige oder die Berechnung (CSR-Format) Duplikate verwendet werden summiert.

Verwandte Themen