深度学习中文NLP任务实战(二):使用训练好的词向量

开篇

先放上我参考的一篇博客
tensorflow 使用预训练词向量

embedding层

我们使用预训练的词向量,最主要的目的就是为了生成embedding层的w

W = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_dim]),
                trainable=False, name="W")
embedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_dim])
embedding_init = W.assign(embedding_placeholder)
sess.run(embedding_init, feed_dict={embedding_placeholder: embedding})

这里的前提就是你代码里面使用的词典和你预训练好的词向量的词典是一致的,这样你的词的id才能在词向量的表里面顺利找到相应的词向量,这样,你的embedding层才能顺利构建。

而事实上,你使用的别人训练好的词向量的词典可能非常大,而你自己的词典确是比较小的,一致的情况只会在你自己训练的词向量中会出现,这时候你需要自己手动去生成w。

    for w in vocab_processor.vocabulary_._mapping:
    #tensorflow生成的词表
        arr = []
        if w in inpH.pre_emb:
            arr = inpH.pre_emb[w]
            #pre_emd,我们预训练的词向量表
            if len(arr) > 0:
                idx = vocab_processor.vocabulary_.get(w)
                initW[idx] = np.asarray(arr).astype(np.float32)
    print("Done assigning intiW. len=" + str(len(initW)))

猜你喜欢

转载自blog.csdn.net/ding_xiaofei/article/details/80957629