TensorFlow团队:TensorFlow Probability的简单介绍

文章来源:ATYUN AI平台 

在2018年TensorFlow开发者峰会上,我们(TensorFlow团队)宣布发布TensorFlow Probability:一种使机器学习研究人员及相关从业人员可以快速可靠地利用最先进硬件构建复杂模型的概率编程工具箱。TensorFlow Probability适用的情况包括:

  • 你想建立一个数据生成模型,推理其隐藏的过程。
  • 你需要量化预测中的不确定性,而不是预测单个值。
  • 你的训练集具有大量与数据点数量相关的特征。
  • 你的数据是结构化的 – 例如,使用组,空间,计算图或语言语义,并且你希望使用先验信息来获取这个结构。
  • 你有一个,如我们在开发者大会上所讨论的,依靠测量值重构等离子体的逆问题。

TensorFlow Probability为你提供解决这些问题的工具。此外,它还继承了TensorFlow的优势,例如自动微分,以及通过多种平台(CPU,GPU和TPU)扩展性能的能力。

什么是TensorFlow Probability?

我们的机器学习概率工具为TensorFlow生态系统中的概率推理和统计分析提供了模块化抽象。

 

TensorFlow团队:TensorFlow Probability的简单介绍

 

TensorFlow Probability结构图。

第0层

TensorFlow的数值运算。特别是,LinearOperator类实现了matrix-free,可以利用特殊结构(对角、低秩等)进行高效计算。它由TensorFlow Probability团队构建和维护,现在是TensorFlow的核心,tf.linalg的一部分。

第1层:统计的构建模块

  • Distributions :包含批量和广播语义的概率分布和相关统计的大量集合。
  • Bijectors:随机变量的可逆和可组合变换。Bijectors提供了丰富的变换分布的类,从经典的例子(如对数正态分布)到复杂的深度学习模型。

