画出决策边界线--plot_2d_separator.py源代码【来自python机器学习基础教程】

  1 import numpy as np
  2 import matplotlib.pyplot as plt
  3 from .plot_helpers import cm2, cm3, discrete_scatter
  4
  5 def _call_classifier_chunked(classifier_pred_or_decide, X):
  6 # The chunk_size is used to chunk the large arrays to work with x86
  7 # memory models that are restricted to < 2 GB in memory allocation. The
  8 # chunk_size value used here is based on a measurement with the
  9 # MLPClassifier using the following parameters:
 10 # MLPClassifier(solver=‘lbfgs‘, random_state=0,
 11 # hidden_layer_sizes=[1000,1000,1000])
 12 # by reducing the value it is possible to trade in time for memory.
 13 # It is possible to chunk the array as the calculations are independent of
 14 # each other.
 15 # Note: an intermittent version made a distinction between
 16 # 32- and 64 bit architectures avoiding the chunking. Testing revealed
 17 # that even on 64 bit architectures the chunking increases the
 18 # performance by a factor of 3-5, largely due to the avoidance of memory
 19 # swapping.
 20 chunk_size = 10000
 21
 22 # We use a list to collect all result chunks
 23 Y_result_chunks = []
 24
 25 # Call the classifier in chunks.
 26 for x_chunk in np.array_split(X, np.arange(chunk_size, X.shape[0],
 27 chunk_size, dtype=np.int32),
 28 axis=0):
 29 Y_result_chunks.append(classifier_pred_or_decide(x_chunk))
 30
 31 return np.concatenate(Y_result_chunks)
 32
 33
 34 def plot_2d_classification(classifier, X, fill=False, ax=None, eps=None,
 35 alpha=1, cm=cm3):
 36 # multiclass
 37 if eps is None:
 38 eps = X.std() / 2.
 39
 40 if ax is None:
 41 ax = plt.gca()
 42
 43 x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
 44 y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
 45 xx = np.linspace(x_min, x_max, 1000)
 46 yy = np.linspace(y_min, y_max, 1000)
 47
 48 X1, X2 = np.meshgrid(xx, yy)
 49 X_grid = np.c_[X1.ravel(), X2.ravel()]
 50 decision_values = classifier.predict(X_grid)
 51 ax.imshow(decision_values.reshape(X1.shape), extent=(x_min, x_max,
 52 y_min, y_max),
 53 aspect=‘auto‘, origin=‘lower‘, alpha=alpha, cmap=cm)
 54 ax.set_xlim(x_min, x_max)
 55 ax.set_ylim(y_min, y_max)
 56 ax.set_xticks(())
 57 ax.set_yticks(())
 58
 59
 60 def plot_2d_scores(classifier, X, ax=None, eps=None, alpha=1, cm="viridis",
 61 function=None):
 62 # binary with fill
 63 if eps is None:
 64 eps = X.std() / 2.
 65
 66 if ax is None:
 67 ax = plt.gca()
 68
 69 x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
 70 y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
 71 xx = np.linspace(x_min, x_max, 100)
 72 yy = np.linspace(y_min, y_max, 100)
 73
 74 X1, X2 = np.meshgrid(xx, yy)
 75 X_grid = np.c_[X1.ravel(), X2.ravel()]
 76 if function is None:
 77 function = getattr(classifier, "decision_function",
 78 getattr(classifier, "predict_proba"))
 79 else:
 80 function = getattr(classifier, function)
 81 decision_values = function(X_grid)
 82 if decision_values.ndim > 1 and decision_values.shape[1] > 1:
 83 # predict_proba
 84 decision_values = decision_values[:, 1]
 85 grr = ax.imshow(decision_values.reshape(X1.shape),
 86 extent=(x_min, x_max, y_min, y_max), aspect=‘auto‘,
 87 origin=‘lower‘, alpha=alpha, cmap=cm)
 88
 89 ax.set_xlim(x_min, x_max)
 90 ax.set_ylim(y_min, y_max)
 91 ax.set_xticks(())
 92 ax.set_yticks(())
 93 return grr
 94
 95
 96 def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None, alpha=1,
 97 cm=cm2, linewidth=None, threshold=None,
 98 linestyle="solid"):
 99 # binary?
