#!/usr/bin/env Python
# coding:utf-8
#improt依赖包
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
import chardet
from gensim import utils
from gensim.models.doc2vec import LabeledSentence
from gensim.models import Doc2Vec
import numpy
from random import shuffle
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
import sklearn.metrics as metrics
# Doc2vec需要以LabeledLineSentece对象作为输入,所以需要构建一个类将文本转化为LabeledLineStentece对象
class LabeledLineSentence(object): def __init__(self, sources):
self.sources = sources
flipped = {}
# make sure that keys are unique
for key, value in sources.items():
if value not in flipped:
flipped[value] = [key]
else:
raise Exception('Non-unique prefix encountered') def __iter__(self):
for source, prefix in self.sources.items():
with utils.smart_open(source) as fin:
for item_no, line in enumerate(fin):
yield LabeledSentence(utils.to_unicode(line).split(), [prefix + '_%s' % item_no]) def to_array(self):
self.sentences = []
for source, prefix in self.sources.items():
with utils.smart_open(source) as fin:
for item_no, line in enumerate(fin):
print chardet.detect(line)
line=line.decode("GB2312",'ignore').encode("utf-8")
print chardet.detect(line)
self.sentences.append(LabeledSentence(utils.to_unicode(line).split(), [prefix + '_%s' % item_no]))
# self.sentences.append(LabeledSentence(utils.to_utf8(line).split(), [prefix + '_%s' % item_no]))
return self.sentences def sentences_perm(self):
shuffle(self.sentences)
return self.sentences #将文本数据以以下方式导入到Doc2vec中
# sources = {u'/Volumes/Macintosh HD/Users/RayChou/Downloads/情感分析训练语料/neg_train.txt':'TRAIN_NEG',
# u'/Volumes/Macintosh HD/Users/RayChou/Downloads/情感分析训练语料/pos_train.txt':'TRAIN_POS'
# ,u'/Volumes/Macintosh HD/Users/RayChou/Downloads/情感分析训练语料/uns_train.txt':'TRAIN_UNS',
# u'/Volumes/Macintosh HD/Users/RayChou/Downloads/情感分析训练语料/uns_test.txt':'TEST_UNS'}
sources = {\
'./yuliao/fYuliao0.txt':'TRAIN_0',
'./yuliao/fYuliao1.txt':'TRAIN_1',
'./yuliao/fYuliao2.txt':'TRAIN_2',
'./yuliao/fYuliao3.txt':'TRAIN_3',
'./yuliao/fYuliao4.txt':'TRAIN_4',
'./yuliao/fYuliao5.txt':'TRAIN_5',\
}
sentences = LabeledLineSentence(sources) #构建Doc2vec模型 model = Doc2Vec(min_count=1, window=15, size=100, sample=1e-4, negative=5, workers=8)
model.build_vocab(sentences.to_array()) #训练Doc2vec模型(本例迭代次数为10,如果时间允许,可以迭代更多的次数)
for epoch in range(2):
model.train(sentences.sentences_perm())
model.save("model.txt")
# model=Doc2Vec.load("model.txt") #将训练好的句子向量装进array里面,后文作为分类器的输入
train_arrays = numpy.zeros((5000, 100))
train_labels = numpy.zeros(5000)
test_arrays = []
true_labels=[]
train_data=[]
train_lb=[]
for i in range(5000):
if(i<=645):
prefix_train_0 = 'TRAIN_0_' + str(i)
train_arrays[i] = model.docvecs[prefix_train_0]
train_labels[i] = 0
elif(i>645 and i<=4249):
j=i-646
prefix_train_1 = 'TRAIN_1_' + str(j)
train_arrays[i]=model.docvecs[prefix_train_1]
train_labels[i]=1
elif(i>4249 and i<=4800):
j=i-4250
prefix_train_2 = 'TRAIN_2_' + str(j)
train_arrays[i]=model.docvecs[prefix_train_2]
train_labels[i]=2
elif(i>4800 and i<=4965):
j=i-4801
prefix_train_3 = 'TRAIN_3_' + str(j)
train_arrays[i]=model.docvecs[prefix_train_3]
train_labels[i]=3
elif(i>4965 and i<=4994):
j=i-4966
prefix_train_4 = 'TRAIN_4_' + str(j)
train_arrays[i]=model.docvecs[prefix_train_4]
train_labels[i]=4
else:
j=i-4995
prefix_train_5 = 'TRAIN_5_' + str(j)
train_arrays[i]=model.docvecs[prefix_train_5]
train_labels[i]=5
#载入测试集数据
a=open("./yuliao/fYuliao0_test.txt")
b=open("./yuliao/fYuliao1_test.txt")
c=open("./yuliao/fYuliao2_test.txt")
d=open("./yuliao/fYuliao3_test.txt")
e=open("./yuliao/fYuliao4_test.txt")
f=open("./yuliao/fYuliao5_test.txt") test_content1=a.readlines()
test_content2=b.readlines()
test_content3=c.readlines()
test_content4=d.readlines()
test_content5=e.readlines()
test_content6=f.readlines() g=open("./yuliao/fYuliao0_test.txt")
test_content7=g.readline()
inferred_docvec=model.infer_vector(test_content7)
print model.docvecs.most_similar([inferred_docvec], topn=3) for i in test_content1:
test_arrays.append(model.infer_vector(i))
true_labels.append(0)
for i in test_content2:
test_arrays.append(model.infer_vector(i))
true_labels.append(1)
for i in test_content3:
test_arrays.append(model.infer_vector(i))
true_labels.append(2)
for i in test_content4:
test_arrays.append(model.infer_vector(i))
true_labels.append(3)
for i in test_content5:
test_arrays.append(model.infer_vector(i))
true_labels.append(4)
for i in test_content6:
test_arrays.append(model.infer_vector(i))
true_labels.append(5) #构建逻辑回归分类器
classifier = LogisticRegression(class_weight={0:0.38,1:0.62})
classifier.fit(train_arrays, train_labels)
# 构建随机森林分类器
'''
from sklearn.ensemble import RandomForestClassifier
RF = RandomForestClassifier(n_estimators=1200,max_depth=14,class_weight={0:0.3,1:0.7})
RF.fit(train_arrays, train_labels)
'''
#构建GBDT分类器
'''
from sklearn.ensemble import GradientBoostingClassifier
GBDT = GradientBoostingClassifier(n_estimators=1000,max_depth=14)
GBDT.fit(train_arrays, train_labels)
'''
#对Test数据进行预测
test_labels_LR=[]
# test_labels_RF=[]
# test_labels_GBDT=[]
for i in range(len(test_arrays)):
test_labels_LR.append(classifier.predict(test_arrays[i]))
'''
test_labels_RF.append(RF.predict(test_arrays[i]))
test_labels_GBDT.append(GBDT.predict(test_arrays[i]))
'''
#打印各个模型的准确率和召回率
print("LR:")
test_labels_LR1 = []
count = 0
for i in range(len(test_labels_LR)):
if (test_labels_LR[i][0] == true_labels[i]):
count +=1
print count
'''
print("RF:")
print(metrics.accuracy_score(test_labels_RF,true_labels))
print(confusion_matrix(test_labels_RF,true_labels))
print("GBDT:")
print(metrics.accuracy_score(test_labels_GBDT,true_labels))
print(confusion_matrix(test_labels_GBDT,true_labels))
'''

