前提・実現したいこと
pythonで深層学習の勉強をしています。書籍『PythonとKerasによるディープラーニング』で、単語のone-hotエンコーディングを行うコードを実際に動かしていて、疑問に感じたコードがありました。しかし自分なりに修正して実行すると、エラーメッセージが出ました。
発生している問題・エラーメッセージ
for j, word in list(enumerate(sample.split()))[:max_length]:
という1行があります。
list()のある必然性が分からず、list()を削除し、以下のように書き直しました。
for j, word in enumerate(sample.split())[:max_length]:
すると、以下のようなエラーメッセージが出ます。
TypeError: 'enumerate' object is not subscriptable
### 知りたいこと
1.エラーの意味は「添え字にアクセスできないオブジェクトです」ですか?
2.list()があるとエラーが出ないようになる理屈を教えてください
3.そもそも[:max_length]は不要な気がするのですが、なぜあるのでしょうか
該当のソースコード
python3.X
1import numpy as np 2 3# This is our initial data; one entry per "sample" 4# (in this toy example, a "sample" is just a sentence, but 5# it could be an entire document). 6samples = ['The cat sat on the mat.', 'The dog ate my homework.'] 7 8# First, build an index of all tokens in the data. 9token_index = {} 10for sample in samples: 11 # We simply tokenize the samples via the `split` method. 12 # in real life, we would also strip punctuation and special characters 13 # from the samples. 14 for word in sample.split(): 15 if word not in token_index: 16 # Assign a unique index to each unique word 17 token_index[word] = len(token_index) + 1 18 # Note that we don't attribute index 0 to anything. 19 20# Next, we vectorize our samples. 21# We will only consider the first `max_length` words in each sample. 22max_length = 10 23 24# This is where we store our results: 25results = np.zeros((len(samples), max_length, max(token_index.values()) + 1)) 26for i, sample in enumerate(samples): 27 for j, word in list(enumerate(sample.split()))[:max_length]: 28 index = token_index.get(word) 29 results[i, j, index] = 1.
試したこと
ちなみに、[:max_length]を削除して以下のように書き直すと、エラーは出ません。
for j, word in enumerate(sample.split()):
enumerateはタプルを返す。これが謎を解くカギになっている気がしますが、よくわかりません。
以下のコードに直すとエラーが出ませんでした。
for j, word in enumerate(sample.split()[:max_length]):
補足情報(FW/ツールのバージョンなど)
google Colaboratoryを使っています。
https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/6.1-one-hot-encoding-of-words-or-characters.ipynb
ここにコードが載っています。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/17 22:00
2019/03/18 02:42
2019/03/20 18:10 編集
2019/03/20 18:10