垃圾邮件分类

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


#预处理
def preprocessing(text):
    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)>=2]
    lmtzr=WordNetLemmatizer()
    tokens=[lmtzr.lemmatize(token) for token in tokens]
    preprocessed_text=' '.join(tokens)
    return preprocessed_text

preprocessing((text))


#读取数据集
import csv
file_path=r'C:\Users\pc\Desktop\SMSSpamCollectionjsn.txt'
sms=open(file_path,'r',encoding='utf-8')
sms_data=[]
sms_label=[]
csv_reader=csv.reader(sms,delimiter='\t')
for line in csv_reader:
    sms_label.append(line[0])
    sms_data.append(line[1])
sms.close();
print("邮件的总数:",len(sms_label))
sms_label


#划分训练集和测试集

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(sms_data,test_size=0.3,random_state=0,startify=sms_label)

#将其向量化
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_text=vectorizer.transform(x_test)

X_train
a=X_train.toarray()
print(a)

for i in range(1000):
    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)

 

转载于:https://www.cnblogs.com/PMAM/p/10078317.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值