あなたの主な問題は、バイナリ化されたy
ものがメモリに収まらないことです。これを回避するために、スパース配列を使用できます。
>>> import numpy as np
>>> from scipy.sparse import csc_matrix
>>> y = np.random.randint(0, 10000, size=5000000) # 5M random integers [0,10K)
y
次のように、これらのラベルを5M x 10K
疎行列に変換できます。
>>> dtype = np.uint8 # change to np.bool if you want boolean or other data type
>>> rows = np.arange(y.size) # each of the elements of `y` is a row itself
>>> cols = y # `y` indicates the column that is going to be flagged
>>> data = np.ones(y.size, dtype=dtype) # Set to `1` each (row,column) pair
>>> ynew = csc_matrix((data, (rows, cols)), shape=(y.size, y.max()+1), dtype=dtype)
ynew
は、各行が 1 つのエントリを除いてゼロでいっぱいのスパース行列です。
>>> ynew
<5000000x10000 sparse matrix of type '<type 'numpy.uint8'>'
with 5000000 stored elements in Compressed Sparse Column format>
スパース行列を処理する方法を学ぶためにコードを調整する必要がありますが、おそらく最良の選択です。さらに、次のように疎行列から完全な行または列を復元できます。
>>> row0 = ynew[0].toarray() # row0 is a standard numpy array
文字列ラベルまたは任意のデータ型のラベルの場合:
>>> y = ['aaa' + str(i) for i in np.random.randint(0, 10000, size=5000000)] # e.g. 'aaa9937'
まず、ラベルから整数へのマッピングを抽出します。
>>> labels = np.unique(y) # List of unique labels
>>> mapping = {u:i for i,u in enumerate(labels)}
>>> inv_mapping = {i:u for i,u in enumerate(labels)} # Only needed if you want to recover original labels at some point
上記mapping
は、各ラベルを整数にマップします (一意のセットに格納されている順序に基づきますlabels
)。
そして、疎行列を再度作成します。
>>> N, M = len(y), labels.size
>>> dtype = np.uint8 # change np.bool if you want boolean
>>> rows = np.arange(N)
>>> cols = [mapping[i] for i in y]
>>> data = np.ones(N, dtype=dtype)
>>> ynew = csc_matrix((data, (rows, cols)), shape=(N, M), dtype=dtype)
label X
将来、元のラベルがどのラベルにマップされるかを知りたい場合は、逆マッピングを作成できます (必須ではありません) 。
>>> inv_mapping = {i:u for i,u in enumerate(labels)}
>>> inv_mapping[10] # ---> something like 'aaaXXX'