sklearn中的樸素貝葉斯模型及其應用

1.使用樸素貝葉斯模型對iris數據集進行花分類app

嘗試使用3種不一樣類型的樸素貝葉斯:dom

 

高斯分佈型測試

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())

 

多項式型spa

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())

 

伯努利型3d

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())

 

運行結果:code

 

2.使用sklearn.model_selection.cross_val_score(),對模型進行驗證。blog

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())

 運行結果:ip

3. 垃圾郵件分類utf-8

數據準備:get

•  用csv讀取郵件數據,分解出郵件類別及郵件內容。

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(line[1])
sms.close()
sms_data

sms_label

 

運行結果:

 

•  對郵件內容進行預處理:去掉長度小於3的詞,去掉沒有語義的詞等

嘗試使用nltk庫:

pip install nltk

import nltk

nltk.download

不成功:就使用詞頻統計的處理方法

import csv
file_path=r"C:/Users/E5-572/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))
print(sms_label)
print(sms_data)

 

 

訓練集和測試集數據劃分

     •  from sklearn.model_selection import train_test_split

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

x_train
x_test

 

相關文章
相關標籤/搜索