单词到数字更快的查找

数据挖掘 Python 语言模型 情绪分析 编码
2021-10-11 12:13:53

我正在训练一个 LSTM 对从这里下载的评论数据集进行情绪分析。音乐评论数据集包含大约 150K 数据点(标记为 pos 或 neg 的不同长度的评论)。创建字典后,我在 Python 中运行一个脚本,用 keras/theano 稍后嵌入的数字替换字符串(单词)。

问题是这么大的数据集需要大量的查找时间。如果有人对更快查找或类似的工具有建议,我将不胜感激。目前我只是遍历语料库中的每个单词并将其替换为字典中的相应数字(本质上是 1-hot 编码)

编辑:

我大致做了以下事情:每个 Python 列表都是一个句子(在此处标记化之前):

['高贵','interesting_superlatives',...,'the_idea']

我想将其转换为整数列表,例如:

[143599, 12387,...,7582]

我将它(可能是错误的)称为 one-hot 编码,因为对于每个单词,字典中只有一个数字。

3个回答

我想用另一个例子来扩展@Emre 的答案——我们将替换“1984”(c)George Orwell(120K 单词)中的所有标记化单词:

In [163]: %paste
import requests
import nltk
import pandas as pd

# source: https://github.com/dwyl/english-words
fn = r'D:\temp\.data\words.txt'
url = 'http://gutenberg.net.au/ebooks01/0100021.txt'

r = requests.get(url)

# read words into Pandas DataFrame
df = pd.read_csv(fn, header=None, names=['word'])
# shuffle DF, so we will have random indexes
df = df.sample(frac=1)
# convert Pandas DF into dictionary: {'word1': unique_number1, 'word2': unique_number2, ...}
lkp = df.reset_index().set_index('word')['index'].to_dict()

# tokenize "1984" (c) George Orwell
words = nltk.tokenize.word_tokenize(r.text)

print('Word Dictionary size: {}'.format(len(lkp)))
print('We have tokenized {} words...'.format(len(words)))
## -- End pasted text --
Word Dictionary size: 354983
We have tokenized 120251 words...

In [164]: %timeit [lkp.get(w, 0) for w in words]
10 loops, best of 3: 66.3 ms per loop

结论:从包含 354.983 个条目的字典中构建一个包含 120K 单词的列表需要 66 毫秒。

你做错了什么。我可以在纳秒内查询一个 10 万字的字典

word_list = open('/usr/share/dict/words').read().split()
len(word_list)

> 99171

word_dict = {word: hash(word) for word in word_list}
%timeit word_dict['blazing']

> 10000000 loops, best of 3: 33.8 ns per loop

您可以使用 Wikipedia 定义中的trie

是一种搜索树——一种有序的树数据结构,用于存储动态集合或关联数组,其中键通常是字符串。

pygtrie提供了一个带有 dict 接口的尝试的实现。这是一个例子

import pygtrie as trie

words = ['cat', 'caterpillar', 'dog', 'mouse']

structure = trie.Trie()

for i, word in enumerate(words):
   structure[word] = i

print structure['caterpillar']