Python项目输出小类概率,机器学习
- from pandas import read_csv
- import numpy as np
- from sklearn.datasets.base import Bunch
- import pickle #导入cPickle包并且取一个别名pickle #持久化类
- from sklearn.feature_extraction.text import TfidfVectorizer
- import jieba
- import xlwt
- import operator#排序用
- from sklearn import metrics
- Straindata=[]
- Strainlabel=[]
- Sart_train=[]
- Stestdata=[]
- Stestlabel=[]
- Sart_test=[]
- Slast=[]
- Snew=[]
- class obj:
- def __init__(self):
- self.key=0
- self.weight=0.0
- def importSmallContentdata(file,data,art,label,f):
- dataset=read_csv(file)
- Sdata = dataset.values[:,:]
- print(type(Sdata))
- if f==1:
- for line in Sdata:
- ls=[]
- ls.append(line[14])
- ls.append(line[15])
- ls.append(line[16])
- ls.append(line[17])
- Slast.append(ls)
- #print(len(Slast))
- #print("需要对照的小类数据准备完毕")
- '''找到smalli不为0的装入Straindata,把数据分开'''
- for smalli in range(14,18):
- #print(smalli)
- count=0
- for line in Sdata:
- count=count+1
- if line[smalli]!='' and line[smalli]!=0 :
- k=1
- ls=[]
- for i in line:
- if k==1:
- art.append(i)
- k=k+1
- continue
- if k==11:#k为14并不代表是line[14],因为line是从0开始
- break
- ls.append(float(i))
- k=k+1
- data.append(ls)
- label.append(line[smalli])
- if f==1:
- Snew.append(count)
- #print("为什么都超限",len(Snew))
- def getKvector(train_set,vec,n):
- nonzero=train_set.tdm.nonzero()
- k=0
- lis=[]
- gather=[]
- p=-1
- for i in nonzero[0]:
- p=p+1
- if k==i:
- a=obj()
- a.key=nonzero[1][p]
- a.weight=train_set.tdm[i,nonzero[1][p]]
- lis.append(a)
- else:
- lis.sort(key=lambda obj: obj.weight, reverse=True)#对链表内为类对象的排序
- gather.append(lis)
- while k < i:
- k=k+1
- lis=[]
- a=obj()
- a.key=nonzero[1][p]
- a.weight=train_set.tdm[i,nonzero[1][p]]
- lis.append(a)
- gather.append(lis)#gather存储的是每条数据的事实描述的特征向量,已经从小到大排好了,只不过每个存既有key又有weight
- #我们只要key,不再需要weight
- sj=1
- for i in gather:
- ls=[]
- for j in i:
- sj=sj+1
- ls.append(float(j.key))
- while sj<=n:
- sj=sj+1
- ls.append(-1)
- sj=1
- vec.append(ls)
- '''读取停用词'''
- def _readfile(path):
- with open(path, "rb") as fp:
- content = fp.read()
- return content
- ''' 读取bunch对象'''
- def _readbunchobj(path):
- with open(path, "rb") as file_obj:
- bunch = pickle.load(file_obj)
- return bunch
- '''写入bunch对象'''
- def _writebunchobj(path, bunchobj):
- with open(path, "wb") as file_obj:
- pickle.dump(bunchobj, file_obj)
- def buildtrainbunch(bunch_path,art_train,trainlabel):
- bunch = Bunch(label=[],contents=[])
- for item1 in trainlabel:
- bunch.label.append(item1)
- #trainContentdatasave=[] #存储所有训练和测试数据的分词
- for item2 in art_train:
- item2=str(item2)
- item2 = item2.replace("\r\n", "")
- item2 = item2.replace(" ", "")
- content_seg=jieba.cut(item2)
- save2=''
- for item3 in content_seg:
- if len(item3) > 1 and item3!='\r\n':
- #trainContentdatasave.append(item3)
- save2=save2+","+item3
- bunch.contents.append(save2)
- with open(bunch_path, "wb") as file_obj:
- pickle.dump(bunch, file_obj)
- print("构建训练数据文本对象结束!!!")
- def buildtestbunch(bunch_path,art_test,testlabel):
- bunch = Bunch(label=[],contents=[])
- for item1 in testlabel:
- bunch.label.append(item1)
- #testContentdatasave=[] #存储所有训练和测试数据的分词
- for item2 in art_test:
- item2=str(item2)
- item2 = item2.replace("\r\n", "")
- item2 = item2.replace(" ", "")
- content_seg=jieba.cut(item2)
- save2=''
- for item3 in content_seg:
- if len(item3) > 1 and item3!='\r\n':
- #testContentdatasave.append(item3)
- save2=save2+","+item3
- bunch.contents.append(save2)
- with open(bunch_path, "wb") as file_obj:
- pickle.dump(bunch, file_obj)
- print("构建测试数据文本对象结束!!!")
- def vector_space(stopword_path,bunch_path,space_path):
- stpwrdlst = _readfile(stopword_path).splitlines()#读取停用词
- bunch = _readbunchobj(bunch_path)#导入分词后的词向量bunch对象
- #构建tf-idf词向量空间对象
- tfidfspace = Bunch(label=bunch.label,tdm=[], vocabulary={})
- #权重矩阵tdm,其中,权重矩阵是一个二维矩阵,tdm[i][j]表示,第j个词(即词典中的序号)在第i个类别中的IF-IDF值
- #使用TfidVectorizer初始化向量空间模型
- vectorizer = TfidfVectorizer(stop_words=stpwrdlst, sublinear_tf=True, max_df=0.5, min_df=0.0001,use_idf=True,max_features=15000)
- #print(vectorizer)
- #文本转为词频矩阵,单独保存字典文件
- tfidfspace.tdm = vectorizer.fit_transform(bunch.contents)
- tfidfspace.vocabulary = vectorizer.vocabulary_
- #创建词袋的持久化
- _writebunchobj(space_path, tfidfspace)
- print("if-idf词向量空间实例创建成功!!!")
- def testvector_space(stopword_path,bunch_path,space_path,train_tfidf_path):
- stpwrdlst = _readfile(stopword_path).splitlines()#把停用词变成列表
- bunch = _readbunchobj(bunch_path)
- tfidfspace = Bunch(label=bunch.label,tdm=[], vocabulary={})
- #导入训练集的TF-IDF词向量空间 ★★
- trainbunch = _readbunchobj(train_tfidf_path)
- tfidfspace.vocabulary = trainbunch.vocabulary
- vectorizer = TfidfVectorizer(stop_words=stpwrdlst, sublinear_tf=True, max_df=0.7, vocabulary=trainbunch.vocabulary, min_df=0.001)
- tfidfspace.tdm = vectorizer.fit_transform(bunch.contents)
- _writebunchobj(space_path, tfidfspace)
- print("if-idf词向量空间实例创建成功!!!")
- if __name__=="__main__":
- '''============================先导入数据=================================='''
- file_train = 'F:/goverment/exceloperating/all_tocai_train.csv'
- file_test = 'F:/goverment/exceloperating/all_tocai_test.csv'
- importSmallContentdata(file_train,Straindata,Sart_train,Strainlabel,0)
- importSmallContentdata(file_test,Stestdata,Sart_test,Stestlabel,1)
- #print("Stestlabel" ,len(Stestlabel))
- #print("小类导入数据完毕")
- #print("大类标签导入完毕")#共1329*4
- '''==========================================================tf-idf对Bar进行文本特征提取============================================================================'''
- #导入分词后的词向量bunch对象
- train_bunch_path ="F:/goverment/exceloperating/trainbunch.bat"#Bunch保存路径
- train_space_path = "F:/goverment/exceloperating/traintfdifspace.dat"
- test_bunch_path ="F:/goverment/exceloperating/testbunch.bat"
- test_space_path = "F:/goverment/exceloperating/testtfdifspace.dat"
- stopword_path ="F:/goverment/exceloperating/hlt_stop_words.txt"
- '''============================================================tf-idf对Sart进行文本特征提取=============================================================================='''
- buildtrainbunch(train_bunch_path,Sart_train,Strainlabel)
- buildtestbunch(test_bunch_path,Sart_test,Stestlabel)
- vector_space(stopword_path,train_bunch_path,train_space_path)
- testvector_space(stopword_path,test_bunch_path,test_space_path,train_space_path)
- train_set=_readbunchobj(train_space_path)
- test_set=_readbunchobj(test_space_path)
- '''训练数据'''
- S_vec_train=[]
- getKvector(train_set,S_vec_train,76)
- '''测试数据'''
- S_vec_test=[]
- getKvector(test_set,S_vec_test,76)
- '''=================将得到的61个特征和之前的其它特征合并Btraindata=================='''
- '''小类训练数据'''
- S_vec_train=np.array(S_vec_train)
- #print(type(S_vec_train))
- #print(S_vec_train.shape)
- Straindata=np.array(Straindata)
- #print(type(Straindata))
- #print(Straindata.shape)
- Straindata=np.hstack((S_vec_train,Straindata))
- #print(Straindata)
- '''小类测试数据'''
- S_vec_test=np.array(S_vec_test)
- Stestdata=np.array(Stestdata)
- Stestdata=np.hstack((S_vec_test,Stestdata))
- print("分类算小类精度")
- Strainlabel=np.array(Strainlabel)
- Strainlabel=np.array(Strainlabel)
- from xgboost import XGBClassifier
- clf= XGBClassifier(learning_rate =0.1,
- n_estimators=1150,
- max_depth=2,
- min_child_weight=1,
- gamma=0,
- subsample=0.8,
- colsample_bytree=0.8,
- objective= 'binary:logistic',
- nthread=4,#没用
- scale_pos_weight=1,#没用
- seed=27)
- clf.fit(Straindata, Strainlabel)
- predict=clf.predict(Stestdata)
- aa=metrics.accuracy_score(Stestlabel, predict)
- print(aa)#40.09
- ''''============================输出技术问题及其可能性================'''
- class attri:
- def __init__(self):
- self.key=0
- self.weight=0.0
- '''====================小类======================='''
- attribute_proba=clf.predict_proba(Stestdata)
- label=[]
- for i in attribute_proba:
- lis=[]
- k=0
- while k<4:
- k=k+1
- p=1
- mm=0
- sj=-1
- for j in i:
- sj=sj+1
- if j>mm:
- mm=j
- p=sj
- i[p]=0#难道是从1开始?
- a=attri()
- a.key=p
- a.weight=mm
- lis.append(a)
- #lis.append(p)
- label.append(lis)
- #接下来将label和snew结合,再排序去重就可以和slast比较了
- #print("为什么都超限",len(Snew))
- print("label",len(label))
- count=0
- for lis in label:
- lis.append(Snew[count])
- count=count+1
- print("结合完成,准备去重!")#此时label和Snew的长度都为1439
- bol=np.zeros(len(label)+1)
- Snew=[]
- for lis in label:
- if bol[lis[4]]==0:
- Snew.append(lis)
- bol[lis[4]]=1
- #print(len(Snew))#去重后为1162
- for i in range(len(Slast)+1):
- if i==0:
- continue
- if bol[i]==0:
- ls=[]
- a=attri()
- a.weight=1
- a.key=0
- ls.append(a)
- ls.append(a)
- ls.append(a)
- ls.append(a)
- ls.append(i)
- Snew.append(ls)
- #print("Snew",len(Snew)) #为1329
- print("去重完毕,准备排序!")
- Snew.sort(key=operator.itemgetter(4))
- print("排序完毕,准备比较!")
- myexcel = xlwt.Workbook()
- sheet = myexcel.add_sheet('sheet')
- si=-2
- sj=-1
- #cys=1
- #print(Snew)
- for i in Snew:
- si=si+2
- #print(si)
- #print("对于记录 %d:" % cys)
- #cys=cys+1
- for j in range(len(i)):
- if(j==len(i)-1):
- continue
- sj=sj+1
- #sheet.write(si,sj,str(j))
- sheet.write(si,sj,str(i[j].key))
- sheet.write(si+1,sj,str(i[j].weight*100))
- #print ("发生技术问题 %d 的可能性是:%.2f %%" % (j.key,j.weight*100))
- sj=-1
- myexcel.save("Snew.xls")
Python项目输出小类概率,机器学习的更多相关文章
- python项目实战-小游戏1
项目规则: 1.玩家和敌人分别从现有的角色中选择3个角色 2.随机生成目前的血量,和攻击量 3.游戏规则:当玩家向敌人发起攻击,敌人当前的血量=之前的血量-玩家的血量,同理 4.3局两胜 5.自定义玩 ...
- Python mysql 操作小类,供大家用用
import binascii import os import linecache import time #add pyDes path #sys.path.append("/data1 ...
- 以正确的方式开源 Python 项目
以正确的方式开源 Python 项目 大多数Python开发者至少都写过一个像工具.脚本.库或框架等对其他人也有用的工具.我写这篇文章的目的是让现有Python代码的开源过程尽可能清 晰和无痛.我不是 ...
- 以正确的方式开源 Python 项目(转)
大多数Python开发者至少都写过一个像工具.脚本.库或框架等对其他人也有用的工具.我写这篇文章的目的是让现有Python代码的开源过程尽可能清晰和无痛.我不是简单的指——“创建一个GitHub库,提 ...
- Python 爬取的类封装【将来可能会改造,持续更新...】(2020年寒假小目标09)
日期:2020.02.09 博客期:148 星期日 按照要求,我来制作 Python 对外爬取类的固定部分的封装,以后在用 Python 做爬取的时候,可以直接使用此类并定义一个新函数来处理CSS选择 ...
- 2013流行Python项目汇总
2013流行Python项目汇总 转自:http://www.kankanews.com/ICkengine/archives/102963.shtml Python作为程序员的宠儿,越来越得到人们的 ...
- 流行的Python项目汇总
年有哪些流行的Python项目呢?下面,我们一起来看下. 一.测试和调试 python_koans :Python Koans 算 “Ruby Koans” 的一部分,作为交互式教程,可以学习 TDD ...
- Docker如何部署Python项目
Docker 部署Python项目 作者:白宁超 2019年5月24日09:09:00 导读: 软件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正确,软件才能运行.如 ...
- 笔记14:Docker 部署Python项目
Docker 部署Python项目 导读: 软件开发最大的麻烦事之一就是环境配置,操作系统设置,各种库和组件的安装.只有它们都正确,软件才能运行.如果从一种操作系统里面运行另一种操作系统,通常我们采取 ...
随机推荐
- HttpClient 4.5.3 get和post请求
HttpCilent 4.5.3 域名购买.com 后缀好域名 https://mi.aliyun.com/shop/38040 GET请求 CloseableHttpClient httpCilen ...
- Ubuntu16 nginx安装http_image_filter_module模块
目录 配置image_filter 配置 重启nginx 如何安装呢? 安装image_filter模块依赖的库. 查看之前的配置 添加上图片模块[由于它是系统模块,不需要额外下载,直接添加就可以了] ...
- RHEL6.5恢复root密码
1.开机上下键停留在如下界面,键盘输入小写e: 2.选择如下选项,并输入小写e: 3.输入1,回车进入单用户模式: 4.键盘输入小写b,进行启动: 5.进入到单用户模式: 6.修改root用户密码,并 ...
- mysql explain extended 查看 执行计划
本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 1. explain 可以查看 ...
- PHP自定义XML类实现数组到XML文件的转换
这两天在公司写和各应用商店应用内搜索的接口,大致就像百度应用内搜索这样的东西,具体可以点下面的链接查看. 百度应用内搜索 有的应用商店需要JSON格式的数据,所以我只需要用下面的语句就可以返回对方服务 ...
- ActiveRecord 惰性加载,和使用gem faker
rails console后: 2.1.4 :001 > User # => User (call 'User.connection' to establish a connection) ...
- POJ 1426 Find the Multiple 思路,线性同余,搜索 难度:2
http://poj.org/problem?id=1426 测试了一番,从1-200的所有值都有long long下的解,所以可以直接用long long 存储 从1出发,每次向10*s和10*s+ ...
- Mac iStat Menu 注册码
9185-4915-3252-3716-0000 1574-5977-7956-8062-0000 6015-5448-3282-4975-0000 9665-5955-6856-2071-0000 ...
- Centos7 防火墙常用命令 开启 关闭防火墙
如果你的系统上没有安装使用命令安装 #yum install firewalld //安装firewalld 防火墙 开启服务 # systemctl start firewalld.service ...
- AI人工智能专业词汇集
作为最早关注人工智能技术的媒体,机器之心在编译国外技术博客.论文.专家观点等内容上已经积累了超过两年多的经验.期间,从无到有,机器之心的编译团队一直在积累专业词汇.虽然有很多的文章因为专业性我们没能尽 ...