use*_*622 3 python keras tensorflow word-embedding
从页面我得到以下代码:
from numpy import array
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.embeddings import Embedding
# define documents
docs = ['Well done!',
'Good work',
'Great effort',
'nice work',
'Excellent!',
'Weak',
'Poor effort!',
'not good',
'poor work',
'Could have done better.']
# define class labels
labels = array([1,1,1,1,1,0,0,0,0,0])
# integer encode the documents
vocab_size = 50
encoded_docs = [one_hot(d, vocab_size) for d in docs]
print(encoded_docs)
# pad documents to a max length of 4 words
max_length = 4
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
print(padded_docs)
# define the model
model = Sequential()
model.add(Embedding(vocab_size, 8, input_length=max_length))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())
# fit the model
model.fit(padded_docs, labels, epochs=50, verbose=0)
# evaluate the model
loss, accuracy = model.evaluate(padded_docs, labels, verbose=0)
print('Accuracy: %f' % (accuracy*100))
Run Code Online (Sandbox Code Playgroud)
encoded_docs,发现单词done和work双方都one_hot的2编码,为什么呢?是因为unicity of word to index mapping non-guaranteed.按照这个页面?embeddings了命令embeddings = model.layers[0].get_weights()[0].在这种情况下,为什么我们得到embedding大小为50的物体?即使两个单词具有相同的one_hot数,它们是否有不同的嵌入?donevswork我还在页面上找到了下面的代码,可以帮助找到每个单词的嵌入.但我不知道如何创建word_to_index
word_to_index是从单词到其索引的映射(即字典),例如love:69 words_embeddings = {w:embeddings [idx]表示w,idx表示word_to_index.items()}
请确保我的理解para #是正确的.
第一层有400个参数,因为总字数为50,嵌入有8个尺寸,所以50*8 = 400.
最后一层有33个参数,因为每个句子最多有4个单词.因此嵌入尺寸为4*8,偏置为1.共33个
_________________________________________________________________
Layer (type) Output Shape Param#
=================================================================
embedding_3 (Embedding) (None, 4, 8) 400
_________________________________________________________________
flatten_3 (Flatten) (None, 32) 0
_________________________________________________________________
dense_3 (Dense) (None, 1) 33
=================================================================
Run Code Online (Sandbox Code Playgroud)
model.add(Embedding(vocab_size, 8, input_length=max_length))
而不进行一次热编码encoded_docs = [one_hot(d, vocab_size) for d in docs]
1 - 是的,单词unicity不能保证,请参阅文档:
one_hot:这是hashing_trick函数的包装器......hashing_trick:"由于散列函数可能发生冲突,可能会将两个或多个单词分配给同一索引.冲突的概率与散列空间的维数和不同对象的数量有关."最好使用一个Tokenizer.(见问题4)
记住在创建索引时应该同时涉及所有单词,这一点非常重要.您不能使用函数创建一个包含2个单词的字典,然后再使用2个单词再创建一个字典....这将创建非常错误的字典.
2 - 嵌入具有大小50 x 8,因为它是在嵌入层中定义的:
Embedding(vocab_size, 8, input_length=max_length)
Run Code Online (Sandbox Code Playgroud)
vocab_size = 50 - 这意味着字典中有50个单词 embedding_size= 8 - 这是嵌入的真实大小:每个单词由8个数字的向量表示.3 - 你不知道.他们使用相同的嵌入.
系统将使用相同的嵌入(index = 2).这对你的模型来说根本不健康.您应该使用另一种方法来创建问题1中的索引.
4 - 您可以手动创建单词词典,也可以使用Tokenizer该类.
手动:
确保删除标点符号,将所有单词设为小写.
只需为您拥有的每个单词创建一个字典:
dictionary = dict()
current_key = 1
for doc in docs:
for word in doc.split(' '):
#make sure you remove punctuation (this might be boring)
word = word.lower()
if not (word in dictionary):
dictionary[word] = current_key
current_key += 1
Run Code Online (Sandbox Code Playgroud)
标记生成器:
from keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer()
#this creates the dictionary
#IMPORTANT: MUST HAVE ALL DATA - including Test data
#IMPORTANT2: This method should be called only once!!!
tokenizer.fit_on_texts(docs)
#this transforms the texts in to sequences of indices
encoded_docs2 = tokenizer.texts_to_sequences(docs)
Run Code Online (Sandbox Code Playgroud)
看输出encoded_docs2:
[[6, 2], [3, 1], [7, 4], [8, 1], [9], [10], [5, 4], [11, 3], [5, 1], [12, 13, 2, 14]]
Run Code Online (Sandbox Code Playgroud)
查看最大指数:
padded_docs2 = pad_sequences(encoded_docs2, maxlen=max_length, padding='post')
max_index = array(padded_docs2).reshape((-1,)).max()
Run Code Online (Sandbox Code Playgroud)
所以,你vocab_size应该是15(否则你会有很多无用的 - 无害的 - 嵌入行).请注意,这0不是用作索引.它会出现在填充中!
不要再"适应"标记器了!这里只使用
texts_to_sequences()或与"拟合"无关的其他方法.
提示:end_of_sentence有时在文本中包含单词可能很有用.
提示2:保存Tokenizer以供日后使用是个好主意(因为它具有特定的数据,用于创建数据fit_on_texts).
#save:
text_to_save = tokenizer.to_json()
#load:
from keras.preprocessing.text import tokenizer_from_json
tokenizer = tokenizer_from_json(loaded_text)
Run Code Online (Sandbox Code Playgroud)
5 - 嵌入的参数是正确的.
稠密:
Params for Dense总是基于前一层(Flatten在本例中).
公式是: previous_output * units + units
这导致了 32 (from the Flatten) * 1 (Dense units) + 1 (Dense bias=units) = 33
拼合:
它得到所有以前的尺寸乘以= 8 * 4.
在Embedding输出lenght = 4和embedding_size = 8.
6 - Embedding图层不依赖于您的数据以及您如何预处理它.
该Embedding层的大小只有50 x 8,因为你这么说.(见问题2)
当然,有更好的方法来预处理数据 - 见问题4.
这将导致您选择更好的vocab_size(字典大小).
获取嵌入矩阵:
embeddings = model.layers[0].get_weights()[0]
Run Code Online (Sandbox Code Playgroud)
选择任何单词索引:
embeding_for_word_7 = embeddings[7]
Run Code Online (Sandbox Code Playgroud)
就这样.
如果您正在使用标记化器,请使用以下命令获取单词索引:
index = tokenizer.texts_to_sequences([['word']])[0][0]
Run Code Online (Sandbox Code Playgroud)