1. from pandas import read_csv
  2. import numpy as np
  3. from sklearn.datasets.base import Bunch
  4. import pickle #导入cPickle包并且取一个别名pickle #持久化类
  5. from sklearn.feature_extraction.text import TfidfVectorizer
  6. import jieba
  7. import xlwt
  8. import operator#排序用
  9. from sklearn import metrics
  10.  
  11. Straindata=[]
  12. Strainlabel=[]
  13. Sart_train=[]
  14.  
  15. Stestdata=[]
  16. Stestlabel=[]
  17. Sart_test=[]
  18.  
  19. Slast=[]
  20. Snew=[]
  21.  
  22. class obj:
  23. def __init__(self):
  24. self.key=0
  25. self.weight=0.0
  26.  
  27. def importSmallContentdata(file,data,art,label,f):
  28. dataset=read_csv(file)
  29. Sdata = dataset.values[:,:]
  30. print(type(Sdata))
  31.  
  32. if f==1:
  33. for line in Sdata:
  34. ls=[]
  35. ls.append(line[14])
  36. ls.append(line[15])
  37. ls.append(line[16])
  38. ls.append(line[17])
  39. Slast.append(ls)
  40. #print(len(Slast))
  41. #print("需要对照的小类数据准备完毕")
  42.  
  43. '''找到smalli不为0的装入Straindata,把数据分开'''
  44. for smalli in range(14,18):
  45. #print(smalli)
  46. count=0
  47. for line in Sdata:
  48. count=count+1
  49. if line[smalli]!='' and line[smalli]!=0 :
  50. k=1
  51. ls=[]
  52. for i in line:
  53. if k==1:
  54. art.append(i)
  55. k=k+1
  56. continue
  57. if k==11:#k14并不代表是line[14],因为line是从0开始
  58. break
  59. ls.append(float(i))
  60. k=k+1
  61. data.append(ls)
  62. label.append(line[smalli])
  63. if f==1:
  64. Snew.append(count)
  65.  
  66. #print("为什么都超限",len(Snew))
  67.  
  68. def getKvector(train_set,vec,n):
  69. nonzero=train_set.tdm.nonzero()
  70. k=0
  71. lis=[]
  72. gather=[]
  73. p=-1
  74. for i in nonzero[0]:
  75. p=p+1
  76. if k==i:
  77. a=obj()
  78. a.key=nonzero[1][p]
  79. a.weight=train_set.tdm[i,nonzero[1][p]]
  80. lis.append(a)
  81. else:
  82. lis.sort(key=lambda obj: obj.weight, reverse=True)#对链表内为类对象的排序
  83. gather.append(lis)
  84. while k < i:
  85. k=k+1
  86. lis=[]
  87. a=obj()
  88. a.key=nonzero[1][p]
  89. a.weight=train_set.tdm[i,nonzero[1][p]]
  90. lis.append(a)
  91. gather.append(lis)#gather存储的是每条数据的事实描述的特征向量,已经从小到大排好了,只不过每个存既有key又有weight
  92.  
  93. #我们只要key,不再需要weight
  94.  
  95. sj=1
  96. for i in gather:
  97. ls=[]
  98. for j in i:
  99. sj=sj+1
  100. ls.append(float(j.key))
  101. while sj<=n:
  102. sj=sj+1
  103. ls.append(-1)
  104. sj=1
  105. vec.append(ls)
  106.  
  107. '''读取停用词'''
  108. def _readfile(path):
  109. with open(path, "rb") as fp:
  110. content = fp.read()
  111. return content
  112.  
  113. ''' 读取bunch对象'''
  114. def _readbunchobj(path):
  115. with open(path, "rb") as file_obj:
  116. bunch = pickle.load(file_obj)
  117. return bunch
  118.  
  119. '''写入bunch对象'''
  120. def _writebunchobj(path, bunchobj):
  121. with open(path, "wb") as file_obj:
  122. pickle.dump(bunchobj, file_obj)
  123.  
  124. def buildtrainbunch(bunch_path,art_train,trainlabel):
  125. bunch = Bunch(label=[],contents=[])
  126. for item1 in trainlabel:
  127. bunch.label.append(item1)
  128.  
  129. #trainContentdatasave=[] #存储所有训练和测试数据的分词
  130. for item2 in art_train:
  131. item2=str(item2)
  132. item2 = item2.replace("\r\n", "")
  133. item2 = item2.replace(" ", "")
  134. content_seg=jieba.cut(item2)
  135. save2=''
  136. for item3 in content_seg:
  137. if len(item3) > 1 and item3!='\r\n':
  138. #trainContentdatasave.append(item3)
  139. save2=save2+","+item3
  140. bunch.contents.append(save2)
  141. with open(bunch_path, "wb") as file_obj:
  142. pickle.dump(bunch, file_obj)
  143. print("构建训练数据文本对象结束!!!")
  144.  
  145. def buildtestbunch(bunch_path,art_test,testlabel):
  146. bunch = Bunch(label=[],contents=[])
  147. for item1 in testlabel:
  148. bunch.label.append(item1)
  149.  
  150. #testContentdatasave=[] #存储所有训练和测试数据的分词
  151. for item2 in art_test:
  152. item2=str(item2)
  153. item2 = item2.replace("\r\n", "")
  154. item2 = item2.replace(" ", "")
  155. content_seg=jieba.cut(item2)
  156. save2=''
  157. for item3 in content_seg:
  158. if len(item3) > 1 and item3!='\r\n':
  159. #testContentdatasave.append(item3)
  160. save2=save2+","+item3
  161. bunch.contents.append(save2)
  162. with open(bunch_path, "wb") as file_obj:
  163. pickle.dump(bunch, file_obj)
  164. print("构建测试数据文本对象结束!!!")
  165. def vector_space(stopword_path,bunch_path,space_path):
  166.  
  167. stpwrdlst = _readfile(stopword_path).splitlines()#读取停用词
  168. bunch = _readbunchobj(bunch_path)#导入分词后的词向量bunch对象
  169. #构建tf-idf词向量空间对象
  170. tfidfspace = Bunch(label=bunch.label,tdm=[], vocabulary={})
  171.  
  172. #权重矩阵tdm,其中,权重矩阵是一个二维矩阵,tdm[i][j]表示,第j个词(即词典中的序号)在第i个类别中的IF-IDF值
  173.  
  174. #使用TfidVectorizer初始化向量空间模型
  175. vectorizer = TfidfVectorizer(stop_words=stpwrdlst, sublinear_tf=True, max_df=0.5, min_df=0.0001,use_idf=True,max_features=15000)
  176. #print(vectorizer)
  177. #文本转为词频矩阵,单独保存字典文件
  178. tfidfspace.tdm = vectorizer.fit_transform(bunch.contents)
  179. tfidfspace.vocabulary = vectorizer.vocabulary_
  180. #创建词袋的持久化
  181. _writebunchobj(space_path, tfidfspace)
  182. print("if-idf词向量空间实例创建成功!!!")
  183.  
  184. def testvector_space(stopword_path,bunch_path,space_path,train_tfidf_path):
  185.  
  186. stpwrdlst = _readfile(stopword_path).splitlines()#把停用词变成列表
  187. bunch = _readbunchobj(bunch_path)
  188. tfidfspace = Bunch(label=bunch.label,tdm=[], vocabulary={})
  189. #导入训练集的TF-IDF词向量空间 ★★
  190. trainbunch = _readbunchobj(train_tfidf_path)
  191. tfidfspace.vocabulary = trainbunch.vocabulary
  192.  
  193. vectorizer = TfidfVectorizer(stop_words=stpwrdlst, sublinear_tf=True, max_df=0.7, vocabulary=trainbunch.vocabulary, min_df=0.001)
  194.  
  195. tfidfspace.tdm = vectorizer.fit_transform(bunch.contents)
  196. _writebunchobj(space_path, tfidfspace)
  197. print("if-idf词向量空间实例创建成功!!!")
  198.  
  199. if __name__=="__main__":
  200.  
  201. '''============================先导入数据=================================='''
  202. file_train = 'F:/goverment/exceloperating/all_tocai_train.csv'
  203. file_test = 'F:/goverment/exceloperating/all_tocai_test.csv'
  204.  
  205. importSmallContentdata(file_train,Straindata,Sart_train,Strainlabel,0)
  206. importSmallContentdata(file_test,Stestdata,Sart_test,Stestlabel,1)
  207.  
  208. #print("Stestlabel" ,len(Stestlabel))
  209.  
  210. #print("小类导入数据完毕")
  211.  
  212. #print("大类标签导入完毕")#共1329*4
  213.  
  214. '''==========================================================tf-idf对Bar进行文本特征提取============================================================================'''
  215. #导入分词后的词向量bunch对象
  216. train_bunch_path ="F:/goverment/exceloperating/trainbunch.bat"#Bunch保存路径
  217. train_space_path = "F:/goverment/exceloperating/traintfdifspace.dat"
  218. test_bunch_path ="F:/goverment/exceloperating/testbunch.bat"
  219. test_space_path = "F:/goverment/exceloperating/testtfdifspace.dat"
  220. stopword_path ="F:/goverment/exceloperating/hlt_stop_words.txt"
  221.  
  222. '''============================================================tf-idf对Sart进行文本特征提取=============================================================================='''
  223. buildtrainbunch(train_bunch_path,Sart_train,Strainlabel)
  224. buildtestbunch(test_bunch_path,Sart_test,Stestlabel)
  225.  
  226. vector_space(stopword_path,train_bunch_path,train_space_path)
  227. testvector_space(stopword_path,test_bunch_path,test_space_path,train_space_path)
  228.  
  229. train_set=_readbunchobj(train_space_path)
  230. test_set=_readbunchobj(test_space_path)
  231.  
  232. '''训练数据'''
  233.  
  234. S_vec_train=[]
  235. getKvector(train_set,S_vec_train,76)
  236.  
  237. '''测试数据'''
  238.  
  239. S_vec_test=[]
  240. getKvector(test_set,S_vec_test,76)
  241.  
  242. '''=================将得到的61个特征和之前的其它特征合并Btraindata=================='''
  243.  
  244. '''小类训练数据'''
  245. S_vec_train=np.array(S_vec_train)
  246. #print(type(S_vec_train))
  247. #print(S_vec_train.shape)
  248. Straindata=np.array(Straindata)
  249. #print(type(Straindata))
  250. #print(Straindata.shape)
  251. Straindata=np.hstack((S_vec_train,Straindata))
  252. #print(Straindata)
  253.  
  254. '''小类测试数据'''
  255. S_vec_test=np.array(S_vec_test)
  256. Stestdata=np.array(Stestdata)
  257. Stestdata=np.hstack((S_vec_test,Stestdata))
  258.  
  259. print("分类算小类精度")
  260. Strainlabel=np.array(Strainlabel)
  261. Strainlabel=np.array(Strainlabel)
  262.  
  263. from xgboost import XGBClassifier
  264. clf= XGBClassifier(learning_rate =0.1,
  265. n_estimators=1150,
  266. max_depth=2,
  267. min_child_weight=1,
  268. gamma=0,
  269. subsample=0.8,
  270. colsample_bytree=0.8,
  271. objective= 'binary:logistic',
  272. nthread=4,#没用
  273. scale_pos_weight=1,#没用
  274. seed=27)
  275. clf.fit(Straindata, Strainlabel)
  276. predict=clf.predict(Stestdata)
  277. aa=metrics.accuracy_score(Stestlabel, predict)
  278. print(aa)#40.09
  279.  
  280. ''''============================输出技术问题及其可能性================'''
  281. class attri:
  282. def __init__(self):
  283. self.key=0
  284. self.weight=0.0
  285.  
  286. '''====================小类======================='''
  287. attribute_proba=clf.predict_proba(Stestdata)
  288.  
  289. label=[]
  290. for i in attribute_proba:
  291. lis=[]
  292. k=0
  293. while k<4:
  294. k=k+1
  295. p=1
  296. mm=0
  297. sj=-1
  298. for j in i:
  299. sj=sj+1
  300. if j>mm:
  301. mm=j
  302. p=sj
  303. i[p]=0#难道是从1开始?
  304. a=attri()
  305. a.key=p
  306. a.weight=mm
  307. lis.append(a)
  308. #lis.append(p)
  309. label.append(lis)
  310. #接下来将label和snew结合,再排序去重就可以和slast比较了
  311. #print("为什么都超限",len(Snew))
  312. print("label",len(label))
  313. count=0
  314. for lis in label:
  315. lis.append(Snew[count])
  316. count=count+1
  317. print("结合完成,准备去重!")#此时label和Snew的长度都为1439
  318.  
  319. bol=np.zeros(len(label)+1)
  320. Snew=[]
  321. for lis in label:
  322. if bol[lis[4]]==0:
  323. Snew.append(lis)
  324. bol[lis[4]]=1
  325.  
  326. #print(len(Snew))#去重后为1162
  327.  
  328. for i in range(len(Slast)+1):
  329. if i==0:
  330. continue
  331. if bol[i]==0:
  332. ls=[]
  333. a=attri()
  334. a.weight=1
  335. a.key=0
  336. ls.append(a)
  337. ls.append(a)
  338. ls.append(a)
  339. ls.append(a)
  340. ls.append(i)
  341. Snew.append(ls)
  342. #print("Snew",len(Snew)) #为1329
  343.  
  344. print("去重完毕,准备排序!")
  345.  
  346. Snew.sort(key=operator.itemgetter(4))
  347. print("排序完毕,准备比较!")
  348.  
  349. myexcel = xlwt.Workbook()
  350. sheet = myexcel.add_sheet('sheet')
  351. si=-2
  352. sj=-1
  353. #cys=1
  354. #print(Snew)
  355. for i in Snew:
  356. si=si+2
  357. #print(si)
  358. #print("对于记录 %d:" % cys)
  359. #cys=cys+1
  360. for j in range(len(i)):
  361. if(j==len(i)-1):
  362. continue
  363. sj=sj+1
  364. #sheet.write(si,sj,str(j))
  365. sheet.write(si,sj,str(i[j].key))
  366. sheet.write(si+1,sj,str(i[j].weight*100))
  367. #print ("发生技术问题 %d 的可能性是:%.2f %%" % (j.key,j.weight*100))
  368. sj=-1
  369. myexcel.save("Snew.xls")

