import numpy as np
import matplotlib.pyplot as plt
from .plot_helpers import cm2, cm3, discrete_scatter def _call_classifier_chunked(classifier_pred_or_decide, X):
# The chunk_size is used to chunk the large arrays to work with x86
# memory models that are restricted to < 2 GB in memory allocation. The
# chunk_size value used here is based on a measurement with the
# MLPClassifier using the following parameters:
# MLPClassifier(solver='lbfgs', random_state=0,
# hidden_layer_sizes=[1000,1000,1000])
# by reducing the value it is possible to trade in time for memory.
# It is possible to chunk the array as the calculations are independent of
# each other.
# Note: an intermittent version made a distinction between
# 32- and 64 bit architectures avoiding the chunking. Testing revealed
# that even on 64 bit architectures the chunking increases the
# performance by a factor of 3-5, largely due to the avoidance of memory
# swapping.
chunk_size = 10000 # We use a list to collect all result chunks
Y_result_chunks = [] # Call the classifier in chunks.
for x_chunk in np.array_split(X, np.arange(chunk_size, X.shape[0],
chunk_size, dtype=np.int32),
axis=0):
Y_result_chunks.append(classifier_pred_or_decide(x_chunk)) return np.concatenate(Y_result_chunks) def plot_2d_classification(classifier, X, fill=False, ax=None, eps=None,
alpha=1, cm=cm3):
# multiclass
if eps is None:
eps = X.std() / 2. if ax is None:
ax = plt.gca() x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
xx = np.linspace(x_min, x_max, 1000)
yy = np.linspace(y_min, y_max, 1000) X1, X2 = np.meshgrid(xx, yy)
X_grid = np.c_[X1.ravel(), X2.ravel()]
decision_values = classifier.predict(X_grid)
ax.imshow(decision_values.reshape(X1.shape), extent=(x_min, x_max,
y_min, y_max),
aspect='auto', origin='lower', alpha=alpha, cmap=cm)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(()) def plot_2d_scores(classifier, X, ax=None, eps=None, alpha=1, cm="viridis",
function=None):
# binary with fill
if eps is None:
eps = X.std() / 2. if ax is None:
ax = plt.gca() x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
xx = np.linspace(x_min, x_max, 100)
yy = np.linspace(y_min, y_max, 100) X1, X2 = np.meshgrid(xx, yy)
X_grid = np.c_[X1.ravel(), X2.ravel()]
if function is None:
function = getattr(classifier, "decision_function",
getattr(classifier, "predict_proba"))
else:
function = getattr(classifier, function)
decision_values = function(X_grid)
if decision_values.ndim > 1 and decision_values.shape[1] > 1:
# predict_proba
decision_values = decision_values[:, 1]
grr = ax.imshow(decision_values.reshape(X1.shape),
extent=(x_min, x_max, y_min, y_max), aspect='auto',
origin='lower', alpha=alpha, cmap=cm) ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(())
return grr def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None, alpha=1,
cm=cm2, linewidth=None, threshold=None,
linestyle="solid"):
# binary?
if eps is None:
eps = X.std() / 2. if ax is None:
ax = plt.gca() x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
xx = np.linspace(x_min, x_max, 1000)
yy = np.linspace(y_min, y_max, 1000) X1, X2 = np.meshgrid(xx, yy)
X_grid = np.c_[X1.ravel(), X2.ravel()]
if hasattr(classifier, "decision_function"):
decision_values = _call_classifier_chunked(classifier.decision_function,
X_grid)
levels = [0] if threshold is None else [threshold]
fill_levels = [decision_values.min()] + levels + [
decision_values.max()]
else:
# no decision_function
decision_values = _call_classifier_chunked(classifier.predict_proba,
X_grid)[:, 1]
levels = [.5] if threshold is None else [threshold]
fill_levels = [0] + levels + [1]
if fill:
ax.contourf(X1, X2, decision_values.reshape(X1.shape),
levels=fill_levels, alpha=alpha, cmap=cm)
else:
ax.contour(X1, X2, decision_values.reshape(X1.shape), levels=levels,
colors="black", alpha=alpha, linewidths=linewidth,
linestyles=linestyle, zorder=5) ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(()) if __name__ == '__main__':
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression
X, y = make_blobs(centers=2, random_state=42)
clf = LogisticRegression(solver='lbfgs').fit(X, y)
plot_2d_separator(clf, X, fill=True)
discrete_scatter(X[:, 0], X[:, 1], y)
plt.show()

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

  1. WPF 如何画出1像素的线

    如何有人告诉你,请你画出1像素的线,是不是觉得很简单,实际上在 WPF 上还是比较难的. 本文告诉大家,如何让画出的线不模糊 画出线的第一个方法,创建一个 Canvas ,添加一个线 界面代码 < ...

  2. python运用turtle 画出汉诺塔搬运过程

    python运用turtle 画出汉诺塔搬运过程 1.打开 IDLE 点击File-New File 新建立一个py文件 2.向py文件中输入如下代码 import turtle class Stac ...

  3. caffe 中 plot accuracy和loss, 并画出网络结构图

    plot accuracy + loss 详情可见:http://www.2cto.com/kf/201612/575739.html 1. caffe保存训练输出到log 并绘制accuracy l ...

  4. 如何用DOM 元素就能画出国宝熊猫

    效果预览 在线演示 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/odKrpy 可交互视频教 ...

  5. scikit-learn机器学习(四)使用决策树做分类,并画出决策树,随机森林对比

    数据来自 UCI 数据集 匹马印第安人糖尿病数据集 载入数据 # -*- coding: utf-8 -*- import pandas as pd import matplotlib matplot ...

  6. 前端每日实战:35# 视频演示如何把 CSS 径向渐变用得出神入化,只用一个 DOM 元素就能画出国宝熊猫

    效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/odKrpy 可交互视频教程 此视频 ...

  7. H5坦克大战之【画出坦克】

    今天是个特殊的日子,圣诞节,也是周末,在这里先祝大家圣诞快乐!喜庆的日子,我们可以稍微放松一下,扯一扯昨天雷霆对战凯尔特人的比赛,这场比赛大威少又双叒叕拿下三双,而且是一个45+11+11的超级三双, ...

  8. 像画笔一样慢慢画出Path的三种方法(补充第四种)

    今天大家在群里大家非常热闹的讨论像画笔一样慢慢画出Path的这种效果该如何实现. 北京-LGL 博客号@ligl007发起了这个话题.然后各路高手踊跃发表意见.最后雷叔 上海-雷蒙 博客号@雷蒙之星 ...

  9. 用css画出三角形

    看到有面试题里会有问到如何用css画出三角形 众所周知好多图形都可以拆分成三角形,所以说会了画三角形就可以画出很多有意思的形状 画出三角形的原理是调整border(边框)的四个方向的宽度,线条样式以及 ...

