├── finance.py
├── result
├── svm_result.png
├── bayes_result.png
├── svm_confusion_matrix.png
└── bayes_confusion_matrix.png
├── 文本数据的分类与分析实验报告.docx
├── read_finance.py
├── README.md
├── WordSegmentation.py
├── TF_IDF_Model.py
└── SVM_Model.py
/finance.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cswangyuhui/TextCategorization/HEAD/finance.py
--------------------------------------------------------------------------------
/result/svm_result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cswangyuhui/TextCategorization/HEAD/result/svm_result.png
--------------------------------------------------------------------------------
/文本数据的分类与分析实验报告.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cswangyuhui/TextCategorization/HEAD/文本数据的分类与分析实验报告.docx
--------------------------------------------------------------------------------
/result/bayes_result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cswangyuhui/TextCategorization/HEAD/result/bayes_result.png
--------------------------------------------------------------------------------
/result/svm_confusion_matrix.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cswangyuhui/TextCategorization/HEAD/result/svm_confusion_matrix.png
--------------------------------------------------------------------------------
/result/bayes_confusion_matrix.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cswangyuhui/TextCategorization/HEAD/result/bayes_confusion_matrix.png
--------------------------------------------------------------------------------
/read_finance.py:
--------------------------------------------------------------------------------
1 |
2 | import pymysql
3 | import requests
4 | from lxml import etree
5 |
6 |
7 | conn = pymysql.connect(host="127.0.0.1", user="root", passwd="123456", db="datamining",
8 | charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
9 | cur = conn.cursor()
10 | sql = "select href from technology_news_new"
11 | cur.execute(sql)
12 |
13 | results = cur.fetchall()
14 | for row in results:
15 | try:
16 | response = requests.get(row['href'])
17 | response.encoding = response.apparent_encoding
18 | root = etree.HTML(response.content.decode('utf-8', 'ignore'))
19 |
20 | content = ''.join(root.xpath("//div[@class='la_con']/p/text()"))
21 | #print(content)
22 | sql = "insert into technology(content) values(%s)"
23 | cur.execute(sql, content)
24 | cur.connection.commit()
25 | except:
26 | print("Error1")
27 |
28 | conn.close()
29 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TextCategorization
2 | 北邮王晓茹老师数据挖掘与数据仓库文本数据的分类与分析实验
3 |
4 | ## 程序结构
5 |
6 | |程序|功能|
7 | |:---|:---|
8 | |finance.py|爬取新闻的链接|
9 | |read_finance.py|根据新闻链接访问新闻,并将新闻写到数据库中|
10 | |WordSegmentation.py|数据清洗、去除停用词、分词|
11 | |TF_IDF_Model.py|朴素贝叶斯算法|
12 | |SVM_Model.py|svm算法|
13 |
14 | ## 程序结果
15 | ### 朴素贝叶斯结果
16 |
17 |

18 |
19 | 
20 |
21 | ### svm结果
22 | 
23 |
24 | 
25 |
--------------------------------------------------------------------------------
/WordSegmentation.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import sys
3 | import re
4 | import jieba.posseg
5 | import os
6 | import MySQLdb
7 | reload(sys)
8 | sys.setdefaultencoding('utf-8')
9 |
10 | def savefile(dirpath,filepath,content):
11 |
12 | if os.path.exists(dirpath)==False:
13 | os.makedirs(dirpath)
14 |
15 | savepath = os.path.join(dirpath,filepath)
16 | print(savepath)
17 | with open(savepath,"w") as fp:
18 | fp.write(content)
19 | fp.close()
20 |
21 | def function(datalist,path):
22 | stopwords = []
23 | for word in open('stop_words_ch.txt', 'r'):
24 | stopwords.append(word.strip())
25 |
26 | db = MySQLdb.connect("localhost", "root", "root", "datamining", charset='utf8')
27 | cursor = db.cursor()
28 |
29 | i = 200001
30 |
31 | for item in datalist:
32 | sql = "select content from " + item
33 | cursor.execute(sql)
34 | results = cursor.fetchall()
35 |
36 | for row in results:
37 | content = []
38 | temptest = re.sub("[@·《》、.%,。?“”():(\u3000)(\xa0)!… ;▼]|[a-zA-Z0-9]|['月''日''年']", "", row['content'])
39 | words = jieba.posseg.cut(temptest)
40 | for w in words:
41 | if w.word not in stopwords and w.flag == 'n':
42 | content.append(w.word)
43 |
44 | forpath = path + "/" + item.replace("_even","").replace("_odd","")
45 | subpath = str(i) +".txt"
46 | savefile(forpath,subpath," ".join(content))
47 | i = i+1
48 | conn.close()
49 |
50 | if __name__=="__main__":
51 | test = ['education_odd', 'ent_odd','food_odd', 'healthy_odd','history_odd', 'houseproperty_odd','military_odd', 'sport_odd','tock_odd', 'technology_odd']
52 | path = ""
53 | function(test, path)
54 | # train = ['education_even,ent_even,food_even,healthy_even,history_even,houseproperty_even,military_even,sport_even,stock_even,technology_even]
55 | # path = ""
56 | # function(train, path)
--------------------------------------------------------------------------------
/TF_IDF_Model.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import os
3 | import datetime
4 | import sys
5 | import pickle
6 | from sklearn.feature_extraction.text import TfidfVectorizer
7 | from sklearn.datasets.base import Bunch
8 | from sklearn import svm
9 | from sklearn.metrics import classification_report
10 | from sklearn.naive_bayes import MultinomialNB
11 | from sklearn import metrics
12 | from sklearn.feature_selection import SelectKBest
13 | from sklearn.feature_selection import chi2
14 | import numpy as np
15 | import pandas as pd
16 | from sklearn.metrics import confusion_matrix
17 |
18 | reload(sys)
19 | sys.setdefaultencoding('utf-8')
20 |
21 |
22 | class TF_IDF:
23 | data_path = "/Users/wangyuhui/Desktop/dataminingData/train/"
24 | test_path = "/Users/wangyuhui/Desktop/dataminingData/test/"
25 | result_path = "/Users/wangyuhui/Desktop/dataminingResult1/"
26 | stop_words_path = "/Users/wangyuhui/Desktop/dataminingData/stop_words_ch.txt"
27 | #class_path = "../test_res/"
28 | stop_words = []
29 | class_code = {"healthy":0,"history":1,"education":2,"ent":3,
30 | "food":4,"houseproperty":5,"military":6,"sport":7,
31 | "stock":8,"technology":9}
32 |
33 | def __init__(self):
34 | self.ConfusionMatrix = np.zeros([len(TF_IDF.class_code),len(TF_IDF.class_code)])
35 | TF_IDF.stop_words = self.read_file(TF_IDF.stop_words_path).strip().split("\n")
36 |
37 | def printList(self, mylist):
38 | for item in mylist:
39 | print item,
40 | print
41 |
42 | # 写文件
43 | def save_file(self, path, content):
44 | with open(path, 'w') as f:
45 | f.write(content)
46 |
47 | # 读文件
48 | def read_file(self, path):
49 | with open(path, 'r') as f:
50 | return f.read()
51 | #读取bunch文件
52 | def readbunchobj(self,path):
53 | with open(path, "rb") as file_obj:
54 | bunch = pickle.load(file_obj)
55 | return bunch
56 |
57 | def writebunchobj(self,path, bunchobj):
58 | with open(path, "wb") as file_obj:
59 | pickle.dump(bunchobj, file_obj)
60 |
61 | # 加载分词结果文件
62 | def loadSegmentation(self,path):
63 | begintime = datetime.datetime.now()
64 | fileDocs = os.listdir(path)
65 | print fileDocs
66 | for item in fileDocs:
67 | if item.startswith("."):
68 | fileDocs.remove(item)
69 | print fileDocs
70 | bunch = Bunch(target_name=[], label=[], filenames=[], contents=[])
71 | bunch.target_name.extend(fileDocs)
72 | # 获取每个目录下所有的文件
73 | for mydir in fileDocs:
74 | class_path = path + mydir + "/" # 拼出分类子目录的路径
75 | file_list = os.listdir(class_path) # 获取class_path下的所有文件
76 | for file_path in file_list: # 遍历类别目录下文件
77 | if file_path.endswith("txt") == False:
78 | continue
79 | fullname = class_path + file_path # 拼出文件名全路径
80 | bunch.label.append(mydir)
81 | bunch.contents.append(self.read_file(fullname)) # 读取文件内容
82 | bunch.filenames.append(mydir+"/"+file_path)
83 | self.writebunchobj(TF_IDF.result_path+"trainData.dat",bunch)
84 | endtime = datetime.datetime.now()
85 | span = endtime - begintime
86 | print "训练bunch:contents长度、label长度:",len(bunch.contents),len(bunch.label)
87 | print "训练数据保存完成,所花费时间为",span.seconds
88 | def loadTestData(self, path):
89 | begintime = datetime.datetime.now()
90 | fileDocs = os.listdir(path)
91 | print fileDocs
92 | for item in fileDocs:
93 | if item.startswith("."):
94 | fileDocs.remove(item)
95 | print fileDocs
96 | bunch = Bunch(target_name=[], label=[], filenames=[], contents=[])
97 | bunch.target_name.extend(fileDocs)
98 | # 获取每个目录下所有的文件
99 | for mydir in fileDocs:
100 | class_path = path + mydir + "/" # 拼出分类子目录的路径
101 | file_list = os.listdir(class_path) # 获取class_path下的所有文件
102 | for file_path in file_list: # 遍历类别目录下文件
103 | if file_path.endswith("txt") == False:
104 | continue
105 | fullname = class_path + file_path # 拼出文件名全路径
106 | bunch.label.append(mydir)
107 | bunch.contents.append(self.read_file(fullname)) # 读取文件内容
108 | bunch.filenames.append(mydir + "/" + file_path)
109 | self.writebunchobj(TF_IDF.result_path + "testData.dat", bunch)
110 | endtime = datetime.datetime.now()
111 | span = endtime - begintime
112 | print "测试bunch:contents长度、label长度:", len(bunch.contents), len(bunch.label)
113 | print "测试数据保存完成,所花费时间为",span.seconds
114 |
115 | def calculateTFIDF(self,train_tfidf_path,bunch_path,tfidf_path):
116 | begintime = datetime.datetime.now()
117 | bunch = self.readbunchobj(bunch_path)
118 | tfidfspace = Bunch(target_name=bunch.target_name, label=bunch.label, filenames=bunch.filenames, tfidfmetrix=[],
119 | vocabulary={})
120 |
121 | if train_tfidf_path is not None:
122 | trainbunch = self.readbunchobj(train_tfidf_path)
123 | tfidfspace.vocabulary = trainbunch.vocabulary
124 | vectorizer = TfidfVectorizer(stop_words=TF_IDF.stop_words, sublinear_tf=True, max_df=0.5,
125 | vocabulary=trainbunch.vocabulary)
126 | tfidfspace.tfidfmetrix = vectorizer.fit_transform(bunch.contents)
127 |
128 | else:
129 | vectorizer = TfidfVectorizer(stop_words=TF_IDF.stop_words, sublinear_tf=True, max_df=0.5)
130 | tfidfspace.tfidfmetrix = vectorizer.fit_transform(bunch.contents)
131 | tfidfspace.vocabulary = vectorizer.vocabulary_
132 | self.writebunchobj(TF_IDF.result_path + "myvocabulary.dat", vectorizer.vocabulary_)
133 | # ch2 = SelectKBest(chi2, k=130000)
134 | # train_X = ch2.fit_transform()
135 |
136 | self.writebunchobj(tfidf_path, tfidfspace)
137 | endtime = datetime.datetime.now()
138 | span = endtime - begintime
139 | if train_tfidf_path is not None:
140 | print "生成测试tf-idf矩阵,所花费时间为",span.seconds
141 | else:
142 | print "生成训练tf-idf矩阵,所花费时间为",span.seconds
143 |
144 | def metrics_result(self,actual, predict):
145 | print('精度:{0:.3f}'.format(metrics.precision_score(actual, predict, average='weighted')))
146 | print('召回:{0:0.3f}'.format(metrics.recall_score(actual, predict, average='weighted')))
147 | print('f1-score:{0:.3f}'.format(metrics.f1_score(actual, predict, average='weighted')))
148 | print(classification_report(testSet.label, predict))
149 |
150 | def trainProcess(self,trainSet):
151 | print "朴素贝叶斯训练过程开始:"
152 | begintime = datetime.datetime.now()
153 | # 训练分类器:输入词袋向量和分类标签,alpha:0.001 alpha越小,迭代次数越多,精度越高
154 | clf = MultinomialNB(alpha=0.001).fit(trainSet.tfidfmetrix, trainSet.label)
155 | with open(TF_IDF.result_path+"MultinomialNBModel.dat", "wb") as file_obj:
156 | pickle.dump(clf, file_obj)
157 | endtime = datetime.datetime.now()
158 | span = endtime - begintime
159 | print "朴素贝叶斯训练时间:",span.seconds
160 |
161 | def SVMProcess(self, trainSet):
162 | print "SVM训练过程开始:"
163 | begintime = datetime.datetime.now()
164 | clf = svm.SVC(C=1.0, cache_size=800, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3,
165 | gamma='auto', kernel='linear', max_iter=-1, probability=False, random_state=None, shrinking=True,
166 | tol=0.001, verbose=False)
167 | clf.fit(trainSet.tfidfmetrix, trainSet.label)
168 | with open("/Users/wangyuhui/Desktop/svmResult/svmModel.dat", "wb") as file_obj:
169 | # with open(TF_IDF.result_path + "svmModel.dat", "wb") as file_obj:
170 | pickle.dump(clf, file_obj)
171 | endtime = datetime.datetime.now()
172 | span = endtime - begintime
173 | print "SVM训练时间:", span.seconds
174 | test_tfidf_path = TF_IDF.result_path + "test_tfidf_svm.dat"
175 | testSet = TF_IDF.readbunchobj(test_tfidf_path)
176 | self.predictProcess("/Users/wangyuhui/Desktop/svmResult/svmModel.dat",testSet)
177 |
178 | def predictProcess(self,modelPath,testSet):
179 | if modelPath is None:
180 | print "模型路径未知"
181 | return
182 | clf = self.readbunchobj(modelPath)
183 | errorFile = "MultinomialNBerror.txt"
184 | if modelPath.find("svm") != -1:
185 | errorFile = "SVMerror.txt"
186 | print "加载模型成功"
187 | # 预测分类结果
188 | predicted = clf.predict(testSet.tfidfmetrix)
189 | outPutList = []
190 | for flabel, file_name, expct_cate in zip(testSet.label, testSet.filenames, predicted):
191 | self.ConfusionMatrix[TF_IDF.class_code[flabel]][TF_IDF.class_code[expct_cate]] += 1
192 | if flabel != expct_cate:
193 | outPutList.append(file_name + ": 实际类别:" + flabel + " -->预测类别:" + expct_cate)
194 | self.save_file(TF_IDF.result_path + errorFile, "\n".join(outPutList))
195 | print("预测完成")
196 | self.showPredictResult()
197 | self.metrics_result(testSet.label, predicted)
198 | print "混淆矩阵为:"
199 | # 显示所有列
200 | pd.set_option('display.max_columns', None)
201 | # 显示所有行
202 | pd.set_option('display.max_rows', None)
203 | print pd.DataFrame(confusion_matrix(testSet.label, predicted),
204 | columns=["education", "ent", "food", "healthy", "history", "houseproperty", "military",
205 | "sport", "stock", "technology"],
206 | index=["education", "ent", "food", "healthy", "history", "houseproperty", "military",
207 | "sport", "stock", "technology"])
208 |
209 | def showPredictResult(self):
210 | for i in range(len(self.ConfusionMatrix)):
211 | keyWord = ""
212 | for key in TF_IDF.class_code:
213 | if TF_IDF.class_code[key] == i:
214 | keyWord = key
215 | break
216 | print "==================================================="
217 | print keyWord + "类预测总数为:", np.sum([self.ConfusionMatrix[i]])
218 | print keyWord + "类预测正确数为:", self.ConfusionMatrix[i][i]
219 | for j in range(len(self.ConfusionMatrix[0])):
220 | if j == i:
221 | continue
222 | predictKey = ""
223 | for key in TF_IDF.class_code:
224 | if TF_IDF.class_code[key] == j:
225 | predictKey = key
226 | break
227 | print keyWord+"类预测为"+predictKey+"数为:", self.ConfusionMatrix[i][j]
228 | print "==================================================="
229 |
230 |
231 |
232 | if __name__ == '__main__':
233 | TF_IDF = TF_IDF()
234 | # 步骤1
235 | # TF_IDF.loadSegmentation(TF_IDF.data_path)
236 | # TF_IDF.loadTestData(TF_IDF.test_path)
237 |
238 | # 步骤2
239 | # train_tfidf_path = TF_IDF.result_path+"train_tfidf.dat"
240 | # train_bunch_path = TF_IDF.result_path+"trainData.dat"
241 | # TF_IDF.calculateTFIDF(train_tfidf_path=None,bunch_path=train_bunch_path,tfidf_path=train_tfidf_path)
242 |
243 | # test_tfidf_path = TF_IDF.result_path+"test_tfidf.dat"
244 | # test_bunch_path = TF_IDF.result_path+"testData.dat"
245 | # TF_IDF.calculateTFIDF(train_tfidf_path=train_tfidf_path, bunch_path=test_bunch_path, tfidf_path=test_tfidf_path)
246 |
247 | # 步骤3
248 | # train_tfidf_path = TF_IDF.result_path + "train_tfidf.dat"
249 | # trainSet = TF_IDF.readbunchobj(train_tfidf_path)
250 | # TF_IDF.trainProcess(trainSet)
251 |
252 | # 步骤4
253 | test_tfidf_path = TF_IDF.result_path + "test_tfidf.dat"
254 | testSet = TF_IDF.readbunchobj(test_tfidf_path)
255 | MultinomialNBPath = TF_IDF.result_path + "MultinomialNBModel.dat"
256 | TF_IDF.predictProcess(MultinomialNBPath,testSet)
257 |
258 | # 步骤2
259 | # train_tfidf_path = TF_IDF.result_path + "train_tfidf_svm.dat"
260 | # train_bunch_path = TF_IDF.result_path + "trainData.dat"
261 | # TF_IDF.calculateTFIDF(train_tfidf_path=None,bunch_path=train_bunch_path,tfidf_path=train_tfidf_path)
262 |
263 | # test_tfidf_path = TF_IDF.result_path + "test_tfidf_svm.dat"
264 | # test_bunch_path = TF_IDF.result_path + "testData.dat"
265 | # #TF_IDF.calculateTFIDF(train_tfidf_path=train_tfidf_path, bunch_path=test_bunch_path, tfidf_path=test_tfidf_path)
266 |
267 | # 步骤3
268 | # train_tfidf_path = TF_IDF.result_path + "train_tfidf_svm.dat"
269 | # trainSet = TF_IDF.readbunchobj(train_tfidf_path)
270 | # TF_IDF.SVMProcess(trainSet)
271 |
272 | # 步骤4
273 | # test_tfidf_path = "/Users/wangyuhui/Desktop/svmResult1/test_tfidf_svm.dat"
274 | # testSet = TF_IDF.readbunchobj(test_tfidf_path)
275 | # svmPath = "/Users/wangyuhui/Desktop/forest/svmModel.dat"
276 | # TF_IDF.predictProcess(svmPath,testSet)
277 |
278 |
--------------------------------------------------------------------------------
/SVM_Model.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import os
3 | import datetime
4 | import sys
5 | import pickle
6 | from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
7 | from sklearn.datasets.base import Bunch
8 | from sklearn import svm
9 | from sklearn.metrics import classification_report
10 | from sklearn.naive_bayes import MultinomialNB
11 | from sklearn import metrics
12 | from sklearn.feature_selection import SelectKBest
13 | from sklearn.feature_selection import chi2
14 | import numpy as np
15 | import pandas as pd
16 | from sklearn.metrics import confusion_matrix
17 |
18 | reload(sys)
19 | sys.setdefaultencoding('utf-8')
20 |
21 |
22 | class TF_IDF:
23 | # data_path = "/Users/wangyuhui/Desktop/dataminingData/train/"
24 | # test_path = "/Users/wangyuhui/Desktop/dataminingData/test/"
25 | # result_path = "/Users/wangyuhui/Desktop/dataminingResult1/"
26 | # stop_words_path = "/Users/wangyuhui/Desktop/dataminingData/stop_words_ch.txt"
27 |
28 | data_path = "/Users/wangyuhui/Desktop/dataminingData/train/"
29 | test_path = "/Users/wangyuhui/Desktop/dataminingData/test/"
30 | # result_path = "C:\\Users\\zo\\Desktop\\dataminingResult\\"
31 | result_path = "/Users/wangyuhui/Desktop/svmResult/"
32 | stop_words_path = "/Users/wangyuhui/Desktop/dataminingData/stop_words_ch.txt"
33 | #class_path = "../test_res/"
34 | stop_words = []
35 | class_code = {"healthy":0,"history":1,"education":2,"ent":3,
36 | "food":4,"houseproperty":5,"military":6,"sport":7,
37 | "stock":8,"technology":9}
38 |
39 | def __init__(self):
40 | self.ConfusionMatrix = np.zeros([len(TF_IDF.class_code),len(TF_IDF.class_code)])
41 | TF_IDF.stop_words = self.read_file(TF_IDF.stop_words_path).strip().split("\n")
42 |
43 | def printList(self, mylist):
44 | for item in mylist:
45 | print item,
46 | print
47 |
48 | # 写文件
49 | def save_file(self, path, content):
50 | with open(path, 'w') as f:
51 | f.write(content)
52 |
53 | # 读文件
54 | def read_file(self, path):
55 | with open(path, 'r') as f:
56 | return f.read()
57 | #读取bunch文件
58 | def readbunchobj(self,path):
59 | with open(path, "rb") as file_obj:
60 | bunch = pickle.load(file_obj)
61 | return bunch
62 |
63 | def writebunchobj(self,path, bunchobj):
64 | with open(path, "wb") as file_obj:
65 | pickle.dump(bunchobj, file_obj)
66 |
67 | # 加载分词结果文件
68 | def loadSegmentation(self, path):
69 | begintime = datetime.datetime.now()
70 | fileDocs = os.listdir(path)
71 | print fileDocs
72 | for item in fileDocs:
73 | if item.startswith("."):
74 | fileDocs.remove(item)
75 | print fileDocs
76 | bunch = Bunch(target_name=[], label=[], filenames=[], contents=[])
77 | bunch.target_name.extend(fileDocs)
78 | # 获取每个目录下所有的文件
79 | for mydir in fileDocs:
80 | class_path = path + mydir + "/" # 拼出分类子目录的路径
81 | file_list = os.listdir(class_path) # 获取class_path下的所有文件
82 | for file_path in file_list: # 遍历类别目录下文件
83 | if file_path.endswith("txt") == False:
84 | continue
85 | fullname = class_path + file_path # 拼出文件名全路径
86 | bunch.label.append(mydir)
87 | bunch.contents.append(self.read_file(fullname)) # 读取文件内容
88 | bunch.filenames.append(mydir + "/" + file_path)
89 | self.writebunchobj(TF_IDF.result_path + "trainData.dat", bunch)
90 | endtime = datetime.datetime.now()
91 | span = endtime - begintime
92 | print "训练bunch:contents长度、label长度:", len(bunch.contents), len(bunch.label)
93 | print "训练数据保存完成,所花费时间为", span.seconds
94 | def loadTestData(self, path):
95 | begintime = datetime.datetime.now()
96 | fileDocs = os.listdir(path)
97 | print fileDocs
98 | for item in fileDocs:
99 | if item.startswith("."):
100 | fileDocs.remove(item)
101 | print fileDocs
102 | bunch = Bunch(target_name=[], label=[], filenames=[], contents=[])
103 | bunch.target_name.extend(fileDocs)
104 | # 获取每个目录下所有的文件
105 | for mydir in fileDocs:
106 | class_path = path + mydir + "/" # 拼出分类子目录的路径
107 | file_list = os.listdir(class_path) # 获取class_path下的所有文件
108 | for file_path in file_list: # 遍历类别目录下文件
109 | if file_path.endswith("txt") == False:
110 | continue
111 | fullname = class_path + file_path # 拼出文件名全路径
112 | bunch.label.append(mydir)
113 | bunch.contents.append(self.read_file(fullname)) # 读取文件内容
114 | bunch.filenames.append(mydir + "/" + file_path)
115 | self.writebunchobj(TF_IDF.result_path + "testData.dat", bunch)
116 | endtime = datetime.datetime.now()
117 | span = endtime - begintime
118 | print "测试bunch:contents长度、label长度:", len(bunch.contents), len(bunch.label)
119 | print "测试数据保存完成,所花费时间为",span.seconds
120 |
121 | def calculateTFIDF(self,train_tfidf_path,bunch_path,tfidf_path):
122 | begintime = datetime.datetime.now()
123 | bunch = self.readbunchobj(bunch_path)
124 | tfidfspace = Bunch(target_name=bunch.target_name, label=bunch.label, filenames=bunch.filenames, tfidfmetrix=[],
125 | vocabulary={})
126 |
127 | if train_tfidf_path is not None:
128 | trainbunch = self.readbunchobj(train_tfidf_path)
129 | tfidfspace.vocabulary = trainbunch.vocabulary
130 | vectorizer = TfidfVectorizer(stop_words=TF_IDF.stop_words, sublinear_tf=True, max_df=0.5,
131 | vocabulary=trainbunch.vocabulary)
132 | tfidfspace.tfidfmetrix = vectorizer.fit_transform(bunch.contents)
133 |
134 | else:
135 | vectorizer = TfidfVectorizer(stop_words=TF_IDF.stop_words, sublinear_tf=True, max_df=0.5)
136 | tfidfspace.tfidfmetrix = vectorizer.fit_transform(bunch.contents)
137 | tfidfspace.vocabulary = vectorizer.vocabulary_
138 | self.writebunchobj(TF_IDF.result_path+"myvocabulary.dat", vectorizer.vocabulary_)
139 | # ch2 = SelectKBest(chi2, k=130000)
140 | # train_X = ch2.fit_transform()
141 |
142 | self.writebunchobj(tfidf_path, tfidfspace)
143 | endtime = datetime.datetime.now()
144 | span = endtime - begintime
145 | if train_tfidf_path is not None:
146 | print "生成测试tf-idf矩阵,所花费时间为",span.seconds
147 | else:
148 | print "生成训练tf-idf矩阵,所花费时间为",span.seconds
149 |
150 | def metrics_result(self,actual, predict):
151 | print('精度:{0:.3f}'.format(metrics.precision_score(actual, predict, average='weighted')))
152 | print('召回:{0:0.3f}'.format(metrics.recall_score(actual, predict, average='weighted')))
153 | print('f1-score:{0:.3f}'.format(metrics.f1_score(actual, predict, average='weighted')))
154 | print(classification_report(testSet.label, predict))
155 |
156 | def trainProcess(self,trainSet):
157 | print "朴素贝叶斯训练过程开始:"
158 | begintime = datetime.datetime.now()
159 | # 训练分类器:输入词袋向量和分类标签,alpha:0.001 alpha越小,迭代次数越多,精度越高
160 | clf = MultinomialNB(alpha=0.001).fit(trainSet.tfidfmetrix, trainSet.label)
161 | with open(TF_IDF.result_path+"MultinomialNBModel.dat", "wb") as file_obj:
162 | pickle.dump(clf, file_obj)
163 | endtime = datetime.datetime.now()
164 | span = endtime - begintime
165 | print "朴素贝叶斯训练时间:",span.seconds
166 |
167 | def SVMProcess(self, trainSet):
168 | print "SVM训练过程开始:"
169 | begintime = datetime.datetime.now()
170 | clf = svm.SVC(C=1.0, cache_size=800, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3,
171 | gamma='auto', kernel='linear', max_iter=-1, probability=False, random_state=None, shrinking=True,
172 | tol=0.001, verbose=False)
173 | clf.fit(trainSet.tfidfmetrix, trainSet.label)
174 | with open(TF_IDF.result_path+"svmModel.dat", "wb") as file_obj:
175 | # with open(TF_IDF.result_path + "svmModel.dat", "wb") as file_obj:
176 | pickle.dump(clf, file_obj)
177 | endtime = datetime.datetime.now()
178 | span = endtime - begintime
179 | print "SVM训练时间:", span.seconds
180 |
181 | def predictProcess(self,modelPath,testSet,predictedResult):
182 | begintime = datetime.datetime.now()
183 | if modelPath is None:
184 | print "模型路径未知"
185 | return
186 | clf = self.readbunchobj(modelPath)
187 | errorFile = "MultinomialNBerror.txt"
188 | if modelPath.find("svm") != -1:
189 | errorFile = "SVMerror.txt"
190 | print "加载模型成功"
191 | endtime = datetime.datetime.now()
192 | span = endtime - begintime
193 | begintime = endtime
194 | print "加载模型时间:", span.seconds
195 | predicted = predictedResult
196 | # 预测分类结果
197 | if predictedResult is None:
198 | predicted = clf.predict(testSet.tfidfmetrix)
199 | self.writebunchobj(TF_IDF.result_path + "predictedresult.dat", predicted)
200 | outPutList = []
201 | for flabel, file_name, expct_cate in zip(testSet.label, testSet.filenames, predicted):
202 | self.ConfusionMatrix[TF_IDF.class_code[flabel]][TF_IDF.class_code[expct_cate]] += 1
203 | if flabel != expct_cate:
204 | outPutList.append(file_name + ": 实际类别:" + flabel + " -->预测类别:" + expct_cate)
205 | self.save_file(TF_IDF.result_path + errorFile, "\n".join(outPutList))
206 | print("预测完成")
207 | self.showPredictResult()
208 | self.metrics_result(testSet.label, predicted)
209 | print "混淆矩阵为:"
210 | # 显示所有列
211 | pd.set_option('display.max_columns', None)
212 | # 显示所有行
213 | pd.set_option('display.max_rows', None)
214 | print pd.DataFrame(confusion_matrix(testSet.label, predicted),
215 | columns=["healthy", "history", "education", "ent", "food", "houseproperty", "military",
216 | "sport", "stock", "technology"],
217 | index=["healthy", "history", "education", "ent", "food", "houseproperty","military","sport","stock","technology"])
218 | endtime = datetime.datetime.now()
219 | span = endtime - begintime
220 | print "SVM预测时间:", span.seconds
221 |
222 | def showPredictResult(self):
223 | for i in range(len(self.ConfusionMatrix)):
224 | keyWord = ""
225 | for key in TF_IDF.class_code:
226 | if TF_IDF.class_code[key] == i:
227 | keyWord = key
228 | break
229 | print "==================================================="
230 | print keyWord + "类预测总数为:", np.sum([self.ConfusionMatrix[i]])
231 | print keyWord + "类预测正确数为:", self.ConfusionMatrix[i][i]
232 | for j in range(len(self.ConfusionMatrix[0])):
233 | if j == i:
234 | continue
235 | predictKey = ""
236 | for key in TF_IDF.class_code:
237 | if TF_IDF.class_code[key] == j:
238 | predictKey = key
239 | break
240 | print keyWord+"类预测为"+predictKey+"数为:", self.ConfusionMatrix[i][j]
241 | print "==================================================="
242 |
243 | def TestDemo(self,vocabulary,clf):
244 | healthy = "因素 肝癌 风险 乙型肝炎"
245 | food = "孩子 饭菜 家常菜 豆腐"
246 | education = "流感 步伐 流感 疑似病例 学生家长 电话 程度 流感 想象 流感 病例 人数 人 流感病毒 学生家长 情况 流感病毒 流感病毒 毒性 病毒 时期 平均温度 摄氏度 温度 病毒传播 高峰期 流感病毒 能力 流感病毒 情况 医疗 部门 疾病 控制能力 病例 病例 医疗 条件 技术 程度 留学生 流感病毒 时期 学生 签证官 学生 成功率 情况 时期 国家 情况 留学生 进程 反观 流感病毒 事件 全球 疫情 国家 全球 疑似病例 国家 病例 数 留学生 国家 情况 学生 开学 个的 事件 政府 流感病毒 流感病毒 疑似病例 患者 大学 学校 校区 学校 患者 校区 校区 病例 个体 案例 公司 公司 办理 名 学生家长 学生 猪 流感 计划 家长 公司 学生家长 计划 家长 入学 关键时刻 孩子 学期 公司 办理 世界 留学生 情况 猪 流感 常识 家长 疫情 地区 留学生 学员 传染性 疾病 常识"
247 | ent = "名状 海角 名单 评委 名状 图 影片 名单 电影 名状 项 赢家 海角 剧情片 男配角 新人 项 电影 海水 火焰 剧情片 男女 主角 赤壁 男配角 项 奖项 电影票房 名单 男孩 降风 原著 剧本 男孩 剧情片 女配角 演员 女主角 光芒 女星 首度 有缘 首度 移师 大使 女主角 男主角 入围者 实力 同场竞技 精彩 硬仗 演员 电影 海角 同片 局面 男孩 骗子 众人 短片 格子 群雄 歌坛 大 灌篮 主题曲 原创 电影 歌曲 电影 工作者 海角 电影票房 新台币 电影 新气象 本土 感情 代表 人物 发迹 脱俗 亮眼 国际 男星 光 电影 资深 灯光师 厂 电影 后辈 奖项 名状 共项 男主角 剧情片 视觉效果 美术设计 造型 动作 原著 剧本 原创 电影 音乐 音效 剪辑 摄影 海角 共项 剧情片 演员 男配角 原创 电影 歌曲 音效 摄影 电影 共项 剧情片 男主角 剧本 动作 视觉效果 音效 海水 火焰 共项 男主角 女主角 剧情片 美术设计 摄影 赤壁 共项 男配角 视觉效果 造型 美术设计 男孩 共项 演员 女配角 原著 剧本 剧情片 事儿 共项 男配角 剧本 造型"
248 | history = "小白菜 案 刑部 尚书"
249 | houseproperty = "外观 图 风格 印花 餐具 外观 涂鸦 花卉 图案 特色 线条 气质 厨房 格调 特质"
250 | military = "对岸 空军 装备 战斗机 军迷 陌生 世纪 对岸 战斗机 型号 老式 性能 盟国 天线 空空导弹 全天候 目标 吊舱 水平 机群 大陆 空军 劲敌 力量对比 大陆 空军 麾下 阵容 对岸 风光 无机 窘境 国际形势 实力 对岸 战斗机 可能性 短期内 现实 机群 对岸 量身 套装 服役 本份 对岸 空军 战斗机 时代 媒体 技术 成果 整体 性能 大陆 空军 级别 机型 服役 改进型 战斗机 单发 中型机 问世 军队 地位 小个子 空战 武器 对岸 空军 顶尖 机型 田忌赛马 对岸 马 大陆 空军 马 对岸 航电 有源 相控阵 航电 系统 技术 原型 能力 航电 功率 逊色 空战 武器 装备 头盔 显示器 基本上 射程 性能 机动性 发动机 发动机 空重 发动机 空重 航电 系统 机身 结构 优势 鸭式 布局 能力 稳盘 能力 机 后者 机体 状态 机龄 新机 起跑线 性能 力压 对岸 利器 大陆 人 事实 大度 心理 事实 作者 利刃 刻雨 无痕 内容 军事 官方 公众 军事 官方 栏目 文章 目的 信息 代表 观点 真实性 凡本网 版权所有 作品版权 作者 版权 原作者 人 本网 作者 利用 方式 作品 军事 军 军事 门户"
251 | sport = "爵士 胖友 距离 差分 哥 福 分差 爵士队 净输分 全场 爵士队 下半场 队史 纪录 爵士 人 队史 赢球 差 纪录 爵士 主场 专业 战 底线 手感 价格公道 问 分差 数据 小 均分 手下留情 人 数据 罚球 命中率 图 图 腿 打篮球 腿 帅气 后仰 腿 大 木桩 区别 近景 球员 镜头 印象 毛钱"
252 | stock = "经济 数据 财经 消息 汇率 跌势 原因 政府 报告 生产者 汇率 元 跌幅 汇率 涨幅 汇率 跌幅 报告 称份 经济学家 报告 称份 生产者 国际 货币 汇率 均告 过度 理由 货币 汇率 原因 股市 投资者 银行 证券公司 外汇 策略师 政府 报告 投资者 信心 重创 投资者 风险 情绪 跌幅 原因 抗议者 政府部门 水平 汇率 涨幅 汇率 涨幅 原因 股市 市场 投资者 利差 交易 交易 投资者 利率 国家 贷款 地区 收益 资产"
253 | technology = "电脑网 游戏 奖项 游戏 奖项 游戏 刺客 信条 战神 蜘蛛侠 怪物 猎人 世界 荒野 镖客 游戏 名单 玩家 荒野 镖客 荒野 镖客 荒野 镖客 游戏 言论 荒野 镖客 游戏 玩家 分量 荒野 镖客 星 游戏 游戏 历时 花费 剧情 系统 画面 游戏 机构 玩家 游戏 大作 游戏 游戏机 电视 游玩 程度 电视 画质 性能 游戏 厂商 事情 高端 电视 荒野 镖客 高端 游戏 画面 外媒 荒野 镖客 画面 事情 游戏 原生 效果 外媒 荒野 镖客 游戏 屏幕 绘制 光谱 图 记录 亮度 光谱 颜色 图像 颜色 水平 动态 颜色 基本上 图像 灰色 粉红色 内容 红色 橙色 结论 荒野 镖客 效果 玩家 选项 感觉 画面 星 玩家 效果 游戏 画质 整体 口碑 销量 游戏 笔者 朋友 朋友 游戏 玩家 游戏 总向 感觉 游戏 画质 电视 玩游戏 画质 电视 笔者 游戏 画质 游戏 画质 引擎 游戏机 机能 电视 画质 游戏 老 电视 玩游戏 游戏 画面 电视 锅 电影 同理 劲 片源 体验 锅 片源 电视 力 技术 画面 视频 技术 经历 漫长 视频 画质 分辨率 深灰 色域 空间 亮度 动态 基础 水平 时代 所幸 动态 市面上 平板电视 标准 电视 平板电视 标准 性能 产物 后者 基础 功能 静态 数据 性能 能力 门槛 公司 费用 电视 厂商 标准 创维 差异 技术 硬件 性能 企业 差距 图片 电视 影片 图 电视 影片 图 奇幻 图 整体 亮度 亮度 颜色 画面 面纱 人物 特写 差异 皮肤 颜色 大 逆光 画面 宽容度 人物 脸部皮肤 细节 细节 衣服 纹理 环境 亮度高 动态 实力 天空 云朵 逆光 飞机 暗部 细节 生机 效果 压倒性 优势 亮度 亮度 色彩 灰度 时代 想象 事物 内容 电影 游戏 电视 高标准 产品"
254 | content = [healthy,food,education,ent,history,houseproperty,military,sport,stock,technology]
255 | vectorizer = CountVectorizer(stop_words=TF_IDF.stop_words,vocabulary=vocabulary)
256 | content = vectorizer.fit_transform(content)
257 | #print content.toarray()
258 | label = clf.predict(content)
259 | print label
260 |
261 |
262 | if __name__ == '__main__':
263 | TF_IDF = TF_IDF()
264 | # 步骤1
265 | # TF_IDF.loadSegmentation(TF_IDF.data_path)
266 | # TF_IDF.loadTestData(TF_IDF.test_path)
267 |
268 | # 步骤2
269 | # train_tfidf_path = TF_IDF.result_path + "train_tfidf_svm.dat"
270 | # train_bunch_path = TF_IDF.result_path + "trainData.dat"
271 | # TF_IDF.calculateTFIDF(train_tfidf_path=None,bunch_path=train_bunch_path,tfidf_path=train_tfidf_path)
272 |
273 | # test_tfidf_path = TF_IDF.result_path + "test_tfidf_svm.dat"
274 | # test_bunch_path = TF_IDF.result_path + "testData.dat"
275 | # TF_IDF.calculateTFIDF(train_tfidf_path=train_tfidf_path, bunch_path=test_bunch_path, tfidf_path=test_tfidf_path)
276 |
277 | # 步骤3
278 | # train_tfidf_path = TF_IDF.result_path + "train_tfidf_svm.dat"
279 | # trainSet = TF_IDF.readbunchobj(train_tfidf_path)
280 | # TF_IDF.SVMProcess(trainSet)
281 |
282 | # 步骤4
283 | predictedResultPath = TF_IDF.result_path + "predictedresult.dat"
284 | test_tfidf_path = TF_IDF.result_path + "test_tfidf_svm.dat"
285 | testSet = TF_IDF.readbunchobj(test_tfidf_path)
286 | svmPath = TF_IDF.result_path + "svmModel.dat"
287 | predictedResult = TF_IDF.readbunchobj(predictedResultPath)
288 | TF_IDF.predictProcess(svmPath,testSet,predictedResult)
289 |
290 | # 步骤5
291 | vocabulary_path = TF_IDF.result_path + "myvocabulary.dat"
292 | vocabulary = TF_IDF.readbunchobj(vocabulary_path)
293 | svmPath = TF_IDF.result_path + "svmModel.dat"
294 | clf = TF_IDF.readbunchobj(svmPath)
295 | TF_IDF.TestDemo(vocabulary,clf)
296 |
297 |
298 |
--------------------------------------------------------------------------------