Python项目输出小类概率,机器学习的更多相关文章

  1. python项目实战-小游戏1

    项目规则: 1.玩家和敌人分别从现有的角色中选择3个角色 2.随机生成目前的血量,和攻击量 3.游戏规则:当玩家向敌人发起攻击,敌人当前的血量=之前的血量-玩家的血量,同理 4.3局两胜 5.自定义玩 ...

  2. Python mysql 操作小类,供大家用用

    import binascii import os import linecache import time #add pyDes path #sys.path.append("/data1 ...

  3. 以正确的方式开源 Python 项目

    以正确的方式开源 Python 项目 大多数Python开发者至少都写过一个像工具.脚本.库或框架等对其他人也有用的工具.我写这篇文章的目的是让现有Python代码的开源过程尽可能清 晰和无痛.我不是 ...

  4. 以正确的方式开源 Python 项目(转)

    大多数Python开发者至少都写过一个像工具.脚本.库或框架等对其他人也有用的工具.我写这篇文章的目的是让现有Python代码的开源过程尽可能清晰和无痛.我不是简单的指——“创建一个GitHub库,提 ...

  5. Python 爬取的类封装【将来可能会改造,持续更新...】(2020年寒假小目标09)

    日期:2020.02.09 博客期:148 星期日 按照要求,我来制作 Python 对外爬取类的固定部分的封装,以后在用 Python 做爬取的时候,可以直接使用此类并定义一个新函数来处理CSS选择 ...

  6. 2013流行Python项目汇总

    2013流行Python项目汇总 转自:http://www.kankanews.com/ICkengine/archives/102963.shtml Python作为程序员的宠儿,越来越得到人们的 ...

  7. 流行的Python项目汇总

    年有哪些流行的Python项目呢?下面,我们一起来看下. 一.测试和调试 python_koans :Python Koans 算 “Ruby Koans” 的一部分,作为交互式教程,可以学习 TDD ...

  8. Docker如何部署Python项目

    Docker 部署Python项目 作者:白宁超 2019年5月24日09:09:00 导读: 软件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正确,软件才能运行.如 ...

  9. 笔记14:Docker 部署Python项目

    Docker 部署Python项目 导读: 软件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正确,软件才能运行.如果从一种操作系统里面运行另一种操作系统,通常我们采取 ...

