from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
import csv
file_path=r'SMSSpamCollectionjsn.txt'
a=open(file_path,'r',encoding='utf-8')#预处理
a_data=[]
a_label=[]
csv_reader=csv.reader(a,delimiter='\t')
for line in csv_reader:
a_label.append(line[0])
a_data.append(line[1])
a.close()
def preprocessing(text):
preprocessing_text= text
return preprocessing_text
#按0.7:0.3比例分为训练集和测试集
X_train, X_test, Y_train, Y_test = train_test_split(a_data, a_label, test_size=0.3, random_state=0,stratify=a_label)
ectorizer=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)
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])
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))
(1671,) ['ham' 'ham' 'ham' ... 'ham' 'spam' 'ham']
nb_confusion_matrix:
[[1447 0]
[ 48 176]]
nb_classification_repert:
precision recall f1-score support
ham 0.97 1.00 0.98 1447
spam 1.00 0.79 0.88 224
avg / total 0.97 0.97 0.97 1671
-9.1053 10 smth -6.1149 free
-9.1053 15 -6.3421 txt
-9.1053 2go -6.4948 mobile
-9.1053 2gthr -6.5769 text
-9.1053 2gthr drinking -6.5780 claim
-9.1053 2marrow -6.6015 stop
-9.1053 2morrow -6.6108 ur
-9.1053 2mrw -6.6352 reply
-9.1053 2mrw luv -6.7198 www
-9.1053 2nd ur -6.7481 prize