【人工智能】机器学习 -- 贝叶斯分类器

目录

一、使用Python开发工具,运行对iris数据进行分类的例子程序NaiveBayes.py,熟悉sklearn机器实习开源库。

1. NaiveBayes.py

2. 运行结果

二、登录https://archive-beta.ics.uci.edu/

三、使用sklearn机器学习开源库,使用贝叶斯分类器对breast-cancer-wisconsin.data进行分类。

1. Python代码

2. 运行截图

四、用java实现贝叶斯分类器算法,并对上述数据进行分类。

1. 流程图

2. 数据结构

3. 算法

4. 测试结果

五、心得体会


一、使用Python开发工具,运行对iris数据进行分类的例子程序NaiveBayes.py,熟悉sklearn机器实习开源库。

1. NaiveBayes.py

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
import matplotlib


# %matplotlib inline

# 生成所有测试样本点
def make_meshgrid(x, y, h=.02):
    x_min, x_max = x.min() - 1, x.max() + 1
    y_min, y_max = y.min() - 1, y.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    return xx, yy


# 对测试样本进行预测,并显示
def plot_test_results(ax, clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax.contourf(xx, yy, Z, **params)


# 载入iris数据集
iris = datasets.load_iris()
# 只使用前面连个特征
X = iris.data[:, :2]
# 样本标签值
y = iris.target

# 创建并训练正态朴素贝叶斯分类器
clf = GaussianNB()
clf.fit(X, y)

title = ('GaussianBayesClassifier')

fig, ax = plt.subplots(figsize=(5, 5))
plt.subplots_adjust(wspace=0.4, hspace=0.4)

X0, X1 = X[:, 0], X[:, 1]
# 生成所有测试样本点
xx, yy = make_meshgrid(X0, X1)

# 显示测试样本的分类结果
plot_test_results(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
# 显示训练样本
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
plt.show()

2. 运行结果

二、登录https://archive-beta.ics.uci.edu/

可以查看提供的各类公共数据源,找到Breast Cancer Wisconsin (Original)数据并下载。

也可以直接输入网址:

https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/

下载wisconsin提供的乳腺肿瘤数breast-cancer-wisconsin.data(已经处理好的数据)和breast-cancer-wisconsin.names(对数据的说明,可以用写字体打开)

 在我上传的资源可以免费下载!!解压即可用【在本文置顶

 下载之后如下

三、使用sklearn机器学习开源库,使用贝叶斯分类器对breast-cancer-wisconsin.data进行分类。

1. Python代码

from sklearn import datasets
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error, classification_report
import pandas as pd
import numpy as np

# 构造列标签名字
column = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape',
          'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli',
          'Mitoses', 'Class']

# 读取数据
data = pd.read_csv(
    "https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
    names=column)

print(data)

# 缺失值进行处理
data = data.replace(to_replace='?', value=np.nan)
# 删除
data = data.dropna()

# 1-10列是特征值,最后一列10 代表11列目标值
x_train, x_test, y_train, y_test = train_test_split(data[column[1:10]], data[column[10]], test_size=0.25)

#
clf = GaussianNB()

clf.fit(x_train, y_train)

title = ('GaussianBayesClassifier')
y_predict = clf.predict(x_test)

# 首先用分类器自带的.score方法来对准确性进行打印:
print("准确率:", clf.score(x_test, y_test))

print("召回率:", classification_report(y_test, y_predict, labels=[2, 4], target_names=["良性", "恶性"]))

2. 运行截图

四、用java实现贝叶斯分类器算法,并对上述数据进行分类。

1. 流程图

图4-1 主程序流程图

图4-2 贝叶斯分类器流程图

图4-3 计算条件概率流程图

2. 数据结构

(1)用一个二维动态数组存储测试和训练数据。

(2)用一个哈希表存储分类对应的数据

<键:不同的分类,值:分类的数组>  便于计算后验概率。

3. 算法

(1)对breast-cancer-wisconsin.data进行分类:分训练集和测试集再进行一个分类处理:

(2)分类

(3)计算条件概率

(4)贝叶斯分类器

4. 测试结果

(1)当测试和训练比例1:1

(2)当训练集为70%,测试集为30%

五、心得体会

更加深刻地理解了课件上的例子,实现了一个朴素贝叶斯算法。在实现的过程发现,如果不用拉普拉斯修正,结果是不合理的。

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值