大作业


import jieba import os import numpy as np import sys #代入内置模块 from datetime import datetime #导入所有的命名空间 import gc path=r'C:\Users\defaultuser0\Backup\我的文档\258' with open(r'C:\Users\defaultuser0\Backup\我的文档\stopword\stopsCN.txt',encoding='UTF-8') as f: stopwords=f.read().split('\n') def processing(tokens): # 去掉非字母汉字的字符 tokens = "".join([char for char in tokens if char.isalpha()]) # 结巴分词 tokens = [token for token in jieba.cut(tokens,cut_all=True) if len(token) >=2] # 去掉停用词 tokens = " ".join([token for token in tokens if token not in stopwords]) return tokens tokenList = [] targetList = [] # 用os.walk获取需要的变量,并拼接文件路径再打开每一个文件 for root,dirs,files in os.walk(path): for f in files: filePath = os.path.join(root,f) with open(filePath, encoding='utf-8') as f: content = f.read() # 获取新闻类别标签,并处理该新闻 target = filePath.split('\\')[-2] targetList.append(target) tokenList.append(processing(content)) # 划分训练集测试集并建立特征向量,为建立模型做准备 # 划分训练集测试集 from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB,MultinomialNB from sklearn.model_selection import cross_val_score from sklearn.metrics import classification_report x_train,x_test,y_train,y_test = train_test_split(tokenList,targetList,test_size=0.2,stratify=targetList) # 转化为特征向量,这里选择TfidfVectorizer的方式建立特征向量。不同新闻的词语使用会有较大不同。 vectorizer = TfidfVectorizer() X_train = vectorizer.fit_transform(x_train) X_test = vectorizer.transform(x_test) # 建立模型,这里用多项式朴素贝叶斯,因为样本特征的a分布大部分是多元离散值 mnb = MultinomialNB() module = mnb.fit(X_train, y_train) #进行预测 y_predict = module.predict(X_test) # 输出模型精确度 scores=cross_val_score(mnb,X_test,y_test,cv=5) print("Accuracy:%.3f"%scores.mean()) # 输出模型评估报告 print("classification_report:\n",classification_report(y_predict,y_test)) # 将预测结果和实际结果进行对比 import collections import matplotlib.pyplot as plt from pylab import mpl mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 # 统计测试集和预测集的各类新闻个数 testCount = collections.Counter(y_test) predCount = collections.Counter(y_predict) print('实际:',testCount,'\n', '预测', predCount) # 建立标签列表,实际结果列表,预测结果列表, nameList = list(testCount.keys()) testList = list(testCount.values()) predictList = list(predCount.values()) x = list(range(len(nameList))) print("新闻类别:",nameList,'\n',"实际:",testList,'\n',"预测:",predictList) # 画图 plt.figure(figsize=(7,5)) total_width, n = 0.6, 2 width = total_width / n plt.bar(x, testList, width=width,label='实际',fc = 'g') for i in range(len(x)): x[i] = x[i] + width plt.bar(x, predictList,width=width,label='预测',tick_label = nameList) plt.grid() plt.title('实际和预测对比图',fontsize=17) plt.xlabel('新闻类别',fontsize=17) plt.ylabel('频数',fontsize=17) plt.legend(fontsize =17) plt.tick_params(labelsize=15) plt.show()

  结果:

 

posted @ 2018-12-23 18:16  澄枫一叶  阅读(93)  评论(0编辑  收藏  举报