tensorflow如何正确加载预训练词向量
使用预训练词向量和随机初始化词向量的差异还是挺大的,现在说一说我使用预训练词向量的流程。
一、构建本语料的词汇表,作为我的基础词汇
二、遍历该词汇表,从预训练词向量中提取出该词对应的词向量
三、初始化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如何正确加载预训练词向量的更多相关文章
- PyTorch在NLP任务中使用预训练词向量
在使用pytorch或tensorflow等神经网络框架进行nlp任务的处理时,可以通过对应的Embedding层做词向量的处理,更多的时候,使用预训练好的词向量会带来更优的性能.下面分别介绍使用ge ...
- pytorch中如何使用预训练词向量
不涉及具体代码,只是记录一下自己的疑惑. 我们知道对于在pytorch中,我们通过构建一个词向量矩阵对象.这个时候对象矩阵是随机初始化的,然后我们的输入是单词的数值表达,也就是一些索引.那么我们会根据 ...
- 文本分类实战(一)—— word2vec预训练词向量
1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...
- word2vec预训练词向量
NLP中的Word2Vec讲解 word2vec是Google开源的一款用于词向量计算 的工具,可以很好的度量词与词之间的相似性: word2vec建模是指用CBoW模型或Skip-gram模型来计算 ...
- 文本分布式表示(二):用tensorflow和word2vec训练词向量
看了几天word2vec的理论,终于是懂了一些.理论部分我推荐以下几篇教程,有博客也有视频: 1.<word2vec中的数学原理>:http://www.cnblogs.com/pegho ...
- [Pytorch]Pytorch加载预训练模型(转)
转自:https://blog.csdn.net/Vivianyzw/article/details/81061765 东风的地方 1. 直接加载预训练模型 在训练的时候可能需要中断一下,然后继续训练 ...
- 使用Huggingface在矩池云快速加载预训练模型和数据集
作为NLP领域的著名框架,Huggingface(HF)为社区提供了众多好用的预训练模型和数据集.本文介绍了如何在矩池云使用Huggingface快速加载预训练模型和数据集. 1.环境 HF支持Pyt ...
- 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 ...
- Visual Studio 2008 Package Load Failure:未能正确加载包“Microsoft.VisualStudio.Xaml”
在安装好Visual Studio 2008后,启动Visual Studio 2008 发现如下提示: 包加载失败 未能正确加载包“Microsoft.VisualStudio.Xaml”( GUI ...
随机推荐
- linux/unix命令参考
- Redis集群搭建(转自一菲聪天的“Windows下搭建Redis集群”)
配置Redis参考:http://blog.csdn.net/zsg88/article/details/73715947 使用Ruby配置集群参考:https://www.cnblogs.com/t ...
- DxO FilmPack for Mac(胶片模拟效果软件)破解版安装
1.软件简介 DxO FilmPack 是 macOS 系统上由知名的 DxO Labs 出品的一套胶片模拟效果滤镜,拥有数十种电影风格的滤镜,今天和大家分享最新的版本,支持最新的 PhotoS ...
- 编程调节Win7/Win8系统音量的一种方法
不得不说, 自Win7(好像是吧), Windows的音量调节功能比以前更人性化了.... 但编程接口却变得更加复杂了............. 还要用到IAudioEndpointVolu ...
- Atitit 常用sdk 模块 组织架构切分 规范与范例attilax总结
Atitit 常用sdk 模块 组织架构切分 规范与范例attilax总结 常用200个模块 2017/04/12 22:01 <DIR> acc 2017/04 ...
- 【Android】Eclipse性能优化,快捷方式,文档注释
快捷方式 方法注释的快捷键:ALT + SHIFT +J 格式化:Ctrl+Shift+F 把当前选中的文本全部变味大写:Ctrl+Shift+X 把当前选中的文本全部变为小写:Ctrl+Shift+ ...
- 【Java】分布式RPC通信框架Apache Thrift 使用总结
简介 Apache Thrift是Facebook开源的跨语言的RPC通信框架,目前已经捐献给Apache基金会管理,由于其跨语言特性和出色的性能,在很多互联网公司得到应用,有能力的公司甚至会基于th ...
- 教程:SpagoBI开源商业智能之XML Template 图表模板
SpagoBI offers a variety of widgets' examples realized with the Highcharts library, that can be divi ...
- (笔记)Linux内核学习(二)之进程
一 进程与线程 进程就是处于执行期的程序,包含了独立地址空间,多个执行线程等资源. 线程是进程中活动的对象,每个线程都拥有独立的程序计数器.进程栈和一组进程寄存器. 内核调度的对象是线程而不是进程.对 ...
- linux安装中文输入法
CentOS英文系统安装中文输入法,简单说说在CentOS 6.3下用yum安装中文输入法的过程. 1.需要root权限,所以要用root登录 ,或su root 2.yum install &q ...