使用python的gensim训练词向量word2Vec

一、环境

windows7 64位

python3.5

二、安装jieba和gensim

打开windows的powershell,定位到anaconda的scripts文件夹,输入

pip install jieba
pip install gensim

三、数据文件格式

原始数据格式

使用jieba分词将文本内容分词和去除停用词

# 分词函数  
def seg_sentence(sentence):  
    sentence_seged = jieba.cut(sentence.strip())  
    stopwords = [line.strip() for line in open('停用词表.txt', 'r', encoding='gbk') 
    outstr = ''  
    for word in sentence_seged:  
        if word not in stopwords:  
            if word != '\t':  
                outstr += word  
                outstr += " "  
    return outstr  

#对摘要进行分词
data_23_2 = pd.DataFrame(columns=['id','tag', 'words'])
for line in data_23.index:
    seg = data_23['summary'][line].replace('\\\\n', ' ').replace('\\t', ' ')
    id = data_23['id'][line]
    tag = 23
    line_seg = seg_sentence(seg)
    l = line_seg.split(' ')
    result=[]
    for i in l:
        result.append(i)
    data_23_2.loc[line] = [id, tag, set(result)]

此时得到的数据格式为

将words保存为txt

fl = open('data3.txt', 'w', encoding='utf8')
for i in data3.index:
    a = list()
    print(i)
    for j in data3['words'][i].strip('{}').split(','):
        a.append(j)
    fl.write(str(a))
    fl.write('\n')
fl.close()

打开txt编辑替换将[],',,替换成空,最终得到的data3.txt文件

四、训练模型

min_count为最少出现次数,size为隐层参数数量

sentences=word2vec.Text8Corpus(u'data3.txt')
model=word2vec.Word2Vec(sentences,min_count=1,size=50)

保存模型

model.save('F:\工作相关\jupyter\数据分析\model\word2vec_model')

 

  • 1
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值