word2vec生成词向量和字向量
生成字符向量的过程中需要注意:
1)在收集数据生成corpus时候,通过Word2Vec生成字向量的时候,产生了“ ”空格字符向量,但是加载模型是不会成功的。那么你不是生成的binary文件,就可以修改此文件,更改或删除。
示例参考代码如下:
import os
import gensim
from gensim.models import word2vec
from sklearn.decomposition import PCA
import numpy as np import logging
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO) class TrainVector:
def __init__(self):
cur = '/'.join(os.path.abspath(__file__).split('/')[:-1])
# 训练语料所在目录
self.token_filepath = os.path.join(cur, 'train_data/token_train.txt')
self.pinyin_filepath = os.path.join(cur, 'train_data/pinyin_train.txt')
self.postag_filepath = os.path.join(cur, 'train_data/postag_train.txt')
self.dep_filepath = os.path.join(cur, 'train_data/dep_train.txt')
self.word_filepath = os.path.join(cur, 'train_data/word_train.txt') # 向量文件所在目录
self.token_embedding = os.path.join(cur, 'model/token_vec_300.bin')
self.postag_embedding = os.path.join(cur, 'model/postag_vec_30.bin')
self.dep_embedding = os.path.join(cur, 'model/dep_vec_10.bin')
self.pinyin_embedding = os.path.join(cur, 'model/pinyin_vec_300.bin')
self.word_embedding = os.path.join(cur, 'model/word_vec_300.bin') #向量大小设置
self.token_size = 300
self.pinyin_size = 300
self.dep_size = 10
self.postag_size = 30
self.word_size = 300 '''基于gensimx训练字符向量,拼音向量,词性向量'''
def train_vector(self, train_path, embedding_path, embedding_size):
sentences = word2vec.Text8Corpus(train_path) # 加载分词语料
model = word2vec.Word2Vec(sentences, size=embedding_size, window=5, min_count=5) # 训练skip-gram模型,默认window=5
model.wv.save_word2vec_format(embedding_path, binary=False) '''基于特征共现+pca降维的依存向训练'''
def train_dep_vector(self, train_path, embedding_path, embedding_size):
f_embedding = open(embedding_path, 'w+')
deps = ['SBV', 'COO', 'ATT', 'VOB', 'FOB', 'IOB', 'POB', 'RAD', 'ADV', 'DBL', 'CMP', 'WP', 'HED', 'LAD']
weight_matrix = []
for dep in deps:
print(dep)
weights = []
for line in open(train_path):
line = line.strip().split('\t')
dep_dict = {i.split('@')[0]:int(i.split('@')[1]) for i in line[1].split(';')}
sum_tf = sum(dep_dict.values())
dep_dict = {key:round(value/sum_tf,10) for key, value in dep_dict.items()}
weight = dep_dict.get(dep, 0.0)
weights.append(str(weight))
weight_matrix.append(weights)
weight_matrix = np.array(weight_matrix)
pca = PCA(n_components = embedding_size)
low_embedding = pca.fit_transform(weight_matrix)
for index, vecs in enumerate(low_embedding):
dep = deps[index]
vec = ' '.join([str(vec) for vec in vecs])
f_embedding.write(dep + ' ' + vec + '\n')
f_embedding.close() '''训练主函数'''
def train_main(self):
#训练依存向量
self.train_dep_vector(self.dep_filepath, self.dep_embedding, self.dep_size)
#训练汉字字向量
self.train_vector(self.token_filepath, self.token_embedding, self.token_size)
#训练汉语词性向量
self.train_vector(self.postag_filepath, self.postag_embedding, self.postag_size)
#训练汉语词向量
self.train_vector(self.word_filepath, self.word_embedding, self.word_size)
# 训练汉语拼音向量
self.train_vector(self.pinyin_filepath, self.pinyin_embedding, self.pinyin_size)
return if __name__ == '__main__':
handler = TrainVector()
handler.train_main()
word2vec生成词向量和字向量的更多相关文章
- word2vec生成词向量原理
假设每个词对应一个词向量,假设: 1)两个词的相似度正比于对应词向量的乘积.即:$sim(v_1,v_2)=v_1\cdot v_2$.即点乘原则: 2)多个词$v_1\sim v_n$组成的一个上下 ...
- 文本分布式表示(二):用tensorflow和word2vec训练词向量
看了几天word2vec的理论,终于是懂了一些.理论部分我推荐以下几篇教程,有博客也有视频: 1.<word2vec中的数学原理>:http://www.cnblogs.com/pegho ...
- [Algorithm & NLP] 文本深度表示模型——word2vec&doc2vec词向量模型
深度学习掀开了机器学习的新篇章,目前深度学习应用于图像和语音已经产生了突破性的研究进展.深度学习一直被人们推崇为一种类似于人脑结构的人工智能算法,那为什么深度学习在语义分析领域仍然没有实质性的进展呢? ...
- 基于word2vec训练词向量(二)
转自:http://www.tensorflownews.com/2018/04/19/word2vec2/ 一.基于Hierarchical Softmax的word2vec模型的缺点 上篇说了Hi ...
- Word2Vec之Deep Learning in NLP (一)词向量和语言模型
转自licstar,真心觉得不错,可惜自己有些东西没有看懂 这篇博客是我看了半年的论文后,自己对 Deep Learning 在 NLP 领域中应用的理解和总结,在此分享.其中必然有局限性,欢迎各种交 ...
- 基于word2vec训练词向量(一)
转自:https://blog.csdn.net/fendouaini/article/details/79905328 1.回顾DNN训练词向量 上次说到了通过DNN模型训练词获得词向量,这次来讲解 ...
- Deep Learning in NLP (一)词向量和语言模型
原文转载:http://licstar.net/archives/328 Deep Learning 算法已经在图像和音频领域取得了惊人的成果,但是在 NLP 领域中尚未见到如此激动人心的结果.关于这 ...
- 【NLP】自然语言处理:词向量和语言模型
声明: 这是转载自LICSTAR博士的牛文,原文载于此:http://licstar.net/archives/328 这篇博客是我看了半年的论文后,自己对 Deep Learning 在 NLP 领 ...
- Python统计excel表格中文本的词频,生成词云图片
import xlrd import jieba import pymysql import matplotlib.pylab as plt from wordcloud import WordClo ...
随机推荐
- 使用 TRESTClient 与 TRESTRequest 作为 HTTP Client(转)
使用 TRESTClient 与 TRESTRequest 作为 HTTP Client 转自:http://www.cnblogs.com/dennieschang/p/6966403.html ...
- 详解 JVM Garbage First(G1) 垃圾收集器(转载)
前言 Garbage First(G1)是垃圾收集领域的最新成果,同时也是HotSpot在JVM上力推的垃圾收集器,并赋予取代CMS的使命.如果使用Java 8/9,那么有很大可能希望对G1收集器进行 ...
- Xcode真机调试失败:The identity used to sign the executable is no longer valid
在Xcode中突然好久没有使用真机调试了.今天使用真机的时候.出现例如以下的警告.并真机执行失败: The identity used to sign the executable is no lon ...
- PHP-问题处理Fatal error: Uncaught Error: Call to undefined function mb_strlen()
1.问题 今天重新安装了ubuntu,PHP,MySQL,Apache,到测试CMS项目时发生一个错误: Fatal error: Uncaught Error: Call to undefined ...
- understanding-raid-setup-in-linux/
https://www.tecmint.com/understanding-raid-setup-in-linux/ Part 1:Introduction to RAID, Concepts of ...
- HTML5+CSS3 效果网站集合
1.jquery插件库 HTML5制作3D樱花漫天飞舞 http://www.jq22.com/jquery-info3547 2.17素材网 http://www.17sucai.com/pi ...
- Troubleshooting Scheduler Autotask Issues (Doc ID 1561498.1)
In this Document Purpose Troubleshooting Steps References APPLIES TO: Oracle Database - Enterp ...
- windows下telnet命令不好用解决方案;
1.按网上说的windows下打开功能,telnet客户端打钩是必须的: 2.如果还不行,找到telnet.exe:然后把此路径添加到环境变量path下即可: ps:telnet的退出:quit命令:
- [转]application.properties详解 --springBoot配置文件
本文转载:http://blog.csdn.net/lpfsuperman/article/details/78287265###; # spring boot application.propert ...
- MapReduce 计数器简介
转自:http://my.oschina.net/leejun2005/blog/276891?utm_source=tuicool&utm_medium=referral 1.计数器 简介 ...