matplotlib绘制决策边界

来源:互联网 发布:国际象棋ai算法 编辑:程序博客网 时间:2024/05/22 01:31

在进行分类模型的可视化时,我们希望能够绘制分类模型的决策边界。绘制决策边界的直观思路是在空间内足够密集地取点,使用分类模型针对这些点进行预测,并将这些点的预测结果可视化。

以下是代码实例:
首先进行预测,这里使用的数据集是iris数据集,为了便于可视化,只使用前两个特征。

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.datasets import load_iris from sklearn.svm import LinearSVCiris = load_iris()# take the first two featuresX = iris.data[:, :2]y = iris.target# train the modelclf = LinearSVC().fit(X, y)# get the range of the picturex_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1# get the points to predict # len(np.arange(x_min, x_max, 0.02)) = 280# len(np.arange(y_min, y_max, 0.02)) = 220# xx.shape = (220L, 280L)# yy.shape = (220L, 280L)xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),                     np.arange(y_min, y_max, 0.02))# predict the pointZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])# Z.shape = (220L, 280L)Z = Z.reshape(xx.shape)

用到的部分函数
(1)np.meshgrid
简单来说就是在空间上取点,根据例子容易理解

x = [1,2,3]y = [4,5]xx, yy = np.meshgrid(x, y)print xx#[[1 2 3]# [1 2 3]]print yy#[[4 4 4]# [5 5 5]]

(2)ravel
简单来说就是降维,根据例子容易理解

print xx#[[1 2 3]# [1 2 3]]print xx.ravel()#[1 2 3 1 2 3]

(3)np.c_
简单来说就是按照特定轴整合,根据例子容易理解

print xx.ravel()#[1 2 3 1 2 3]print yy.ravel()#[4 4 4 5 5 5] print np.c_[xx.ravel(), yy.ravel()]#[[1 4]# [2 4]# [3 4]# [1 5]# [2 5]# [3 5]]

然后绘制图形,需要用到metplotlib.pyplot的两个函数,contourf绘制平面,scatter绘制散点,cmap用于指定颜色。

plt.figure()# red yellow blueplt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu)plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdYlBu)# red yellow green#plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlGn)#plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdYlGn)# red yellow blue#from matplotlib.colors import ListedColormap#plt.contourf(xx, yy, Z, cmap=ListedColormap(['r', 'y', 'b']))#plt.scatter(X[:, 0], X[:, 1], c=y, cmap=ListedColormap(['r', 'y', 'b']))plt.xlabel('Sepal Length')plt.ylabel('Sepal Width')plt.xlim(x_min, x_max)plt.ylim(y_min, y_max)plt.title('SVC with linear kernel')plt.show()

这里写图片描述

0 0
原创粉丝点击