100 if eps is None:
101 eps = X.std() / 2.
102
103 if ax is None:
104 ax = plt.gca()
105
106 x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
107 y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
108 xx = np.linspace(x_min, x_max, 1000)
109 yy = np.linspace(y_min, y_max, 1000)
110
111 X1, X2 = np.meshgrid(xx, yy)
112 X_grid = np.c_[X1.ravel(), X2.ravel()]
113 if hasattr(classifier, "decision_function"):
114 decision_values = _call_classifier_chunked(classifier.decision_function,
115 X_grid)
116 levels = [0] if threshold is None else [threshold]
117 fill_levels = [decision_values.min()] + levels + [
118 decision_values.max()]
119 else:
120 # no decision_function
121 decision_values = _call_classifier_chunked(classifier.predict_proba,
122 X_grid)[:, 1]
123 levels = [.5] if threshold is None else [threshold]
124 fill_levels = [0] + levels + [1]
125 if fill:
126 ax.contourf(X1, X2, decision_values.reshape(X1.shape),
127 levels=fill_levels, alpha=alpha, cmap=cm)
128 else:
129 ax.contour(X1, X2, decision_values.reshape(X1.shape), levels=levels,
130 colors="black", alpha=alpha, linewidths=linewidth,
131 linestyles=linestyle, zorder=5)
132
133 ax.set_xlim(x_min, x_max)
134 ax.set_ylim(y_min, y_max)
135 ax.set_xticks(())
136 ax.set_yticks(())
137
138
139 if __name__ == ‘__main__‘:
140 from sklearn.datasets import make_blobs
141 from sklearn.linear_model import LogisticRegression
142 X, y = make_blobs(centers=2, random_state=42)
143 clf = LogisticRegression(solver=‘lbfgs‘).fit(X, y)
144 plot_2d_separator(clf, X, fill=True)
145 discrete_scatter(X[:, 0], X[:, 1], y)
146 plt.show()

原文地址:https://www.cnblogs.com/aaronhoo/p/10146934.html

时间: 2024-08-02 03:54:43

画出决策边界线--plot_2d_separator.py源代码【来自python机器学习基础教程】的相关文章

《Python机器学习基础教程》高清中文版PDF+高清英文版PDF+源代码

资源链接:https://pan.baidu.com/s/1sa64QTsQ7A5WlZxMuNmYHg<Python机器学习基础教程>高清中文版PDF+高清英文版PDF+源代码高清中文版PDF,306页,带目录和书签,文字能够复制粘贴:高清英文版PDF,392页,带目录和书签,彩色配图,文字能够复制粘贴:中英文两版可以对比学习.配套源代码:经典书籍,讲解详细:其中,高清中文版如图: 原文地址:http://blog.51cto.com/14063572/2317004

分享《Python数据分析基础教程:NumPy学习指南(第2版)》高清中文PDF+英文PDF+源代码

下载:https://pan.baidu.com/s/1YSD97Gd3gmmPmNkvuG0eew更多资料分享:http://blog.51cto.com/3215120 <Python数据分析基础教程:NumPy学习指南(第2版)>高清中文PDF+高清英文PDF+源代码 高清中文版PDF,249页,带目录和书签,文字能够复制粘贴:高清英文版PDF,310页,带目录和书签,文字能够复制粘贴:中英文两版可以对比学习.配套源代码:经典书籍,讲解详细:其中高清中文版如图: 原文地址:http://

[转]html5 Canvas画图教程(9)—canvas中画出矩形和圆形

