4

文字列ラベルをワンホット エンコーディングにエンコードしようとすると、メモリの問題が発生し続けます。約 500 万行と約 10000 の異なるラベルがあります。次のことを試しましたが、メモリエラーが発生し続けます:

from sklearn import preprocessing
lb = preprocessing.LabelBinarizer()
label_fitter = lb.fit(y)
y = label_fitter.transform(y)

私も次のようなことを試しました:

import numpy as np

def one_hot_encoding(y):
    unique_values = set(y)
    label_length = len(unique_values)
    enu_uniq = zip(unique_values , range(len(unique_values)))
    dict1 = dict(enu_uniq)
    values = []
    for i in y:
        temp = np.zeros((label_length,), dtype="float32")
        if i in dict1:
            temp[dict1[i]] = 1.0
        values.append(temp)
    return np.array(values)

まだメモリエラーが発生しています。ヒントはありますか?ここでスタックに同じことを尋ねる人もいますが、答えは役に立たないようです。

4

2 に答える 2

3

あなたの主な問題は、バイナリ化された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'
于 2016-12-09T12:54:11.017 に答える