sklearn中的朴素贝叶斯模型及其应用
# 高斯分布型 from sklearn import datasets iris=datasets.load_iris() from sklearn.naive_bayes import GaussianNB gnb=GaussianNB() pred=gnb.fit(iris.data, iris.target) y_pred=pred.predict(iris.data) print(iris.data.shape[0],(iris.target != y_pred).sum())
#多项式型 from sklearn import datasets iris=datasets.load_iris() from sklearn.naive_bayes import MultinomialNB gnb=MultinomialNB() pred=gnb.fit(iris.data, iris.target) y_pred=pred.predict(iris.data) print(iris.data.shape[0],(iris.target != y_pred).sum())
#伯努利型 from sklearn import datasets iris=datasets.load_iris() from sklearn.naive_bayes import BernoulliNB gnb=BernoulliNB() pred=gnb.fit(iris.data, iris.target) y_pred=pred.predict(iris.data) print(iris.data.shape[0],(iris.target != y_pred).sum())
2.使用sklearn.model_selection.cross_val_score(),对模型进行验证:
#多项式型 from sklearn.naive_bayes import BernoulliNB from sklearn.model_selection import cross_val_score gnb=BernoulliNB() scores=cross_val_score(gnb,iris.data,iris.target,cv=10) print("Accuracy:%.3f"%scores.mean())
#伯努利型 from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import cross_val_score gnb=MultinomialNB() scores=cross_val_score(gnb,iris.data,iris.target,cv=10) print("Accuracy:%.3f"%scores.mean())
3. 垃圾邮件分类
import csv file_path=r'F:SMSSpamCollectionjs.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() sms_label sms_data=str(sms_data) sms_data=sms_data.lower() sms_data=sms_data.split() sms_newdata=[] i=0 #去掉长度小于3的词 for i in sms_data: if len(i)>4: sms_newdata.append(i) continue sms_newdata