我能像这里一样使用fasttext word vector吗:
https://github.com/facebookresearch/fastText/blob/master/pretrained-vectors.md
in a tensorflow script as an embedding vector instead of word2vec or glove without using the library fasttext
最佳答案
当您使用预先训练的单词向量时,可以使用gensim libarary。
。
https://blog.manash.me/how-to-use-pre-trained-word-vectors-from-facebooks-fasttext-a71e6d55f27
In [1]: from gensim.models import KeyedVectors
In [2]: jp_model = KeyedVectors.load_word2vec_format('wiki.ja.vec')
In [3]: jp_model.most_similar('car')
Out[3]:
[('cab', 0.9970724582672119),
('tle', 0.9969051480293274),
('oyc', 0.99671471118927),
('oyt', 0.996662974357605),
('車', 0.99665766954422),
('s', 0.9966464638710022),
('新車', 0.9966358542442322),
('hice', 0.9966053366661072),
('otg', 0.9965877532958984),
('車両', 0.9965814352035522)]
编辑
我用cnn-text-classification-tf创建了一个新分支。这是链接。
https://github.com/satojkovic/cnn-text-classification-tf/tree/use_fasttext
在这个分支中,有三个修改可以使用fasttext。
从fasttext中提取vocab和word_vec。(util_fasttext.py)
model = KeyedVectors.load_word2vec_format('wiki.en.vec')
vocab = model.vocab
embeddings = np.array([model.word_vec(k) for k in vocab.keys()])
with open('fasttext_vocab_en.dat', 'wb') as fw:
pickle.dump(vocab, fw, protocol=pickle.HIGHEST_PROTOCOL)
np.save('fasttext_embedding_en.npy', embeddings)
嵌入层
W由零初始化,然后设置一个嵌入的占位符来接收单词。(text_cnn.py)
W_ = tf.Variable(
tf.constant(0.0, shape=[vocab_size, embedding_size]),
trainable=False,
name='W')
self.embedding_placeholder = tf.placeholder(
tf.float32, [vocab_size, embedding_size],
name='pre_trained')
W = tf.assign(W_, self.embedding_placeholder)
使用词汇和单词
。
with open('fasttext_vocab_en.dat', 'rb') as fr:
vocab = pickle.load(fr)
embedding = np.load('fasttext_embedding_en.npy')
pretrain = vocab_processor.fit(vocab.keys())
x = np.array(list(vocab_processor.transform(x_text)))
feed_dict = {
cnn.input_x: x_batch,
cnn.input_y: y_batch,
cnn.dropout_keep_prob: FLAGS.dropout_keep_prob,
cnn.embedding_placeholder: embedding
}
请试一试。
关于python - 使用快速文本预训练词向量嵌入 tensorflow 脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44829438/