使用朴素贝叶斯模型对iris数据集进行花分类
1.使用高斯分布型对iris数据集进行花分类
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 = gnb.predict(iris.data) # 分类预测 print(iris.data.shape[0],(iris.target != y_pred).sum())
2.使用多项式型对iris数据集进行花分类
from sklearn.datasets import load_iris
iris = 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())
3.使用伯努利型对iris数据集进行花分类
from sklearn.datasets import load_iris
iris = 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())
使用sklearn.model_selection.cross_val_score(),对模型进行验证。
1.高斯分布型
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())
2.多项式型
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.伯努利型
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())
3. 垃圾邮件分类
数据准备:
- 用csv读取邮件数据,分解出邮件类别及邮件内容。
- 对邮件内容进行预处理:去掉长度小于3的词,去掉没有语义的词等
尝试使用nltk库:
pip install nltk
import nltk
nltk.download
不成功:就使用词频统计的处理方法
import csv file_path=r'I:pythonSMSSpamCollectionjsn.txt' sms=open(file_path,'r',encoding='utf-8') sms_data=[] sms_label=[] csv_reader=csv.reader(sms,delimiter=' ') 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)