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
- matplotlib绘制决策边界
- 数据挖掘-Iris数据集分析-决策边界_根据花瓣数据绘制(七)
- 决策边界 支持向量机
- 机器学习笔记之决策边界
- matplotlib-绘制精美图表
- matplotlib绘制简单图
- matplotlib 散点图绘制
- 使用matplotlib绘制图表
- matplotlib 绘制三维图
- matplotlib绘制基本图形
- matplotlib绘制K线图
- 使用matplotlib绘制散点图
- Matplotlib绘制树形图
- Matplotlib绘制甘特图
- matplotlib绘制条形图
- matplotlib 绘制条形图
- matplotlib 绘制动画
- Matplotlib绘制动画
- 加法原理与乘法原理
- 前端面试资源
- L1-017. 到底有多二
- 排列与组合
- 数据挖掘常用工具
- matplotlib绘制决策边界
- maven+Spring+SpringMvc+tomcat(原生非maven插件)整合
- 均线扣抵
- Catalan数应用
- Python eval 函数妙用
- 大型网站技术架构-5 万无一失:网站的高可用架构
- jvm学习----JDK命令行工具
- Java学习----day3——八大排序
- 杨辉三角与二项式定理