使用预训练词向量和随机初始化词向量的差异还是挺大的,现在说一说我使用预训练词向量的流程。

  一、构建本语料的词汇表,作为我的基础词汇

  二、遍历该词汇表,从预训练词向量中提取出该词对应的词向量

  三、初始化embeddings遍历,将数据赋值给tensor

样例代码:

  

 #-*- coding: UTF-8 -*-
import numpy as np
import tensorflow as tf
'''本程序只是对word2vec进行了简单的预处理,应用到复杂模型中还需要根据实际情况做必要的改动''' class Wordlist(object):
def __init__(self, filename, maxn = 100000):
lines = map(lambda x: x.split(), open(filename).readlines()[:maxn])
self.size = len(lines) self.voc = [(item[0][0], item[1]) for item in zip(lines, xrange(self.size))]
self.voc = dict(self.voc) def getID(self, word):
try:
return self.voc[word]
except:
return 0 def get_W(word_vecs, k=300):
"""
Get word matrix. W[i] is the vector for word indexed by i
"""
vocab_size = len(word_vecs)
word_idx_map = dict()
W = np.zeros(shape=(vocab_size+1, k), dtype='float32')
W[0] = np.zeros(k, dtype='float32')
i = 1
for word in word_vecs:
W[i] = word_vecs[word]
word_idx_map[word] = i
i += 1
return W, word_idx_map def load_bin_vec(fname, vocab):
"""
Loads 300x1 word vecs from Google (Mikolov) word2vec
"""
i=0
word_vecs = {}
pury_word_vec = []
with open(fname, "rb") as f:
header = f.readline()
print 'header',header
vocab_size, layer1_size = map(int, header.split())
print 'vocabsize:',vocab_size,'layer1_size:',layer1_size
binary_len = np.dtype('float32').itemsize * layer1_size
for line in xrange(vocab_size):
word = []
while True:
ch = f.read(1)
#print ch
if ch == ' ':
word = ''.join(word)
#print 'single word:',word
break
if ch != '\n':
word.append(ch)
#print word
#print word
if word in vocab:
word_vecs[word] = np.fromstring(f.read(binary_len), dtype='float32')
pury_word_vec.append(word_vecs[word])
if i==0:
print 'word',word
i=1
else:
f.read(binary_len)
#np.savetxt('googleembedding.txt',pury_word_vec)
return word_vecs,pury_word_vec def add_unknown_words(word_vecs, vocab, min_df=1, k=300):
"""
For words that occur in at least min_df documents, create a separate word vector.
0.25 is chosen so the unknown vectors have (approximately) same variance as pre-trained ones
"""
for word in vocab:
if word not in word_vecs and vocab[word] >= min_df:
word_vecs[word] = np.random.uniform(-0.25,0.25,k) if __name__=="__main__":
w2v_file = "GoogleNews-vectors-negative300.bin"#Google news word2vec bin文件
print "loading data...",
vocab = Wordlist('vocab.txt')#自己的数据集要用到的词表
w2v,pury_word2vec = load_bin_vec(w2v_file, vocab.voc)
add_unknown_words(w2v, vocab.voc)
W, word_idx_map = get_W(w2v) '''embedding lookup简单应用'''
Wa = tf.Variable(W)
embedding_input = tf.nn.embedding_lookup(Wa, [0,1,2])#正常使用时要替换成相应的doc with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
input = sess.run(Wa)
#print np.shape(Wa)