随机推荐

  1. HttpClient 4.5.3 get和post请求

    HttpCilent 4.5.3 域名购买.com 后缀好域名 https://mi.aliyun.com/shop/38040 GET请求 CloseableHttpClient httpCilen ...

  2. Ubuntu16 nginx安装http_image_filter_module模块

    目录 配置image_filter 配置 重启nginx 如何安装呢? 安装image_filter模块依赖的库. 查看之前的配置 添加上图片模块[由于它是系统模块,不需要额外下载,直接添加就可以了] ...

  3. RHEL6.5恢复root密码

    1.开机上下键停留在如下界面,键盘输入小写e: 2.选择如下选项,并输入小写e: 3.输入1,回车进入单用户模式: 4.键盘输入小写b,进行启动: 5.进入到单用户模式: 6.修改root用户密码,并 ...

  4. mysql explain extended 查看 执行计划

    本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 1. explain 可以查看 ...

  5. PHP自定义XML类实现数组到XML文件的转换

    这两天在公司写和各应用商店应用内搜索的接口,大致就像百度应用内搜索这样的东西,具体可以点下面的链接查看. 百度应用内搜索 有的应用商店需要JSON格式的数据,所以我只需要用下面的语句就可以返回对方服务 ...

  6. ActiveRecord 惰性加载,和使用gem faker

    rails console后: 2.1.4 :001 > User # => User (call 'User.connection' to establish a connection) ...

  7. POJ 1426 Find the Multiple 思路,线性同余,搜索 难度:2

    http://poj.org/problem?id=1426 测试了一番,从1-200的所有值都有long long下的解,所以可以直接用long long 存储 从1出发,每次向10*s和10*s+ ...

  8. Mac iStat Menu 注册码

    9185-4915-3252-3716-0000 1574-5977-7956-8062-0000 6015-5448-3282-4975-0000 9665-5955-6856-2071-0000 ...

  9. Centos7 防火墙常用命令 开启 关闭防火墙

    如果你的系统上没有安装使用命令安装 #yum install firewalld  //安装firewalld 防火墙 开启服务 # systemctl start firewalld.service ...

  10. AI人工智能专业词汇集

    作为最早关注人工智能技术的媒体,机器之心在编译国外技术博客.论文.专家观点等内容上已经积累了超过两年多的经验.期间,从无到有,机器之心的编译团队一直在积累专业词汇.虽然有很多的文章因为专业性我们没能尽 ...