PyMC3实现贝叶斯神经网络

转自https://blog.csdn.net/jackxu8/article/details/71308390#commentBox

源地址https://docs.pymc.io/notebooks/bayesian_neural_network_advi.html

PyMC3中的贝叶斯深网络

生成数据

产生一个简单的线性不可分的二分类问题的模拟数据。

%matplotlib inline
import pymc3 as pm
import theano.tensor as T
import theano
import sklearn
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
from sklearn import datasets
from sklearn.preprocessing import scale
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_moons
/Users/xujie/.pyenv/versions/anaconda3-4.3.1/lib/python3.6/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20."This module will be removed in 0.20.", DeprecationWarning)
X, Y = make_moons(noise=0.2, random_state=0, n_samples=1000)
X = scale(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5)
fig, ax = plt.subplots()
ax.scatter(X[Y==0, 0], X[Y==0, 1], color='b',edgecolors='k',alpha=0.6, label='Class 0')
ax.scatter(X[Y==1, 0], X[Y==1, 1], color='r',edgecolors='k',alpha=0.6, label='Class 1')
sns.despine(); ax.legend()
ax.set(xlabel='X', ylabel='Y', title='Toy binary classification data set');

这里写图片描述

模型定义

神经网络的基础单元是感知器,和逻辑回归中的类似。将感知器并行排列然后堆叠起来获得隐层。这里使用2个隐层,每层有5个神经元。使用正态分布来正则化权重。

ann_input = theano.shared(X_train)
ann_output = theano.shared(Y_train)n_hidden = 5# Initialize random weights between each layer
init_1 = np.random.randn(X.shape[1], n_hidden)
init_2 = np.random.randn(n_hidden, n_hidden)
init_out = np.random.randn(n_hidden)with pm.Model() as neural_network:# Weights from input to hidden layerweights_in_1 = pm.Normal('w_in_1', 0, sd=1, shape=(X.shape[1], n_hidden), testval=init_1)# Weights from 1st to 2nd layerweights_1_2 = pm.Normal('w_1_2', 0, sd=1, shape=(n_hidden, n_hidden), testval=init_2)# Weights from hidden layer to outputweights_2_out = pm.Normal('w_2_out', 0, sd=1, shape=(n_hidden,), testval=init_out)# Build neural-network using tanh activation functionact_1 = T.tanh(T.dot(ann_input, weights_in_1))act_2 = T.tanh(T.dot(act_1, weights_1_2))act_out = T.nnet.sigmoid(T.dot(act_2, weights_2_out))# Binary classification -> Bernoulli likelihoodout = pm.Bernoulli('out', act_out,observed=ann_output)
/Users/xujie/.pyenv/versions/anaconda3-4.3.1/lib/python3.6/site-packages/theano/tensor/basic.py:2146: UserWarning: theano.tensor.round() changed its default from `half_away_from_zero` to `half_to_even` to have the same default as NumPy. Use the Theano flag `warn.round=False` to disable this warning."theano.tensor.round() changed its default from"

变分推理:缩放模型的复杂性

现在可以使用MCMC采样器(如NUTS)进行采样将获得不错的效果,但是这会非常缓慢。这里使用全新的ADVI变分推理算法,更加快速,对模型复杂度的适应性也更好。但是,这是均值近似,因此忽略后验中的相关性。

%%timewith neural_network:# Run ADVI which returns posterior means, standard deviations, and the evidence lower bound (ELBO)v_params = pm.variational.advi(n=50000)
Average ELBO = -151.63: 100%|██████████| 50000/50000 [00:13<00:00, 3790.27it/s]
Finished [100%]: Average ELBO = -136.89CPU times: user 15.5 s, sys: 695 ms, total: 16.1 s
Wall time: 18 s

画出目标函数(ELBO)可以看出随着优化的进行,效果主见提升。

plt.plot(v_params.elbo_vals);
plt.ylabel('ELBO');
plt.xlabel('iteration');

这里写图片描述

为了观察方便,这里使用sample_vp()对后验进行采样(这个函数只是对正态分布进行采样,因此和MCMC不一样)。