(有关更多信息,请参阅:https://arxiv.org/abs/1711.10604)

第2层:模型构建

  • Edward2:一种将灵活的概率模型指定为程序的概率编程语言。
  • 概率层:具有它们所代表函数不确定性的神经网络层,扩展了TensorFlow层。
  • 可训练分布:由单个张量参数化的概率分布,使建立输出概率分布神经网络变得容易。

第3层:概率推理

  • 马尔可夫链Monte Carlo:通过抽样逼近积分的算法。包括HMC(Hamiltonian Monte Carlo)算法,随机游走Metropolis-Hastings,以及构建自定义转换内核的能力。
  • 变分推理:通过优化来近似积分的算法。
  • 优化器:随机优化方法,扩展TensorFlow优化器。。
  • 蒙特卡洛:用于计算蒙特卡罗期望值的工具。

第4层:预制模型和推理

  • 贝叶斯结构的时间序列(即将推出):用于拟合时间序列模型的高级接口(即类似于R语言的BSTS包)。
  • 广义线性混合模型(即将推出):用于拟合混合效应回归模型(mixed-effects regression models)的高级接口(类似于R的lme4包)。

TensorFlow Probability团队致力于通过尖端功能,持续代码更新和错误修复来支持用户和贡献者。我们将继续添加端到端的示例和教程。

示例:

使用EDWARD2构建线性混合效应模型

线性混合效应模型是一种对数据中结构化关系进行建模的简单方法。也称为等级线性模型(hierarchical linear model),它共享统计的各组数据点的强度,以改进对单个数据点的推理。

作为演示,我们使用R中流行的lme4包中的InstEval数据集,它由大学课程及其评级组成。使用TensorFlow Probability,我们将模型指定为Edward2概率程序(tfp.edward2,继承自Edward)。下面的程序根据其生成过程对模型进行具体化。

01import tensorflow as tf
02from tensorflow_probabilityimport edward2 as ed
03def model(features):
04  # Set up fixed effects and other parameters.
05  intercept= tf.get_variable("intercept", [])
06  service_effects= tf.get_variable("service_effects", [])
07  student_stddev_unconstrained= tf.get_variable(
08      "student_stddev_pre", [])
09  instructor_stddev_unconstrained= tf.get_variable(
10      "instructor_stddev_pre", [])
11  # Set up random effects.
12  student_effects= ed.MultivariateNormalDiag(
13      loc=tf.zeros(num_students),
14      scale_identity_multiplier=tf.exp(
15          student_stddev_unconstrained),
16      name="student_effects")
17  instructor_effects= ed.MultivariateNormalDiag(
18      loc=tf.zeros(num_instructors),
19      scale_identity_multiplier=tf.exp(
20          instructor_stddev_unconstrained),
21      name="instructor_effects")
22  # Set up likelihood given fixed and random effects.
23  ratings= ed.Normal(
24      loc=(service_effects* features["service"]+
25           tf.gather(student_effects, features["students"])+
26           tf.gather(instructor_effects, features["instructors"])+
27           intercept),
28      scale=1.,
29      name="ratings")
30return ratings

该模型将“服务”,“学生”和“教师”的特征字典作为输入;这是每个元素描述单个课程的向量。模型对这些输入进行回归,假定潜在的随机变量,并返回课程评级的分布。在此输出上运行的TensorFlow会话将返回生成的评级。

详细请参阅:https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Models.ipynb

使用TFP BIJECTORS构建高斯COPULA函数

Copula是多元概率分布,每个变量的边际概率分布是均匀的。要使用TFP内联函数构建copula,可以使用Bijectors和TransformedDistribution。这些抽象可以轻松创建复杂的分布,如:

01import tensorflow_probability as tfp
02tfd= tfp.distributions
03tfb= tfp.distributions.bijectors
04# Example: Log-Normal Distribution
05log_normal= tfd.TransformedDistribution(
06    distribution=tfd.Normal(loc=0., scale=1.),
07    bijector=tfb.Exp())
08# Example: Kumaraswamy Distribution
09Kumaraswamy= tfd.TransformedDistribution(
10    distribution=tfd.Uniform(low=0., high=1.),
11    bijector=tfb.Kumaraswamy(
12        concentration1=2.,
13        concentration0=2.))
14# Example: Masked Autoregressive Flow
15https://arxiv.org/abs/1705.07057
16shift_and_log_scale_fn= tfb.masked_autoregressive_default_template(
17    hidden_layers=[512,512],
18    event_shape=[28*28])
19maf= tfd.TransformedDistribution(
20    distribution=tfd.Normal(loc=0., scale=1.),    
21    bijector=tfb.MaskedAutoregressiveFlow(
22        shift_and_log_scale_fn=shift_and_log_scale_fn))

高斯copula创建一些自定义Bijectors,然后又展示了如何轻松地建立多个不同的Copula函数。

背景信息参阅“理解TensorFlow分布形状”:https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Understanding%20TensorFlow%20Distributions%20Shapes.ipynb

使用TFP构建变分自动编码器

变分自动编码器是一种机器学习模型,它使用一个学习系统来表示一些低维空间中的数据,并且使用第二学习系统来将低维表示还原为原本的输入。由于TF支持自动微分,因此黑盒变分推理简直就是小case!例如:

01import tensorflow as tf
02import tensorflow_probability as tfp
03# Assumes user supplies `likelihood`, `prior`, `surrogate_posterior`
04# functions and that each returns a
05# tf.distribution.Distribution-like object.
06elbo_loss= tfp.vi.monte_carlo_csiszar_f_divergence(
07    f=tfp.vi.kl_reverse, # Equivalent to "Evidence Lower BOund"
08    p_log_prob=lambda z: likelihood(z).log_prob(x)+ prior().log_prob(z),
09    q=surrogate_posterior(x),
10    num_draws=1)
11train= tf.train.AdamOptimizer(
12    learning_rate=0.01).minimize(elbo_loss)

详细信息,请查看我们的变分自动编码器示例!

链接:https://github.com/tensorflow/probability/tree/master/tensorflow_probability/examples/vae

具有TFP概率层的贝叶斯神经网络

贝叶斯神经网络是在其权重和偏置上具有先验分布的神经网络。它通过这些先验提供了更多不确定性。贝叶斯神经网络也可以解释为神经网络的无限集合:它依据先验分配每个神经网络结构概率。

作为示范,我们使用CIFAR-10数据集:特征(形状为32 x 32 x 3的图像)和标签(值为0到9)。为了拟合神经网络,我们将使用变分推理(这是一套逼近神经网络权重和偏置的后验分布的方法)。也就是说,我们使用TensorFlow Probabilistic Layers模块(tfp.layers)中最近发布的Flipout estimator。

01import tensorflow as tf
02import tensorflow_probability as tfp
03def neural_net(inputs):
04  net= tf.reshape(inputs, [-1,32,32,3])
05  net= tfp.layers.Convolution2DFlipout(filters=64,
06                                        kernel_size=5,
07                                        padding='SAME',
08                                        activation=tf.nn.relu)(net)
09  net= tf.keras.layers.MaxPooling2D(pool_size=2,
10                                     strides=2,
11                                     padding='SAME')(net)
12  net= tf.reshape(net, [-1,8 * 8 * 64])
13  net= tfp.layers.DenseFlipout(units=10)(net)
14  return net
15# Build loss function for training.
16logits= neural_net(features)
17neg_log_likelihood= tf.nn.softmax_cross_entropy_with_logits(
18    labels=labels, logits=logits)
19kl= sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
20loss= neg_log_likelihood+ kl
21train_op= tf.train.AdamOptimizer().minimize(loss)

neural_net函数在输入张量上组建神经网络层,并且针对概率卷积层和概率稠密层执行随机前向迭代。该函数返回输出张量,它的形状具有批量大小和10个值。张量的每一行代表了logits(无约束概率值),即每个数据点属于10个类中的一个。

对于训练,我们建立损失函数,它包括两项:预期的负的对数似然和KL散度。我们通过蒙特卡罗近似预期的负对数似然。而KL散度作为层的参数,通过正则化项添加。

tfp.layers也可以用于使用tf.keras.Model类的eager execution (可以立即评估操作并且无需额外图形构建步骤)。

view source

01class MNISTModel(tf.keras.Model):
02  def __init__(self):
03    super(MNISTModel,self).__init__()
04    self.dense1= tfp.layers.DenseFlipout(units=10)
05    self.dense2= tfp.layers.DenseFlipout(units=10)
06  def call(self,input):
07    """Run the model."""
08    result= self.dense1(input)
09    result= self.dense2(result)
10    # reuse variables from dense2 layer
11    result= self.dense2(result) 
12    return result
13model= MNISTModel()

入门

要开始在TensorFlow中进行概率机器学习,请运行:

1pip install--user--upgrade tfp-nightly

对于所有的代码和细节,请查看github.com/tensorflow/probability

本文转自ATYUN人工智能媒体平台,原文链接:TensorFlow团队:TensorFlow Probability的简单介绍

更多推荐

剑桥大学训练蔬菜采摘机器人识别成熟莴苣并进行收割

AI使用谷歌趋势数据来预测感染流感人数

RapidMiner:企业身份验证

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值