樸素貝葉斯應用:垃圾郵件分類

1. 數據準備:收集數據與讀取算法

2. 數據預處理:處理數據app

3. 訓練集與測試集:將先驗數據按必定比例進行拆分。dom

4. 提取數據特徵,將文本解析爲詞向量 。機器學習

5. 訓練模型:創建模型,用訓練數據訓練模型。即根據訓練樣本集,計算詞項出現的機率P(xi|y),後獲得各種下詞彙出現機率的向量 。學習

6. 測試模型:用測試數據集評估模型預測的正確率。測試

混淆矩陣spa

準確率、精確率、召回率、F值code

7. 預測一封新郵件的類別。orm

8. 考慮如何進行中文的文本分類(期末做業之一)。 blog

 

要點:

理解樸素貝葉斯算法

理解機器學習算法建模過程

理解文本經常使用處理流程

理解模型評估方法

#垃圾郵件分類

import csv
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer

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):
    #分詞
    tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] 
#對文本按照句子進行分割
#     for sent in nltk.sent_tokenize(text):  
#對句子進行分詞       
#         for word in nltk.word_tokenize(sent):          
#             print(word)
    tokens

    #停用詞
    stops = stopwords.words('english')
    stops

    #去掉停用詞
    tokens = [token for token in tokens if token not in stops]
    tokens

    #去掉短於3的詞
    tokens = [token.lower() for token in tokens if len(token)>=3]
    tokens

    #詞性還原
    lmtzr = WordNetLemmatizer()
    tokens = [lmtzr.lemmatize(token) for token in tokens]
    tokens

    #將剩下的詞從新鏈接成字符串
    preprocessed_text = ' '.join(tokens)
    return preprocessed_text

preprocessing(text)


#讀數據
file_path = r'C:\Users\s2009\Desktop\email.txt'
sms = open(file_path,'r',encoding = 'utf-8')
sms_data = []
sms_target = []
csv_reader = csv.reader(sms,delimiter = '\t')

#將數據分別存入數據列表和目標分類列表
for line in csv_reader:
    sms_data.append(preprocessing(line[1]))
    sms_target.append(line[0])
sms.close()

print("郵件總數爲:",len(sms_target))
sms_target



#將數據分爲訓練集和測試集
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(sms_data,sms_target,test_size=0.3,random_state=0,startify=sms_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='12')

X_train=vectorizer.fit_transform(x_train)
X_test=vectorizer.transform(x_test)

import numpy as np               
##觀察向量
a = X_train.toarray()
#X_test = X_test.toarray()
#X_train.shape
#X_train
 
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)

#分類結果顯示
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report

#x_test預測結果
print(y_nb_pred.shape,y_nb_pred)
print('nb_confusion_matrix:')
#混淆矩陣
cm=confusion_matrix(y_test,y_nb_pred)
print(cm)
print('nb_classification_report:')
#主要分類指標的文本報告cr=classification_report(y_test,y_nb_pred)
print(cr)

#出現過的單詞列表
feature_name=vectorizer.get_feature_name()
#先驗機率
coefs=clf_coef_ 
intercept=clf.intercept_
#對數機率p(x_i|y)與單詞x_i映射coefs_with_fns=sorted(zip(coefs[0],feature_names))

n=10
#最大的10個與最小的10個單詞top=zip(coefs_with_fns[:n],coefs_with_fns[:-(n+1):-1])
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))

 

 

相關文章
相關標籤/搜索