doc2vec使用笔记的更多相关文章

  1. Use of Deep Learning in Modern Recommendation System: A Summary of Recent Works(笔记)

    注意:论文中,很多的地方出现baseline,可以理解为参照物的意思,但是在论文中,我们还是直接将它称之为基线,也 就是对照物,参照物. 这片论文中,作者没有去做实际的实验,但是却做了一件很有意义的事 ...

  2. 人工智能头条(公开课笔记)+AI科技大本营——一拨微信公众号文章

    不错的 Tutorial: 从零到一学习计算机视觉:朋友圈爆款背后的计算机视觉技术与应用 | 公开课笔记 分享人 | 叶聪(腾讯云 AI 和大数据中心高级研发工程师) 整    理 | Leo 出   ...

  3. git-简单流程(学习笔记)

    这是阅读廖雪峰的官方网站的笔记,用于自己以后回看 1.进入项目文件夹 初始化一个Git仓库,使用git init命令. 添加文件到Git仓库,分两步: 第一步,使用命令git add <file ...

  4. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

  5. SQL Server技术内幕笔记合集

    SQL Server技术内幕笔记合集 发这一篇文章主要是方便大家找到我的笔记入口,方便大家o(∩_∩)o Microsoft SQL Server 6.5 技术内幕 笔记http://www.cnbl ...

  6. PHP-自定义模板-学习笔记

    1.  开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2.  整体架构图 ...

  7. PHP-会员登录与注册例子解析-学习笔记

    1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...

  8. NET Core-学习笔记(三)

    这里将要和大家分享的是学习总结第三篇:首先感慨一下这周跟随netcore官网学习是遇到的一些问题: a.官网的英文版教程使用的部分nuget包和我当时安装的最新包版本不一致,所以没法按照教材上给出的列 ...

  9. springMVC学习笔记--知识点总结1

    以下是学习springmvc框架时的笔记整理: 结果跳转方式 1.设置ModelAndView,根据view的名称,和视图渲染器跳转到指定的页面. 比如jsp的视图渲染器是如下配置的: <!-- ...

