数据加载

  1. def load_data(path):
  2. data = np.loadtxt(path, dtype=float, delimiter=',', converters={4: iris_type})
  3. x, y = np.split(data, (4,), axis=1)
  4. # 未来便于可视化,取x的前两列特征
  5. x = x[:, :2]
  6. return x, y

构建模型

这里使用Pipeline直接将归一化和模型放在一起

  1. def build_model():
  2. gnb = Pipeline([
  3. ('sc', StandardScaler()),
  4. ('clf', GaussianNB())])
  5. return gnb

绘制结果函数

  1. def plot_data(x, y, model):
  2. '''
  3. :param x: 训练数据x
  4. :param y: 训练数据y
  5. :param mdoel: 模型
  6. :return:
  7. '''
  8. N, M = 500, 500 # 横纵各采样多少个值
  9. x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的范围
  10. x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的范围
  11. t1 = np.linspace(x1_min, x1_max, N)
  12. t2 = np.linspace(x2_min, x2_max, M)
  13. x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点
  14. x_test = np.stack((x1.flat, x2.flat), axis=1) # 测试点
  15. mpl.rcParams['font.sans-serif'] = [u'simHei']
  16. mpl.rcParams['axes.unicode_minus'] = False
  17. cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF'])
  18. cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
  19. y_hat = model.predict(x_test) # 预测值
  20. y_hat = y_hat.reshape(x1.shape) # 使之与输入的形状相同
  21. plt.figure(facecolor='w')
  22. plt.pcolormesh(x1, x2, y_hat, cmap=cm_light) # 预测值的显示
  23. plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(y), edgecolors='k', s=50, cmap=cm_dark) # 样本的显示
  24. plt.xlabel('length', fontsize=14)
  25. plt.ylabel('weidth', fontsize=14)
  26. plt.xlim(x1_min, x1_max)
  27. plt.ylim(x2_min, x2_max)
  28. plt.title('GaussianNB classification', fontsize=18)
  29. plt.grid(True)
  30. plt.show()

主函数

  1. if __name__ == '__main__':
  2. x, y = load_data('../data/iris.data')
  3. model = build_model()
  4. model.fit(x, y.ravel())
  5. plot_data(x, y, model)
  6. # 训练集上的预测结果
  7. y_hat = model.predict(x)
  8. y = y.reshape(-1)
  9. result = y_hat == y
  10. print(y_hat)
  11. print(result)
  12. acc = np.mean(result)
  13. print('准确度: %.2f%%' % (100 * acc))

分类结果

  1. 准确度: 78.00%

image.png

代码位置

完整代码位置:https://github.com/Knowledge-Precipitation-Tribe/Machine-Learning/blob/master/bayesian/iris-classification.py