with neural_network:trace = pm.variational.sample_vp(v_params, draws=5000)
100%|██████████| 5000/5000 [00:00<00:00, 10687.44it/s]

这里完成了模型训练,然后使用posterior predictive check (PPC)对排除在外的数据点进行预测。使用sample_ppc()从后验中生成新数据(从变分估计中采样)。

# Replace shared variables with testing set
ann_input.set_value(X_test)
ann_output.set_value(Y_test)# Creater posterior predictive samples
ppc = pm.sample_ppc(trace, model=neural_network, samples=500)# Use probability of > 0.5 to assume prediction of class 1
pred = ppc['out'].mean(axis=0) > 0.5
100%|██████████| 500/500 [00:03<00:00, 139.67it/s]
fig, ax = plt.subplots()
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1], color='b',edgecolors='k',alpha=0.6)
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r',edgecolors='k',alpha=0.6)
sns.despine()
ax.set(title='Predicted labels in testing set', xlabel='X', ylabel='Y');

这里写图片描述

print('Accuracy = {}%'.format((Y_test == pred).mean() * 100))
Accuracy = 95.6%

分类器分析

为了分析这个分类器的结果,多整个输入空间上的网络输出做出评估。

grid = np.mgrid[-3:3:100j,-3:3:100j]
grid_2d = grid.reshape(2, -1).T
dummy_out = np.ones(grid.shape[1], dtype=np.int8)
ann_input.set_value(grid_2d)
ann_output.set_value(dummy_out)# 对后验估计进行采样
ppc = pm.sample_ppc(trace, model=neural_network, samples=500)
100%|██████████| 500/500 [00:04<00:00, 101.43it/s]

绘制预测平面如下

cmap = sns.diverging_palette(250, 12, s=85, l=25, as_cmap=True)
fig, ax = plt.subplots(figsize=(10, 6))
contour = ax.contourf(*grid, ppc['out'].mean(axis=0).reshape(100, 100), cmap=cmap)
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1], color='b', edgecolors='k',alpha=0.6)
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r', edgecolors='k',alpha=0.6)
cbar = plt.colorbar(contour, ax=ax)
_ = ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel='X', ylabel='Y');
cbar.ax.set_ylabel('Posterior predictive mean probability of class label = 0');

这里写图片描述

预测中的不确定性

目前未知,这些工作都可以在非贝叶斯神经网络上完成。每个类别的后验均值可以用极大似然估计给出。然而,贝叶斯神经网络还可以给出后验估计的标准差,来评价后验中的不确定性。

cmap = sns.cubehelix_palette(light=1, as_cmap=True)
fig, ax = plt.subplots(figsize=(10, 6))
contour = ax.contourf(*grid, ppc['out'].std(axis=0).reshape(100, 100), cmap=cmap)
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1], color='b', edgecolors='k',alpha=0.6)
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r', edgecolors='k',alpha=0.6)
cbar = plt.colorbar(contour, ax=ax)
_ = ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel='X', ylabel='Y');
cbar.ax.set_ylabel('Uncertainty (posterior predictive standard deviation)');

这里写图片描述

可以看出,在越接近决策边界的地方,预测的不确定性越高。而预测结果与不确定性相关联分析是许多应用领域的重要因素,比如医学检测。为了更高的准确性,可以让模型在不确定性高的地方进行更多的采样。

微批AVDI(Mini-batch AVDI):可扩展数据大小

此前,都是在所有数据上一次性训练模型。这样的训练方式对于数据集的大小不可扩展。然而可以在一小批数据上(mini-batch of data)进行训练(随机梯度下降),可以避免局部最小并获得更快的收敛。

