tensorflow - 在 keras 中使用带有 LSTM nn 的 Gensim Fasttext 模型

标签 tensorflow keras nlp gensim word-embedding

我已经在非常短的句子(最多 10 个单词)的语料库上使用 Gensim 训练了 fasttext 模型。我知道我的测试集包括不在我的训练语料库中的词,即我的语料库中的一些词像“Oxytocin”、“Lexitocin”、“Ematrophin”、“Betaxitocin”
给定测试集中的一个新词,fasttext 非常清楚地知道通过使用字符级别 n-gram 生成一个与训练集中其他相似词具有高余弦相似度的向量
如何将 fasttext 模型合并到 LSTM keras 网络中,而不会丢失 fasttext 模型到词汇表中的向量列表?因为那样的话,即使 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)

关于tensorflow - 在 keras 中使用带有 LSTM nn 的 Gensim Fasttext 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62743531/

相关文章:

python - 在 TensorFlow 2.0 中,如何将 TFRecord 数据提供给 keras 模型?

python - 无法理解 tensorflow 代码示例中的 lstm 使用

python - Keras 模型评估()与预测类()给出不同的精度结果

machine-learning - 使用词嵌入时处理缺失词的最佳方法是什么?

machine-learning - Keras 保存的模型预测不同 session 上的不同值

python: 基于字典的分词

tensorflow - 批处理队列(tf.train.batch)不保留顺序吗?

python - 导入tensorflow时出错(刚刚安装)python 3.7

python - Keras:使用灰度蒙版和 ImageDataGenerator 类进行图像分割

python - 如何在 TensorFlow 2 中获取 Keras 张量的值?