朴素貝葉斯應用:垃圾郵件分類
1. 數據准備:收集數據與讀取
2. 數據預處理:處理數據
3. 訓練集與測試集:將先驗數據按一定比例進行拆分。
4. 提取數據特征,將文本解析為詞向量 。
5. 訓練模型:建立模型,用訓練數據訓練模型。即根據訓練樣本集,計算詞項出現的概率P(xi|y),后得到各類下詞匯出現概率的向量 。
6. 測試模型:用測試數據集評估模型預測的正確率。
混淆矩陣 ,准確率、精確率、召回率、F值
7. 預測一封新郵件的類別。
#導入nltk數據包 import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer #導入包 import csv import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report text = '''As per your request 'Melle Melle (Oru Minnaminunginte Nurungu Vettam)' has been set as your callertune for all Callers. Press *9 to copy your friends Callertune''' #進行郵件預處理 def preprocessing(text): text=text.decode("utf-8") # 分詞 tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] stops = stopwords.words('english') #停用詞 tokens = [token for token in tokens if token not in stops] #去掉停用詞 tokens = [token.lower() for token in tokens if len(token) >= 3] #去掉短於3的詞 #詞性還原 lmtzr = WordNetLemmatizer() tokens = [lmtzr.lemmatize(token) for token in tokens] #將剩下的詞重新連接成字符串 preprocessed_text = ' '.join(tokens) return preprocessed_text #讀數據 file_path = r'C:\Users\Administrator\Desktop\ems.txt' ems = open(file_path,'r',encoding='utf-8') ems_data=[] ems_label=[] #保存 csv_reader=csv.reader(ems,delimiter='\t') #將數據分別存入數據列表和目標分類列表 for line in csv_reader: ems_label.append(line[0]) ems_data.append(preprocessing(line[1])) ems.close() #將數據分為訓練集和測試集,再將其向量化 from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(ems_data,ems_target,test_size=0.3,random_state=0,startify=ems_target) print(len(x_train,len(x_test))) # 將其向量化 from sklearn.feature_extraction.text import TfidfVectorizer #建立數據的特征向量 vectorizer=TfidfVectorizer(min_df=2,ngram_range=(1,2),stop_words='english',strip_accents='unicode',norm='l2') X_train = vectorizer.fit_transform(x_train) X_test = vectorizer.transform(x_test) import numpy as np #觀察向量 a = X_train.toarray() for i in range(1000): #輸出不為0的列 for j in range(5984): if a[i,j]!=0: print(i,j,a[i,j]) #朴素貝葉斯分類器 from sklearn.navie_bayes import MultinomialNB clf = MultinomialNB().fit(X_train,y_train) y_nb_pred = clf.predict(X_test) # 分類結果顯示 print(y_nb_pred.shape,y_nb_pred) # x-test預測結果 print('nb_confusion_matrix:') cm = confusion_matrix(y_test,y_nb_pred) #混淆矩陣 print(cm) print('nb_classification_repert:') cr = classification_report(y_test,y_nb_pred) # 主要分類指標的文本報告 print(cr) feature_names=vectorizer.get_feature_names() # 出現過的單詞列表 coefs=clf.coef_ # 先驗概率 p(x_ily),6034 feature_log_preb intercept = clf.intercept_ # P(y),class_log_prior : array,shape(n... coefs_with_fns=sorted(zip(coefs[0],feature_names)) #對數概率P(x_i|y)與單詞x_i映射 n=10 top=zip(coefs_with_fns[:n],coefs_with_fns[:-(n+1):-1]) #最大的10個與最小的10個單詞 for (coef_1,fn_1),(coef_2,fn_2) in top: print('\t%.4f\t%-15s\t\t%.4f\t%-15s' % (coef_1,fn_1,coef_2,fn_2)) #預測一封新郵件的類別。 new_email=['新郵件'] vectorizer(new_email) clf.predict(new_email)
結果: