数字の単語がより速いルックアップ
-
16-10-2019 - |
質問
からダウンロードされたレビューデータセットでセンチメント分析のためにLSTMをトレーニングしています ここ. 。 Music Review Datasetには、約150kのデータポイントが含まれています(さまざまな長さの標識POSまたはNEGのレビュー)。辞書を作成した後、Pythonでスクリプトを実行して、Keras/Theanoが後で埋め込む数字に文字列(単語)を置き換えます。
問題は、このような大きなデータセットには、検索に多くの時間が必要であることです。より速いルックアップなどのためのツールについて誰かが提案してくれたら感謝します。現在、コーパス内のすべての単語をループして、辞書の対応する数値に置き換えます(本質的に1-HOTエンコード)
編集:
私は大まかに次のことを行っています。各Pythonリストは文です(ここでの象徴化の前):
'Noble'、 'infiction_superlatives'、...、 'the_idea'
次のような整数のリストにコンバージョンになりたいです。
[143599, 12387,...,7582]
私はそれを(おそらく間違って)1ホットのエンコードと呼びました。なぜなら、各単語には辞書に正確に1つの数字があるからです。
解決
拡張したいのですが 偉大な @emreの答え 別の例では、「1984」(c)ジョージオーウェル(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ミリ秒かかりました。
他のヒント
あなたは何か間違ったことをしています。ナノ秒で100Kワードのdictを照会できます
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
aを使用できます トリー ウィキペディアの定義から:
一種の検索ツリーです。キーが通常文字列である動的セットまたは連想配列を保存するために使用される順序付けられたツリーデータ構造です。
ピグトリー 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']