1.使用朴素贝叶斯模型对iris数据集进行花分类 尝试使用3种不同类型的朴素贝叶斯: 高斯分布型 多项式型 伯努利型
from sklearn.datasets import load_iris
iris=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 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())
from sklearn imp
ort 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())
2.使用sklearn.model_selection.cross_val_score(),对模型进行验证。 from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import cross_val_score gnb=GaussianNB() scores=cross_val_score(gnb,iris.data,iris.target,cv=10) print("Accuracy:%.3f"%scores.mean()) 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())
def preprocessing(text): preprocessed_text=text return preprocessed_text import csv file_path=r‘C:\Users\Administrator\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(preprosessing(line[1])) #sms.close sms_label sms_data sms_label
原文地址:https://www.cnblogs.com/h000/p/10000226.html