from six.moves import zip# Set back to original data to retrain
ann_input.set_value(X_train)
ann_output.set_value(Y_train)# Tensors and RV that will be using mini-batches
minibatch_tensors = [ann_input, ann_output]
minibatch_RVs = [out]# Generator that returns mini-batches in each iteration
def create_minibatch(data):while True:# Return random data samples of set size 100 each iterationixs = np.random.randint(len(data), size=50)yield data[ixs]minibatches = zip(create_minibatch(X_train),create_minibatch(Y_train),
)total_size = len(Y_train)
%%timewith neural_network:# Run advi_minibatchv_params = pm.variational.advi_minibatch(n=50000, minibatch_tensors=minibatch_tensors, minibatch_RVs=minibatch_RVs, minibatches=minibatches, total_size=total_size, learning_rate=1e-2, epsilon=1.0)
Average ELBO = -123.12: 100%|██████████| 50000/50000 [00:16<00:00, 3043.69it/s]
Finished minibatch ADVI: ELBO = -121.76CPU times: user 20.5 s, sys: 371 ms, total: 20.9 s
Wall time: 23.9 s
with neural_network:    trace = pm.variational.sample_vp(v_params, draws=5000)
100%|██████████| 5000/5000 [00:00<00:00, 9914.64it/s]

mini-batch方式的运行时间更长,但是收敛更快。

pm.traceplot(trace);

这里写图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/491406.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Dynamics CRM 开启图表的3D效果展示

CRM中的图表在我们的业务场景中用的很多&#xff0c;用户可以根据自己的实际需求来构建图表查看数据。我们平时看到的图表都是平面的&#xff0c;像下图中的这种&#xff0c;那有没有一种方式可以让展示3D效果看起来更立体呢&#xff0c;答案是可以的。 这里就以上面的图表为例…

OpenCV初体验

OpenCV提供了一些实用工具来读取从视频流到摄像机画面的各种各样的图像格式&#xff0c;这些工具都是HighGUI的一部分。下面几个小例子可以让初学者提前体验一下OpenCV的功能。 1. 打开一张图像并且将其显示在屏幕上 #include "stdafx.h" #include <opencv2/ope…

“CRISPR婴儿”计划疯狂重启 顶级科学家们表示无力阻止

来源&#xff1a; 生物通新的“CRISPR婴儿”计划启动&#xff0c;顶级科学人士感到震惊&#xff0c;却表示他们无力阻止它6月10日&#xff0c;俄罗斯分子生物学家Denis Rebrikov表示计划开展基因编辑婴儿实验&#xff0c;并公开了他将跨越“红线”的研究计划。两位有影响力的学…

写一些脚本的心得总结系列第3篇------同步数据到其他表

3.同步数据到其他表的。 这种又分插入和更新字段两种情况&#xff0c;除了sql方面的逻辑外&#xff0c;要考虑记录执行sql和变化前后数据记录。总是要做最坏的打算&#xff0c;一旦更新错了还能回滚数据。 比如在更新之前先记录被更新的数据记录到某表&#xff08;新建表&#…

PyMC3和Lasagne构建神经网络(ANN)和卷积神经网络(CNN)

转自http://www.sohu.com/a/162460147_505915 源地址https://twiecki.io/blog/2016/07/05/bayesian-deep-learning/ 今天&#xff0c;我们将使用Lasagne构建一个更有趣的模型&#xff0c;这是一个灵活的Theano图书馆&#xff0c;用于构建各种类型的神经网络。你可能知道&…

OpenCV高斯滤波GaussianBlur

图像处理中&#xff0c;常用的滤波算法有均值滤波、中值滤波以及高斯滤波等。 三种滤波器的对比滤波器种类基本原理特点均值滤波使用模板内所有像素的平均值代替模板中心像素灰度值易收到噪声的干扰&#xff0c;不能完全消除噪声&#xff0c;只能相对减弱噪声中值滤波计算模板内…

(附视频) | AI奠基人、美国AI科学家特伦斯谈深度学习​

来源&#xff1a;笑看国际风云特伦斯 谢诺夫斯基&#xff08;Terrence Sejnowski&#xff09;&#xff1a;世界十大人工智能科学家之一&#xff0c;还是美国仅3位在世的‘四院院士’之一&#xff0c;同时兼任全球人工智能顶级会议NIPS基金会主席。1989年&#xff0c;特伦斯加入…

Chapter 3.GDI/DirectDraw Internal Data Structures

说明&#xff0c;在这里决定跳过第二章&#xff0c;实在是因为里面涉及的内容太理论&#xff0c;对我而言又太艰深 3.1 HANDLES AND OBJECT-ORIRNTED PROGRAMMING In normal object-oriented programming practice,information hiding is achieved by declaring certain member…

