Why reinvent the wheel? Use sklearn.feature_extraction.text.CountVectorizer :
Example:
from sklearn.feature_extraction.text import CountVectorizer from nltk import sent_tokenize text = """Пытаюсь преобразовать стоки в numpy массив с помощью one-hot-encoding на character уровне. В массиве 1.6кк строк при попытке преобразовать более +-200к строк выдает memory error. У меня вопрос в том, это физический предел моего ПК(8 гб) или можно как то обойти эту ошибку? Спасибо.""" sents = sent_tokenize(text) vect = CountVectorizer() X_vect = vect.fit_transform(sents)
Result:
In [6]: X_vect.A Out[6]: array([[0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 2, 1, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64) In [7]: vect.get_feature_names() Out[7]: ['200к', '6кк', 'character', 'encoding', 'error', 'hot', 'memory', 'numpy', 'one', 'более', 'вопрос', 'выдает', 'гб', 'или', 'как', 'массив', 'массиве', 'меня', 'моего', 'можно', 'на', 'обойти', 'ошибку', 'пк', 'помощью', 'попытке', 'предел', 'преобразовать', 'при', 'пытаюсь', 'спасибо', 'стоки', 'строк', 'то', 'том', 'уровне', 'физический', 'это', 'эту']
PS CountVectorizer by default returns a sparse matrix as a result - it usually takes several orders of magnitude less memory compared to regular Numpy NDArray.
In [9]: X_vect Out[9]: <3x39 sparse matrix of type '<class 'numpy.int64'>' with 40 stored elements in Compressed Sparse Row format> In [10]: type(X_vect) Out[10]: scipy.sparse.csr.csr_matrix
UPDATE: One-hot-encoding at the level of single characters:
In [22]: vect = CountVectorizer(token_pattern=r'(?u)[\w\d]{1}') In [23]: X_vect = vect.fit_transform(sents) In [24]: ''.join(vect.get_feature_names()) Out[24]: '01268acdeghimnoprtuyабвгдежзийклмнопрстуфчшщыьэюя' In [25]: X_vect Out[25]: <3x49 sparse matrix of type '<class 'numpy.int64'>' with 77 stored elements in Compressed Sparse Row format>
range(train_size)withxrange(train_size)- Enikeyschik