过程:获取数据,训练词向量,模型超参数设置,模型效果检验,模型保存与加载
1.获取数据(英语维基百科的部分网页信息, 它的大小在300M左右
)
[root@bhs fastte]# wget -c http://mattmahoney.net/dc/enwik9.zip -P data[root@bhs data]# unzip enwik9.zip [root@bhs data]# ll
total 1291608-rw-r--r--1 root root 1000000000 Jun 12011 enwik9
-rw-r--r--1 root root 322592222 Sep 22011 enwik9.zip-rw-r--r--1 root root 1995 May 2400:17 wikifil.pl
查看下载的数据
[root@bhs data]# more enwik9<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sch
emaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang
="en"><siteinfo><sitename>Wikipedia</sitename><base>http://en.wikipedia.org/wiki/Main_Page</base><generator>MediaWiki 1.6alpha</generator><case>first-letter</case><namespaces><namespace key="-2">Media</namespace><namespace key="-1">Special</namespace><namespace key="0"/><namespace key="1">Talk</namespace><namespace key="2">User</namespace><namespace key="3">User talk</namespace><namespace key="4">Wikipedia</namespace><namespace key="5">Wikipedia talk</namespace>
数据处理
使用wikifil.pl文件处理脚本来清除XML/HTML格式的内容
[root@bhs data]# perl wikifil.pl enwik9 > fil
输出结果为由空格分割的单词
[root@bhs data]# more fil
anarchism originated as a term of abuse first used against early working classradicals including the diggers of the eng
lish revolution and the sans culottes of the french revolution whilst the term is still used in a pejorative way to descr
2.训练词向量
# 在训练词向量过程中, 我们可以设定很多常用超参数来调节我们的模型效果,# 无监督训练模式: 'skipgram' 或者 'cbow', 默认为'skipgram', 在实践中,skipgram模式在利用子词方面比cbow更好.# 词嵌入维度dim: 默认为100, 但随着语料库的增大, 词嵌入的维度往往也要更大.# 数据循环次数epoch: 默认为5, 但当你的数据集足够大, 可能不需要那么多次.# 学习率lr: 默认为0.05, 根据经验, 建议选择[0.01,1]范围内.# 使用的线程数thread: 默认为12个线程, 一般建议和你的cpu核数相同
model=fasttext.train_unsupervised('./fil','cbow',dim=300,epoch=1,lr=0.1,thread=2)
Read 124M words
Number of words:218316
Number of labels:0
Progress:100.0% words/sec/thread:26829 lr:0.000000 avg.loss:1.507921 ETA: 0h 0m 0s
3.模型效果检验
# 检查单词向量质量的一种简单方法就是查看其邻近单词, 通过我们主观来判断这些邻近单词是否与目标单词相关来粗略评定模型效果好坏.
查找"小狗"的邻近单词, 我们可以发现与小狗有关的词汇.>>> model.get_nearest_neighbors('dog')[(0.8416129350662231,'catdog'),(0.7638700604438782,'sleddog'),(0.7467442154884338,'dogcow'),<