本文讲一下在canvas中画出矩形和圆形的办法,他们属于基础图形.当然,基础图形本来不止他们,但在canvas中,只有画矩形与圆形不需要用其他方法模拟. canvas画矩形 1,fillRect与strokeRect fillRect可以直接填充出一个矩形,填充样式是你当前设置的样式:同理strokeRect就是直接描边一个矩形 他们的参数是一致的,依次是(起点x坐标,起点y,矩形的宽,矩形的高).这里的起点,注意,是指矩形的左上角那个点. 我们通常用他们来做简单的事,他们也只能做简单的事.为什

架构师必备技能:教你画出一张合格的技术架构图

当我们想用一张或几张图来描述我们的系统时,是不是经常遇到以下情况: 对着画布无从下手.删了又来? 如何用一张图描述我的系统,并且让产品.运营.开发都能看明白? 画了一半的图还不清楚受众是谁? 画出来的图到底是产品图功能图还是技术图又或是大杂烩? 图上的框框有点少是不是要找点儿框框加进来? 布局怎么画都不满意…… 如果有同样的困惑,本文将介绍一种画图的方法论,来让架构图更清晰. 先厘清一些基础概念 1.什么是架构? 架构就是对系统中的实体以及实体之间的关系所进行的抽象描述,是一系列的决策. 架构是

如何画出一张合格的技术架构图?

当我们想用一张或几张图来描述我们的系统时,是不是经常遇到以下情况: 对着画布无从下手.删了又来? 如何用一张图描述我的系统,并且让产品.运营.开发都能看明白? 画了一半的图还不清楚受众是谁? 画出来的图到底是产品图功能图还是技术图又或是大杂烩? 图上的框框有点少是不是要找点儿框框加进来? 布局怎么画都不满意…… 如果有同样的困惑,本文将介绍一种画图的方法论,来让架构图更清晰. 先厘清一些基础概念 1.什么是架构? 架构就是对系统中的实体以及实体之间的关系所进行的抽象描述,是一系列的决策. 架构是

OpenCv 使用vector&lt;Point&gt;画出轮廓外接矩形

Hai 1 IplImage* printrect(IplImage *contourim) 2 { 3 4 IplImage *rectim=cvCreateImage(cvGetSize(contourim), IPL_DEPTH_8U, 3); 5 int flag=1; 6 vector<Point> points; 7 for(;contourSeq!=NULL;contourSeq=contourSeq->h_next) 8 { 9 10 11 for(int i=0;i&l

如何在论文中画出漂亮的插图?

知乎用户的回答(1259票)]: 强烈推荐 Python 的绘图模块 matplotlib: python plotting .画出来的图真的是高端大气上档次,低调奢华有内涵~ 适用于从 2D 到 3D,从标量到矢量的各种绘图.能够保存成从 eps, pdf 到 svg, png, jpg 的多种格式.并且 Matplotlib 的绘图函数基本上都与 Matlab 的绘图函数名字都差不多,迁移的学习成本比较低.开源免费.如图所示(题目描述中的图在最后): (以下图片均引用自 Thumbnail

列名作为分类值时如何画出统计图

一般来说,在报表中设计的统计图要用到两个变量值,一个是分类值,一般是统计中的横轴,还有一个就是系列值,相应的就是统计图中的纵轴.绝大多数情况下,分类值与系列值都是来源于表中的数据,也就是说,统计图是基于数据库表中的记录来设计器的,例如下面这个统计图: 一般会来自于这样的数据: 但是,有时会遇到下面这样的数据: 显然,如果还需要做出前面的统计图,那么分类值和系列值就需要使用数据库中的列名也就是字段名了.说实话,小编以前看到这种数据除了摇头,也就是想办法重新设计一张数据表,把所有列名存入一个字段,然

Python3 Tkinter基础 Canvas bind 绑定左键 鼠标左键点击时,在当前位置画出一个椭圆形

镇场诗: 清心感悟智慧语,不着世间名与利.学水处下纳百川,舍尽贡高我慢意. 学有小成返哺根,愿铸一良心博客.诚心于此写经验,愿见文者得启发.------------------------------------------ code: from tkinter import * root=Tk() w=Canvas(root,width=200,height=200,background='white') w.pack() def paint(event): #event.x 鼠标左键的横坐标