首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在keras中结合使用Gensim Fasttext模型和LSTM nn

在keras中结合使用Gensim Fasttext模型和LSTM nn
EN

Stack Overflow用户
提问于 2020-07-06 00:39:08
回答 1查看 2.3K关注 0票数 4

我已经用Gensim在非常短的句子(最多10个单词)语料库上训练了快速文本模型。我知道我的测试集中包含不在我的训练语料库中的单词,即我的语料库中的一些单词,如“催产素”、“来曲霉素”、"Ematrophin“、”Betaxitocin“。

给定测试集中的一个新词,fasttext非常清楚地知道通过使用字符级n-gram来生成与训练集中的其他相似词具有很高余弦相似度的向量

如何将快速文本模型合并到LSTM keras网络中,而不会将快速文本模型丢失为词汇中的一个向量列表?因为那样我就不会处理任何OOV了,即使fasttext做得很好。

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-06 06:54:17

下面是将fasttext模型合并到LSTM Keras网络中的过程

代码语言:javascript
运行
复制
# 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)

如何处理看不见的文本

代码语言:javascript
运行
复制
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)
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62743531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档