2017-02-08 3 views
1

Ich bin neu in Python, verwende ich folgenden Weg, um die Daten in einem Link-Liste-Matrix-Format zu speichern.zufällige split sparse.lil_matrix in Python

>>> from scipy import sparse,random 
>>> m = 2 
>>> X = [sparse.lil_matrix((5,5)) for i in range(m)] 
>>> X[0][0,1] = 1 
>>> X[0][2,3] = 1 
>>> X[1][0,4] = 1 
>>> X[1][1,4] = 1 
>>> X[1][2,4] = 1 
>>> X 

    [<5x5 sparse matrix of type '<type 'numpy.float64'>' 
     with 2 stored elements in LInked List format>, <5x5 sparse matrix of type '<type 'numpy.float64'>' 
     with 3 stored elements in LInked List format>] 

Gibt es eine Möglichkeit zufällig diese lil_matrix X als Ausbildung zu teilen (75%) und Testset (25%)

Antwort

0

Zuerst Ihre X ist eine Liste mit zwei schwach besetzte Matrizen.

Aber wenn ich eine Sparse Matrix zu machen, kann ich wählen Zeilen mit einfacher Indizierung:

In [41]: M=sparse.lil_matrix(np.eye(5)) 

In [42]: M 
Out[42]: 
<5x5 sparse matrix of type '<class 'numpy.float64'>' 
    with 5 stored elements in LInked List format> 

In [43]: M.A 
Out[43]: 
array([[ 1., 0., 0., 0., 0.], 
     [ 0., 1., 0., 0., 0.], 
     [ 0., 0., 1., 0., 0.], 
     [ 0., 0., 0., 1., 0.], 
     [ 0., 0., 0., 0., 1.]]) 

In [44]: M[[0,1,4],:] 
Out[44]: 
<3x5 sparse matrix of type '<class 'numpy.float64'>' 
    with 3 stored elements in LInked List format> 

In [45]: M[[2,3],:] 
Out[45]: 
<2x5 sparse matrix of type '<class 'numpy.float64'>' 
    with 2 stored elements in LInked List format> 

In [46]: M[[2,3],:].A 
Out[46]: 
array([[ 0., 0., 1., 0., 0.], 
     [ 0., 0., 0., 1., 0.]]) 

Row Indizierung von schwach besetzten Matrizen ist nicht so schnell wie mit dichten Arrays, sondern arbeitet, zumindest für lil und csr Formate.

Es gibt nichts besonderes im Paket scipy.sparse zum Teilen einer Matrix wie diesem. Sie müssten die zufällige Indizierung selbst erarbeiten.

sklearn.model_selection.train_test_split Griffe Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes. den Code Tracing, die tatsächliche Spaltung mit utils.safe_indexing(X, indices) getan wird, die eine Vielzahl von X verarbeiten kann. Aber es ist wie eine sparse Matrix indexiert, wie ich gezeigt habe. Es kann ein csr Format anstelle von lil erfordern.