sklearn中的朴素贝叶斯模型及其应用

时间:2022-07-15 15:09:44

1、(1)多项式

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.naive_bayes import BernoulliNB
bnl = BernoulliNB()
pred = bnl.fit(iris.data,iris.target)#g构造模型
y_pred = pred.predict(iris.data)#预测
print(iris.data.shape[0],(iris.target!=y_pred).sum())

sklearn中的朴素贝叶斯模型及其应用

(2)高斯分布型

from sklearn.naive_bayes import GaussianNB
gnb1=GaussianNB()#构造建立模型
pred=gnb1.fit(iris.data,iris.target)#模型训练,拟合
y_pred=gnb1.predict(iris.data)#分类预测
print(iris.data.shape[0],(iris.target!=y_pred).sum())
scores=cross_val_score(gnb1,iris.data,iris.target,cv=10)
print("Accuracy:%.3f"%scores.mean())
print(y_pred)

(3)伯努利型

from sklearn.naive_bayes import BernoulliNB
gnb2=BernoulliNB()#构造
pred=gnb2.fit(iris.data,iris.target)#模型训练,拟合
y_pred=gnb2.predict(iris.data)#分类预测
print(iris.data.shape[0],(iris.target!=y_pred).sum())
scores=cross_val_score(gnb2,iris.data,iris.target,cv=10)
print("Accuracy:%.3f"%scores.mean())
print(y_pred)

 

2、

from sklearn.datasets import load_iris
iris = load_iris() 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())

sklearn中的朴素贝叶斯模型及其应用

3、

import csv
file_path=r'D:\1\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()
sms_data=str(sms_data)#将列表转化为字符串
sms_data=sms_data.lower()#对大小写进行处理
sms_data=sms_data.split()#变成列表的形式
sms_data1=[]#存放处理后的内容
i=0
for i in sms_data:#去掉长度小于3的单词
if len(i)>4:
sms_data1.append(i)
continue