从 Python 中的文本创建序列向量
Creating sequence vector from text in Python
我现在正在尝试为基于 LSTM 的神经网络准备输入数据。
我有大量的文本文档,我想要的是为每个文档制作序列向量,这样我就可以将它们作为训练数据提供给 LSTM RNN。
我糟糕的做法:
import re
import numpy as np
#raw data
train_docs = ['this is text number one', 'another text that i have']
#put all docs together
train_data = ''
for val in train_docs:
train_data += ' ' + val
tokens = np.unique(re.findall('[a-zа-я0-9]+', train_data.lower()))
voc = {v: k for k, v in dict(enumerate(tokens)).items()}
然后 brutforce 用 "voc" 字典替换每个文档。
是否有任何库可以帮助完成这项任务?
您可以使用 NLTK 来标记训练文档。 NLTK 提供了一个标准的单词标记器或允许您定义自己的标记器(例如 RegexpTokenizer)。查看 here 以了解有关可用的不同标记器功能的更多详细信息。
Here 也可能有助于预处理文本。
下面是一个使用 NLTK 预训练单词标记器的快速演示:
from nltk import word_tokenize
train_docs = ['this is text number one', 'another text that i have']
train_docs = ' '.join(map(str, train_docs))
tokens = word_tokenize(train_docs)
voc = {v: k for k, v in dict(enumerate(tokens)).items()}
使用 Keras 文本预处理解决 类:
http://keras.io/preprocessing/text/
这样做:
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
train_docs = ['this is text number one', 'another text that i have']
tknzr = Tokenizer(lower=True, split=" ")
tknzr.fit_on_texts(train_docs)
#vocabulary:
print(tknzr.word_index)
Out[1]:
{'this': 2, 'is': 3, 'one': 4, 'another': 9, 'i': 5, 'that': 6, 'text': 1, 'number': 8, 'have': 7}
#making sequences:
X_train = tknzr.texts_to_sequences(train_docs)
print(X_train)
Out[2]:
[[2, 3, 1, 8, 4], [9, 1, 6, 5, 7]]
我现在正在尝试为基于 LSTM 的神经网络准备输入数据。 我有大量的文本文档,我想要的是为每个文档制作序列向量,这样我就可以将它们作为训练数据提供给 LSTM RNN。
我糟糕的做法:
import re
import numpy as np
#raw data
train_docs = ['this is text number one', 'another text that i have']
#put all docs together
train_data = ''
for val in train_docs:
train_data += ' ' + val
tokens = np.unique(re.findall('[a-zа-я0-9]+', train_data.lower()))
voc = {v: k for k, v in dict(enumerate(tokens)).items()}
然后 brutforce 用 "voc" 字典替换每个文档。
是否有任何库可以帮助完成这项任务?
您可以使用 NLTK 来标记训练文档。 NLTK 提供了一个标准的单词标记器或允许您定义自己的标记器(例如 RegexpTokenizer)。查看 here 以了解有关可用的不同标记器功能的更多详细信息。
Here 也可能有助于预处理文本。
下面是一个使用 NLTK 预训练单词标记器的快速演示:
from nltk import word_tokenize
train_docs = ['this is text number one', 'another text that i have']
train_docs = ' '.join(map(str, train_docs))
tokens = word_tokenize(train_docs)
voc = {v: k for k, v in dict(enumerate(tokens)).items()}
使用 Keras 文本预处理解决 类: http://keras.io/preprocessing/text/
这样做:
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
train_docs = ['this is text number one', 'another text that i have']
tknzr = Tokenizer(lower=True, split=" ")
tknzr.fit_on_texts(train_docs)
#vocabulary:
print(tknzr.word_index)
Out[1]:
{'this': 2, 'is': 3, 'one': 4, 'another': 9, 'i': 5, 'that': 6, 'text': 1, 'number': 8, 'have': 7}
#making sequences:
X_train = tknzr.texts_to_sequences(train_docs)
print(X_train)
Out[2]:
[[2, 3, 1, 8, 4], [9, 1, 6, 5, 7]]