2016-08-08 40 views
2

Ich habe eine sehr große spärliche Matrix vom Typ 'scipy.sparse.coo.coo_matrix'. Ich kann mit .tocsr() in csr konvertieren, aber .todense() funktioniert nicht, da das Array zu groß ist. Ich möchte in der Lage sein, Elemente aus der Matrix zu extrahieren, wie ich es mit einem regulären Array tun würde, so dass ich Zeilenelemente an eine Funktion übergeben kann.Zugriff auf spärliche Matrixelemente

Als Referenz, wenn es gedruckt, sieht die Matrix wie folgt:

(7, 0) 0.531519363001 
(48, 24) 0.400946334437 
(70, 6) 0.684460955022 
... 
+1

Die Das 'csr'-Format akzeptiert die Indizierung genauso wie dichte Arrays (wenn auch nicht ganz so schnell). Das 'coo' Format nicht. Für ganze Zeilen möchten Sie viele tun: M1 = M.tocsr(); Zeile = M1 [i,:]. A' ('toarray()') unter der Annahme, dass die Funktion ein dichtes Array erwartet. – hpaulj

+0

Wie würdest du zum Beispiel die drei Zahlen am oberen Rand meines Ausdrucks herausziehen ((7, 0) 0.531519363001)? Ich weiß nicht, was die .A in Ihrem Beispiel tut, aber wenn ich diesen Teil überspringen, bekomme ich eine lange Reihe von [0 0 0 ... 0] – Helicity

Antwort

3

eine Matrix bilden mit 3 Elementen:

In [550]: M = sparse.coo_matrix(([.5,.4,.6],([0,1,2],[0,5,3])), shape=(5,7)) 

Es ist Standardanzeige (repr(M)):

In [551]: M 
Out[551]: 
<5x7 sparse matrix of type '<class 'numpy.float64'>' 
    with 3 stored elements in COOrdinate format> 

und Druckanzeige (str (M)) - sieht wie die Eingabe aus:

In [552]: print(M) 
    (0, 0) 0.5 
    (1, 5) 0.4 
    (2, 3) 0.6 

Konvertit csr Format:

In [553]: Mc=M.tocsr() 
In [554]: Mc[1,:] # row 1 is another matrix (1 row): 
Out[554]: 
<1x7 sparse matrix of type '<class 'numpy.float64'>' 
    with 1 stored elements in Compressed Sparse Row format> 

In [555]: Mc[1,:].A # that row as 2d array 
Out[555]: array([[ 0. , 0. , 0. , 0. , 0. , 0.4, 0. ]]) 

In [556]: print(Mc[1,:]) # like 2nd element of M except for row number 
    (0, 5) 0.4 

Einzelelement:

In [560]: Mc[1,5] 
Out[560]: 0.40000000000000002 

Die Datenattribute dieses Formats (wenn Sie möchten weiter graben)

In [562]: Mc.data 
Out[562]: array([ 0.5, 0.4, 0.6]) 
In [563]: Mc.indices 
Out[563]: array([0, 5, 3], dtype=int32) 
In [564]: Mc.indptr 
Out[564]: array([0, 1, 2, 3, 3, 3], dtype=int32) 
In [565]: M.data 
Out[565]: array([ 0.5, 0.4, 0.6]) 
In [566]: M.col 
Out[566]: array([0, 5, 3], dtype=int32) 
In [567]: M.row 
Out[567]: array([0, 1, 2], dtype=int32) 
+0

Wie kann ich die beiden Zahlen, die mit dem einzelnen Element verbunden sind extrahieren Ich komme von Mc [1,5] (in diesem Fall (0,5) wenn ich mich nicht irre)? – Helicity

+0

Ich denke rdist.row [i], rdist.col [i] würde die Zahlen bekommen, die ich will. – Helicity