tensorflow如何正确加载预训练词向量的更多相关文章

  1. PyTorch在NLP任务中使用预训练词向量

    在使用pytorch或tensorflow等神经网络框架进行nlp任务的处理时,可以通过对应的Embedding层做词向量的处理,更多的时候,使用预训练好的词向量会带来更优的性能.下面分别介绍使用ge ...

  2. pytorch中如何使用预训练词向量

    不涉及具体代码,只是记录一下自己的疑惑. 我们知道对于在pytorch中,我们通过构建一个词向量矩阵对象.这个时候对象矩阵是随机初始化的,然后我们的输入是单词的数值表达,也就是一些索引.那么我们会根据 ...

  3. 文本分类实战(一)—— word2vec预训练词向量

    1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...

  4. word2vec预训练词向量

    NLP中的Word2Vec讲解 word2vec是Google开源的一款用于词向量计算 的工具,可以很好的度量词与词之间的相似性: word2vec建模是指用CBoW模型或Skip-gram模型来计算 ...

  5. 文本分布式表示(二):用tensorflow和word2vec训练词向量

    看了几天word2vec的理论,终于是懂了一些.理论部分我推荐以下几篇教程,有博客也有视频: 1.<word2vec中的数学原理>:http://www.cnblogs.com/pegho ...

  6. [Pytorch]Pytorch加载预训练模型(转)

    转自:https://blog.csdn.net/Vivianyzw/article/details/81061765 东风的地方 1. 直接加载预训练模型 在训练的时候可能需要中断一下,然后继续训练 ...

  7. 使用Huggingface在矩池云快速加载预训练模型和数据集

    作为NLP领域的著名框架,Huggingface(HF)为社区提供了众多好用的预训练模型和数据集.本文介绍了如何在矩池云使用Huggingface快速加载预训练模型和数据集. 1.环境 HF支持Pyt ...

  8. Microsoft Visual Studio 2008 未能正确加载包“Visual Web Developer HTML Source Editor Package” | “Visual Studio HTM Editor Package”

    在安装Microsoft Visual Studio 2008 后,如果Visual Studio 2008的语言版本与系统不一致时,比如:在Windows 7 English System 安装Vi ...

  9. Visual Studio 2008 Package Load Failure:未能正确加载包“Microsoft.VisualStudio.Xaml”

    在安装好Visual Studio 2008后,启动Visual Studio 2008 发现如下提示: 包加载失败 未能正确加载包“Microsoft.VisualStudio.Xaml”( GUI ...

随机推荐

  1. SQL 中的多条件查询

    在应用程序开发中,多条件查询是个经常遇到的情况,最简单最麻烦的方法是把所有的可能情况都考虑到,但是无疑是繁琐的,而且很容易漏掉可能的情形,下面是SQL语句实现多条件查询的情况 select * fro ...

  2. 11G新特性 -- ASM的兼容性

    Oracle 11g中,asm同时支持10g和11g数据库.但是asm的版本不能低于数据库的版本. 与兼容性现相关的两个参数: ·compatible.rdbms 支持的最低版本的oracle数据库版 ...

  3. 【转】AlphaGo Zero 和强人工智能

    AlphaGo Zero 和强人工智能 前段时间比较热门的是 AlphaGo(阿法狗)的升级版:AlphaGo Zero(阿法狗零).跟阿法狗不同,阿法狗零不依赖于任何人类对弈记录,完全从围棋的规则出 ...

  4. docker的swarm介绍

    转载自:https://blog.csdn.net/karamos/article/details/80132082 另外一篇:https://www.jianshu.com/p/9eb9995884 ...

  5. eslint 入门学习

    想学eslint已经很久了,可是每次进到官网看一下就觉得头大,无法下手,但是最近到了年底,进行年度总结,作为一个有志向的程序媛,还是要追求编码规范的,因此今天再次拿起来了eslint,记录一下我的学习 ...

  6. 30. Substring with Concatenation of All Words

    题目: You are given a string, s, and a list of words, words, that are all of the same length. Find all ...

  7. [Python] 01 - Number

    故事背景 一.大纲 如下,chapter4 是个概览,之后才是具体讲解. 二. 编译过程 Ref: http://www.dsf.unica.it/~fiore/LearningPython.pdf

  8. 如何在Django1.8 结合Python3.4版本中使用MySql

    Python2.7时代连接MySql的MySQLdb还不支持Python3.4. pip install pymysql 最关键的一点,在站点的__init__.py文件中,我们添加如下代码: 1 i ...

  9. Texture::setUnRefImageDataAfterApply

    当该值设置为true时,OSG在应用过该纹理对象后(apply),自动释放其对Image对象的引用,以减少内存占用

  10. for循环将字典添加到列表中出现覆盖前面数据的问题

    出现问题: rets = [{'id':1},{"id":2},{"id":3}] context = {} context['count'] = len(re ...