随机推荐

  1. win7 下安装oracle 10 g

    首先下对版本,Oracle 10g支持Win7版: http://download.oracle.com/otn/nt/oracle10g/10203/10203_vista_w2k8_x86_pro ...

  2. zabbix的日常监控-分布式监控(十)

    参考博文:http://blog.51cto.com/jinlong/2051966 zabbix proxy 可以代替 zabbix server 检索客户端的数据,然后把数据汇报给 zabbix ...

  3. "字符串"经过strip 之后还是字符串, 而"字符串"经过split 分开后,就变成了一个列表["x","xx","xxx"]

    "字符串"经过strip 之后还是字符串, 而"字符串"经过split 分开后,就变成了一个列表["x","xx",&q ...

  4. MySQL知识总结(四)二进制日志

    1 定义 bin-log日志记录了所有的DDL和DML的语句,但不包括查询的语句,语句以事件的方式保存,描述了数据的更改过程,此日志对发生灾难时数据恢复起到了极为重要的作用. 2 开启 mysql默认 ...

  5. 1927. [SDOI2010]星际竞速【费用流】

    Description 10年一度的银河系赛车大赛又要开始了.作为全银河最盛大的活动之一,夺得这个项目的冠军无疑是很多人的 梦想,来自杰森座α星的悠悠也是其中之一.赛车大赛的赛场由N颗行星和M条双向星 ...

  6. 【洛谷】【堆】P1168 中位数

    [题目描述:] 给出一个长度为N的非负整数序列A[i],对于所有1 ≤ k ≤ (N + 1) / 2,输出A[1], A[3], …, A[2k - 1]的中位数.即前1,3,5,……个数的中位数. ...

  7. Hive学习之路 (六)Hive SQL之数据类型和存储格式

    一.数据类型 1.基本数据类型 Hive 支持关系型数据中大多数基本数据类型 类型 描述 示例 boolean true/false TRUE tinyint 1字节的有符号整数 -128~127 1 ...

  8. Jenkins启动和停止服务

    1.怎么启动Jenkins? step1:进入到Jenkins的war包所在的目录. 如果是win7及以上版本,直接打开Jenkins的war包所在的目录,在地址栏敲cmd,回车. 上述结果和进入cm ...

  9. 真机测试出现INSTALL_FAILED_USER_RESTRICTED安装错误

    之前用小米测试的时候遇到一个问题,两个一样型号的手机一个能直接用Android Studio安装公司的项目一个却不可以,总是报INSTALL_FAILED_USER_RESTRICTED错误,具体见下 ...

  10. [转]打造自己的LINQ Provider(上):Expression Tree揭秘

    概述 在.NET Framework 3.5中提供了LINQ 支持后,LINQ就以其强大而优雅的编程方式赢得了开发人员的喜爱,而各种LINQ Provider更是满天飞,如LINQ to NHiber ...