2016-06-09 11 views
2

Ich habe 3 dünn besetzte Matrizen:Wie stacked mehrere dünn besetzte Matrizen (Feature-Matrizen)?

In [39]: 

mat1 


Out[39]: 
(1, 878049) 
<1x878049 sparse matrix of type '<type 'numpy.int64'>' 
    with 878048 stored elements in Compressed Sparse Row format> 

In [37]: 

mat2 


Out[37]: 
(1, 878049) 
<1x878049 sparse matrix of type '<type 'numpy.int64'>' 
    with 744315 stored elements in Compressed Sparse Row format> 

In [35]: 

mat3 



Out[35]: 
(1, 878049) 
<1x878049 sparse matrix of type '<type 'numpy.int64'>' 
    with 788618 stored elements in Compressed Sparse Row format> 

Vom documentation, ich gelesen, dass es zu hstack, möglich ist vstack und concatenate sie solche Art von Matrizen. Also habe ich versucht, sie hstack:

import numpy as np 

matrix1 = np.hstack([[address_feature, dayweek_feature]]).T 
matrix2 = np.vstack([[matrix1, pddis_feature]]).T 


X = matrix2 

jedoch die Abmessungen stimmen nicht überein:

In [41]: 

X_combined_features.shape 

Out[41]: 

(2, 1) 

Bitte beachte, dass ich eine solche Matrizen bin Stapeln, da ich sie mit einem Scikit-Learn verwenden möchten Klassifikationsalgorithmus . Daher Wie sollte ich hstack eine Reihe von verschiedenen dünn besetzten Matrizen?.

Antwort

2

Verwenden Sie die sparse-Versionen von vstack. Als allgemeine Regel müssen Sie sparse Funktionen und Methoden verwenden, nicht die numpy solche mit ähnlichem Namen. sparse Matrizen sind keine Unterklassen von numpyndarray.

Aber Ihre 3 drei Matrizen sehen nicht spärlich aus. Sie sind 1x878049. Einer hat 878048 Nicht-Null-Elemente - das bedeutet nur ein 0-Element.

So könnte man genauso gut sie in dichte Anordnungen gedreht (mit .toarray() oder .A) und np.hstack oder np.vstack verwenden.

np.hstack([address_feature.A, dayweek_feature.A]) 

Und verwenden Sie nicht die doppelten Klammern. Alle Verkettungsfunktionen nehmen eine einfache Liste oder ein Tupel der Arrays. Und diese Liste kann mehr als 2 Arrays haben

In [296]: A=sparse.csr_matrix([0,1,2,0,0,1]) 

In [297]: B=sparse.csr_matrix([0,0,0,1,0,1]) 

In [298]: C=sparse.csr_matrix([1,0,0,0,1,0]) 

In [299]: sparse.vstack([A,B,C]) 
Out[299]: 
<3x6 sparse matrix of type '<class 'numpy.int32'>' 
    with 7 stored elements in Compressed Sparse Row format> 

In [300]: sparse.vstack([A,B,C]).A 
Out[300]: 
array([[0, 1, 2, 0, 0, 1], 
     [0, 0, 0, 1, 0, 1], 
     [1, 0, 0, 0, 1, 0]], dtype=int32) 

In [301]: sparse.hstack([A,B,C]).A 
Out[301]: array([[0, 1, 2, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0]], dtype=int32) 

In [302]: np.vstack([A.A,B.A,C.A]) 
Out[302]: 
array([[0, 1, 2, 0, 0, 1], 
     [0, 0, 0, 1, 0, 1], 
     [1, 0, 0, 0, 1, 0]], dtype=int32) 
+0

Danke für die Hilfe, große Antwort !. –

Verwandte Themen