💬
scipyのcsr_matrixとは?
概要
csr_matrix は SciPy の疎行列(sparse matrix)ライブラリで提供される、
「圧縮行形式(Compressed Sparse Row, CSR)」 の行列クラスです。
なぜ疎行列が必要?
行列のほとんどが 0 のとき(=疎行列)、通常の NumPy 配列で表現すると 無駄なメモリがかかる。
csr_matrix は、非ゼロ要素だけを効率的に保存・計算するための仕組みです。
実例
たとえば、以下のような特徴があったとします:
ユーザー1(行0)が「男性(特徴列2)」、年齢30(特徴列5)
ユーザー2(行1)が「女性(特徴列3)」、年齢25(特徴列4)
このように、ユーザー×特徴の「1だけが入る」行列を作るのに便利です。
from scipy.sparse import csr_matrix
data = [1, 2, 3, 4] # すべての特徴の値(1など)
row = [0, 0, 1, 1] # ユーザー0, 0, 1, 1
col = [2, 5, 3, 4] # 特徴の列番号
shape = (2, 6) # ユーザー2人、特徴6個
print('csr')
print(csr)
print('arrayに戻すと')
print(csr.toarray())
出力
csr
<Compressed Sparse Row sparse matrix of dtype 'int64'
with 4 stored elements and shape (2, 6)>
Coords Values
(0, 2) 1
(0, 5) 2
(1, 3) 3
(1, 4) 4
arrayに戻すと
[[0 0 1 0 0 2]
[0 0 0 3 4 0]]
このようにcsrは0を含まないためスパースデータを効率的に処理できます。
Discussion