随机推荐

  1. 使用django开发论坛输出调试信息时附加远程客户端IP地址!

    前言 最近使用django开发了个匿名社区(哈士奇社区 4nmb.com),但是有个问题一直困扰我半天,就是如何在django调试信息上输出远程客户端的真实IP地址,在网上找了很多资料也没见人遇到过, ...

  2. ASP.NET Core3.x 基础—注册服务(2)

    这篇文章介绍在ASP.NET Core中注册一下自己的服务. 首先创建一个Services文件夹.在文件夹里面创建一个接口 IClock,以及两个类ChinaClock.UtcClock.这两个类分别 ...

  3. spring源码阅读笔记10:bean生命周期

    前面的文章主要集中在分析Spring IOC容器部分的原理,这部分的核心逻辑是和bean创建及管理相关,对于单例bean的管理,从创建好到缓存起来再到销毁,其是有一个完整的生命周期,并且Spring也 ...

  4. 学习Vue第四节,v-model和双向数据绑定

    Vue指令之v-model和双向数据绑定 <!DOCTYPE html> <html> <head> <meta charset="utf-8&qu ...

  5. Vue实现靠边悬浮球(PC端)

    我想把退出登录的按钮做成一个悬浮球的样子,带动画的那种. 实现是这个样子: 手边没有球形图.随便找一个,功能这里演示的为单机悬浮球注销登录 嗯,具体代码: <div :class="[ ...

  6. spring学习笔记(七)HttpMessageConverter

    spring学习笔记(七)HttpMessageConverter 1. HttpMessageConverter的加载 2. 从StringMessageConverter探究消息转换器的原理 1. ...

  7. NEON的比较是把所有的bit都设置为1

    NEON中的比较指令,如果结果为true,是把所有的bit都设置为1,而不是设置为1. ushort data1[4] = {129,0,136,255}; uint16x4_t v0 = vld1_ ...

  8. 【Hadoop离线基础总结】MapReduce增强(下)

    MapReduce增强(下) MapTask运行机制详解以及MapTask的并行度 MapTask运行流程 第一步:读取数据组件InputFormat(默认TextInputFormat)会通过get ...

  9. 海外网站如何通过代理IP进行采集?

    海外网站如何通过代理IP进行采集? 我们在做爬虫的时候,经常会遇到这种情况,爬虫最初运行的时候,数据是可以正常获取的,一切看起来都那么的美好,然而,不一会儿,就可能会出现403 Forbidden , ...

  10. C# 数据操作系列 - 4. 自己实现一个ORM

    0. 前言 在之前的几篇内容中,我们了解了如何通过ADO.NET 访问数据库,如何修改.新增数据.如何通过DataSet和DataAdapter获取数据,我们将在这一篇试试自己实现一个简单的ORM框架 ...