Tensorflow 在keras中使用Gensim快速文本模型和LSTM神经网络

Tensorflow 在keras中使用Gensim快速文本模型和LSTM神经网络,tensorflow,keras,nlp,gensim,word-embedding,Tensorflow,Keras,Nlp,Gensim,Word Embedding,我用Gensim在非常短的句子(最多10个单词)的语料库上训练了fasttext模型。我知道我的测试集包含了我的训练语料库中没有的单词,也就是说,我的语料库中的一些单词像“催产素”、“Lexitocin”、“Ematrophin”、“Betaxitocin” 如果测试集中有一个新词,fasttext非常清楚如何通过使用字符级别n-gram生成一个与序列集中其他相似词具有高余弦相似性的向量 如何将fasttext模型整合到LSTM keras网络中,而不将fasttext模型丢失到vocab中的向

我用Gensim在非常短的句子(最多10个单词)的语料库上训练了fasttext模型。我知道我的测试集包含了我的训练语料库中没有的单词,也就是说,我的语料库中的一些单词像“催产素”、“Lexitocin”、“Ematrophin”、“Betaxitocin”

如果测试集中有一个新词,fasttext非常清楚如何通过使用字符级别n-gram生成一个与序列集中其他相似词具有高余弦相似性的向量

如何将fasttext模型整合到LSTM keras网络中,而不将fasttext模型丢失到vocab中的向量列表中?因为这样即使fasttext做得很好,我也不会处理任何OOV


有什么想法吗?

这里介绍将fasttext模型合并到LSTM Keras网络中的过程

# define dummy data and precproces them

docs = ['Well done',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent',
        'Weak',
        'Poor effort',
        'not good',
        'poor work',
        'Could have done better']

docs = [d.lower().split() for d in docs]

# train fasttext from gensim api

ft = FastText(size=10, window=2, min_count=1, seed=33)
ft.build_vocab(docs)
ft.train(docs, total_examples=ft.corpus_count, epochs=10)

# prepare text for keras neural network

max_len = 8

tokenizer = tf.keras.preprocessing.text.Tokenizer(lower=True)
tokenizer.fit_on_texts(docs)

sequence_docs = tokenizer.texts_to_sequences(docs)
sequence_docs = tf.keras.preprocessing.sequence.pad_sequences(sequence_docs, maxlen=max_len)

# extract fasttext learned embedding and put them in a numpy array

embedding_matrix_ft = np.random.random((len(tokenizer.word_index) + 1, ft.vector_size))

pas = 0
for word,i in tokenizer.word_index.items():
    
    try:
        embedding_matrix_ft[i] = ft.wv[word]
    except:
        pas+=1

# define a keras model and load the pretrained fasttext weights matrix

inp = Input(shape=(max_len,))
emb = Embedding(len(tokenizer.word_index) + 1, ft.vector_size, 
                weights=[embedding_matrix_ft], trainable=False)(inp)
x = LSTM(32)(emb)
out = Dense(1)(x)

model = Model(inp, out)

model.predict(sequence_docs)
如何处理看不见的文本

unseen_docs = ['asdcs work','good nxsqa zajxa']
unseen_docs = [d.lower().split() for d in unseen_docs]

sequence_unseen_docs = tokenizer.texts_to_sequences(unseen_docs)
sequence_unseen_docs = tf.keras.preprocessing.sequence.pad_sequences(sequence_unseen_docs, maxlen=max_len)

model.predict(sequence_unseen_docs)