9

質問:リスト内の値に基づいて、1つのスパース行列を2つに分割するにはどうすればよいですか?

つまり、スパース行列がありXます。

>>print type(X)
<class 'scipy.sparse.csr.csr_matrix'>

リストのリストとして頭の中で視覚化すると、次のようになります。

>>print X.todense()
[[1,3,4]
 [3,2,2]
 [4,8,1]]

そして、私はこのようなリストを持っていますy

y = [-1, 
      3, 
     -4]

の対応する値が正か負かXに応じて、2つのスパース行列に分離するにはどうすればよいですか?yたとえば、どうすれば次のようになりますか。

>>print X_pos.todense()
 [[3,2,2]] 
>>print X_neg.todense()
 [[1,3,4]
  [4,8,1]]

結果(X_posおよびX_neg)も、最初はスパース行列を分割しているだけなので、明らかにスパース行列になるはずです。

ありがとう!

4

1 に答える 1

8

np.where正と負の値の 2 つのインデックス配列を生成するために使用しy、それらを使用して疎行列にインデックスを付けます。

>>> X = csr_matrix([[1,3,4], [3,2,2], [4,8,1]])
>>> y = np.array([-1, 3, -4])
>>> y_pos = np.where(y > 0)[0]
>>> y_neg = np.where(y < 0)[0]
>>> X_pos = X[y_pos]
>>> X_neg = X[y_neg]

目的の要素を含む CSR マトリックスを作成する必要があります。

>>> X_pos
<1x3 sparse matrix of type '<type 'numpy.int64'>'
    with 3 stored elements in Compressed Sparse Row format>
>>> X_neg
<2x3 sparse matrix of type '<type 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>
>>> X_pos.A
array([[3, 2, 2]])
>>> X_neg.A
array([[1, 3, 4],
       [4, 8, 1]])
于 2012-08-31T11:14:53.553 に答える