OpenCV图像金字塔

图像金字塔是图像多尺度表达的一种&#xff0c;是一种以多分辨率来解释图像的有效但概念简单的结构。一幅图像的金字塔是一系列以金字塔形状排列的分辨率逐步降低&#xff0c;且来源于同一张原始图的图像集合。其通过梯次向下采样获得&#xff0c;直到达到某个终止条件才停止采…

带你深入理解图灵机--天才所在的时代

来源&#xff1a;人机与认知实验室这几年由于区块链的大热&#xff0c;以太坊独特的solidity语言实现智能合约功能&#xff0c;图灵完备这个词走进大家的视线。没有计算机专业知识的同学其实很难理解这个词的意思&#xff0c;其实计算机专业的同学都没有深入理解图灵机&#xf…

用PyMC3进行贝叶斯统计分析(代码+实例)

问题类型1&#xff1a;参数估计 真实值是否等于X&#xff1f; 给出数据&#xff0c;对于参数&#xff0c;可能的值的概率分布是多少&#xff1f; 例子1&#xff1a;抛硬币问题 硬币扔了n次&#xff0c;正面朝上是h次。 参数问题 想知道 p 的可能性。给定 n 扔的次数和 h …

2015总结及2016计划

2015计划完成情况&#xff1a; 1.网站建起来&#xff08;未完成&#xff09; 2.发布一款游戏&#xff08;cocos2dx或u3d&#xff09;&#xff08;未完成&#xff09; 3.稳定一年工作&#xff08;完成&#xff09; 4.学习C或C&#xff0c;能够使用其中一种进行windows编程&#…

华为: 即将发布5G+VR的颠覆式智能眼镜

来源&#xff1a;VR每日必看6月27日MWC19上海期间&#xff0c;华为手机业务总裁何刚在全球终端峰会发表演讲&#xff0c;提及华为终端在5G时代的全场景战略是“18N”。“1”就是华为手机&#xff0c;“8”则囊括了TV、平板、PC、耳机、车机、手表、眼镜、音响八项终端产品&…

OpenCV的数据类型——基础数据类型

OpenCV有很多数据类型&#xff0c;从组织结构的角度来看&#xff0c;OpenCV的基础类型类型主要分为三类。第一类是直接从C原语中继承的基础数据类型&#xff1b;第二类是辅助对象&#xff1b;第三类是大型数据类型。本文主要介绍OpenCV的基础数据类型。 目录 Point类 Scalar…

Process finished with exit code -1073741819 (0xC0000005)

运行TensorFlow出现如下错误&#xff0c;尝试了很多网上的方法都不行&#xff0c;最后把代码中的中文路径改为英文后就解决了

LeetCode - Partition List

题目&#xff1a; Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1-…

Cell:重大突破!三位学术大咖,打造全新“DNA显微镜”

来源&#xff1a;中国生物技术网传统上&#xff0c;科学家们使用光、X射线和电子来观察组织和细胞的内部。如今&#xff0c;科学家们能够在整个大脑中追踪线状的神经纤维&#xff0c;甚至可以观察活的小鼠胚胎如何产生原始心脏中的跳动细胞。但是这些显微镜无法看到的是&#x…

OpenCV的数据类型——辅助对象

在上一篇文章中&#xff0c;主要介绍了OpenCV的基础数据类型。接下来在本篇文章中将主要对OpenCV的辅助对象进行介绍。 cv::TermCriteria类 在很多算法中都存在着循环嵌套&#xff0c;只有满足终止条件时才会退出。通常情况下&#xff0c;终止条件的形式要么是达到允许的有限…

概率密度函数某一点的意义

在连续型随机变量的概率密度函数中&#xff0c;某一点的值不等于该点的概率值&#xff0c;就像不能计算汽车在某一点的速度&#xff0c;因为速度是距离除以时间&#xff0c;对某一点来说不存在距离的概念。如果要计算某一点x的概率的话&#xff0c;就要对x取邻域&#xff08;无…

eclipse中monokai插件的安装

eclipse中monokai插件的安装转载于:https://www.cnblogs.com/zhujiabin/p/5099675.html