我已经在gensim中训练了word2vec。在Keras中,我想用它来嵌入单词的句子矩阵。由于存储所有句子的矩阵非常空间和内存效率低下。因此,我想在Keras中制作嵌入层以实现此目的,以便可以在其他层(LSTM)中使用它。您能详细告诉我该怎么做吗?
PS:它与其他问题不同,因为我使用gensim而不是keras进行word2vec培训。
答案 0 :(得分:7)
使用新的Gensim版本,这非常容易:
w2v_model.wv.get_keras_embedding(train_embeddings=False)
您有Keras嵌入层
答案 1 :(得分:6)
假设您有以下数据需要编码
docs = ['Well done!',
'Good work',
'Great effort',
'nice work',
'Excellent!',
'Weak',
'Poor effort!',
'not good',
'poor work',
'Could have done better.']
然后您必须像这样使用Keras的Tokenizer
对它进行标记,并找到vocab_size
t = Tokenizer()
t.fit_on_texts(docs)
vocab_size = len(t.word_index) + 1
然后您可以将其封装为这样的序列
encoded_docs = t.texts_to_sequences(docs)
print(encoded_docs)
然后您可以填充序列,以便所有序列都具有固定长度
max_length = 4
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
然后使用word2vec模型制作嵌入矩阵
# load embedding as a dict
def load_embedding(filename):
# load embedding into memory, skip first line
file = open(filename,'r')
lines = file.readlines()[1:]
file.close()
# create a map of words to vectors
embedding = dict()
for line in lines:
parts = line.split()
# key is string word, value is numpy array for vector
embedding[parts[0]] = asarray(parts[1:], dtype='float32')
return embedding
# create a weight matrix for the Embedding layer from a loaded embedding
def get_weight_matrix(embedding, vocab):
# total vocabulary size plus 0 for unknown words
vocab_size = len(vocab) + 1
# define weight matrix dimensions with all 0
weight_matrix = zeros((vocab_size, 100))
# step vocab, store vectors using the Tokenizer's integer mapping
for word, i in vocab.items():
weight_matrix[i] = embedding.get(word)
return weight_matrix
# load embedding from file
raw_embedding = load_embedding('embedding_word2vec.txt')
# get vectors in the right order
embedding_vectors = get_weight_matrix(raw_embedding, t.word_index)
一旦有了嵌入矩阵,就可以像这样在Embedding
层中使用它
e = Embedding(vocab_size, 100, weights=[embedding_vectors], input_length=4, trainable=False)
此层可用于制作这样的模型
model = Sequential()
e = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=4, trainable=False)
model.add(e)
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)
所有代码均改编自this很棒的博客文章。跟随它以了解有关使用手套的嵌入的更多信息
有关使用word2vec的信息,请参见this帖子
答案 2 :(得分:0)
我的经过gensim训练的w2v模型的代码。
from keras.preprocessing.text import Tokenizer
import gensim
import pandas as pd
import numpy as np
from itertools import chain
w2v = gensim.models.Word2Vec.load("models/w2v.model")
vocab = w2v.wv.vocab
t = Tokenizer()
combined = pd.read_csv("./data/combined_data.csv")
all_words = list(chain(*combined["chunks"]))
vocab_size = len(all_words) + 1
t.fit_on_texts(all_words)
def get_weight_matrix():
# define weight matrix dimensions with all 0
weight_matrix = np.zeros((vocab_size, w2v.vector_size))
# step vocab, store vectors using the Tokenizer's integer mapping
for i in range(len(all_words)):
weight_matrix[i + 1] = w2v[all_words[i]]
return weight_matrix
embedding_vectors = get_weight_matrix()
emb_layer = Embedding(vocab_size, output_dim=w2v.vector_size, weights=[embedding_vectors], input_length=FIXED_LENGTH, trainable=False)