赞
踩
目录
一、使用Python开发工具,运行对iris数据进行分类的例子程序NaiveBayes.py,熟悉sklearn机器实习开源库。
二、登录https://archive-beta.ics.uci.edu/
三、使用sklearn机器学习开源库,使用贝叶斯分类器对breast-cancer-wisconsin.data进行分类。
- 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()
可以查看提供的各类公共数据源,找到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(对数据的说明,可以用写字体打开)
在我上传的资源可以免费下载!!解压即可用【在本文置顶】
下载之后如下
- 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=["良性", "恶性"]))
图4-1 主程序流程图
图4-2 贝叶斯分类器流程图
图4-3 计算条件概率流程图
(1)用一个二维动态数组存储测试和训练数据。
(2)用一个哈希表存储分类对应的数据
<键:不同的分类,值:分类的数组> 便于计算后验概率。
(1)对breast-cancer-wisconsin.data进行分类:分训练集和测试集再进行一个分类处理:
(2)分类
(3)计算条件概率
(4)贝叶斯分类器
(1)当测试和训练比例1:1
(2)当训练集为70%,测试集为30%
更加深刻地理解了课件上的例子,实现了一个朴素贝叶斯算法。在实现的过程发现,如果不用拉普拉斯修正,结果是不合理的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。