diff --git a/tensorflow_probability/g3doc/api_docs/python/_toc.yaml b/tensorflow_probability/g3doc/api_docs/python/_toc.yaml index 977a4f10ad..74f8c50e9b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/_toc.yaml +++ b/tensorflow_probability/g3doc/api_docs/python/_toc.yaml @@ -42,6 +42,8 @@ toc: path: /probability/api_docs/python/tfp/bijectors/CholeskyToInvCholesky - title: ConditionalBijector path: /probability/api_docs/python/tfp/bijectors/ConditionalBijector + - title: DiscreteCosineTransform + path: /probability/api_docs/python/tfp/bijectors/DiscreteCosineTransform - title: Exp path: /probability/api_docs/python/tfp/bijectors/Exp - title: FillTriangular @@ -160,6 +162,10 @@ toc: path: /probability/api_docs/python/tfp/distributions/GaussianProcessRegressionModel - title: Geometric path: /probability/api_docs/python/tfp/distributions/Geometric + - title: Gumbel + path: /probability/api_docs/python/tfp/distributions/Gumbel + - title: HalfCauchy + path: /probability/api_docs/python/tfp/distributions/HalfCauchy - title: HalfNormal path: /probability/api_docs/python/tfp/distributions/HalfNormal - title: Independent @@ -168,6 +174,8 @@ toc: path: /probability/api_docs/python/tfp/distributions/InverseGamma - title: InverseGammaWithSoftplusConcentrationRate path: /probability/api_docs/python/tfp/distributions/InverseGammaWithSoftplusConcentrationRate + - title: InverseGaussian + path: /probability/api_docs/python/tfp/distributions/InverseGaussian - title: kl_divergence path: /probability/api_docs/python/tfp/distributions/kl_divergence - title: Kumaraswamy @@ -218,6 +226,8 @@ toc: path: /probability/api_docs/python/tfp/distributions/normal_conjugates_known_scale_predictive - title: OneHotCategorical path: /probability/api_docs/python/tfp/distributions/OneHotCategorical + - title: Pareto + path: /probability/api_docs/python/tfp/distributions/Pareto - title: percentile path: /probability/api_docs/python/tfp/distributions/percentile - title: Poisson @@ -272,6 +282,8 @@ toc: path: /probability/api_docs/python/tfp/distributions/VectorLaplaceDiag - title: VectorSinhArcsinhDiag path: /probability/api_docs/python/tfp/distributions/VectorSinhArcsinhDiag + - title: VonMises + path: /probability/api_docs/python/tfp/distributions/VonMises - title: VonMisesFisher path: /probability/api_docs/python/tfp/distributions/VonMisesFisher - title: Wishart @@ -312,12 +324,14 @@ toc: path: /probability/api_docs/python/tfp/edward2/Gamma - title: Geometric path: /probability/api_docs/python/tfp/edward2/Geometric - - title: get_interceptor - path: /probability/api_docs/python/tfp/edward2/get_interceptor + - title: get_next_interceptor + path: /probability/api_docs/python/tfp/edward2/get_next_interceptor - title: HalfNormal path: /probability/api_docs/python/tfp/edward2/HalfNormal - title: Independent path: /probability/api_docs/python/tfp/edward2/Independent + - title: interceptable + path: /probability/api_docs/python/tfp/edward2/interceptable - title: interception path: /probability/api_docs/python/tfp/edward2/interception - title: InverseGamma @@ -364,6 +378,8 @@ toc: path: /probability/api_docs/python/tfp/edward2/SinhArcsinh - title: StudentT path: /probability/api_docs/python/tfp/edward2/StudentT + - title: tape + path: /probability/api_docs/python/tfp/edward2/tape - title: TransformedDistribution path: /probability/api_docs/python/tfp/edward2/TransformedDistribution - title: Uniform @@ -398,6 +414,10 @@ toc: path: /probability/api_docs/python/tfp/glm/fit - title: fit_one_step path: /probability/api_docs/python/tfp/glm/fit_one_step + - title: fit_sparse + path: /probability/api_docs/python/tfp/glm/fit_sparse + - title: fit_sparse_one_step + path: /probability/api_docs/python/tfp/glm/fit_sparse_one_step - title: GammaExp path: /probability/api_docs/python/tfp/glm/GammaExp - title: GammaSoftplus @@ -414,6 +434,8 @@ toc: path: /probability/api_docs/python/tfp/glm/Poisson - title: PoissonSoftplus path: /probability/api_docs/python/tfp/glm/PoissonSoftplus + - title: soft_threshold + path: /probability/api_docs/python/tfp/glm/soft_threshold - title: tfp.layers section: - title: Overview @@ -446,6 +468,8 @@ toc: section: - title: Overview path: /probability/api_docs/python/tfp/math + - title: custom_gradient + path: /probability/api_docs/python/tfp/math/custom_gradient - title: diag_jacobian path: /probability/api_docs/python/tfp/math/diag_jacobian - title: matvecmul @@ -542,6 +566,24 @@ toc: path: /probability/api_docs/python/tfp/positive_semidefinite_kernels/MaternThreeHalves - title: PositiveSemidefiniteKernel path: /probability/api_docs/python/tfp/positive_semidefinite_kernels/PositiveSemidefiniteKernel + - title: tfp.sts + section: + - title: Overview + path: /probability/api_docs/python/tfp/sts + - title: AdditiveStateSpaceModel + path: /probability/api_docs/python/tfp/sts/AdditiveStateSpaceModel + - title: LocalLinearTrend + path: /probability/api_docs/python/tfp/sts/LocalLinearTrend + - title: LocalLinearTrendStateSpaceModel + path: /probability/api_docs/python/tfp/sts/LocalLinearTrendStateSpaceModel + - title: Seasonal + path: /probability/api_docs/python/tfp/sts/Seasonal + - title: SeasonalStateSpaceModel + path: /probability/api_docs/python/tfp/sts/SeasonalStateSpaceModel + - title: StructuralTimeSeries + path: /probability/api_docs/python/tfp/sts/StructuralTimeSeries + - title: Sum + path: /probability/api_docs/python/tfp/sts/Sum - title: tfp.trainable_distributions section: - title: Overview diff --git a/tensorflow_probability/g3doc/api_docs/python/index.md b/tensorflow_probability/g3doc/api_docs/python/index.md index 96813a9ac6..64e0562456 100644 --- a/tensorflow_probability/g3doc/api_docs/python/index.md +++ b/tensorflow_probability/g3doc/api_docs/python/index.md @@ -12,6 +12,7 @@ * tfp.bijectors.CholeskyOuterProduct * tfp.bijectors.CholeskyToInvCholesky * tfp.bijectors.ConditionalBijector +* tfp.bijectors.DiscreteCosineTransform * tfp.bijectors.Exp * tfp.bijectors.FillTriangular * tfp.bijectors.Gumbel @@ -65,10 +66,13 @@ * tfp.distributions.GaussianProcess * tfp.distributions.GaussianProcessRegressionModel * tfp.distributions.Geometric +* tfp.distributions.Gumbel +* tfp.distributions.HalfCauchy * tfp.distributions.HalfNormal * tfp.distributions.Independent * tfp.distributions.InverseGamma * tfp.distributions.InverseGammaWithSoftplusConcentrationRate +* tfp.distributions.InverseGaussian * tfp.distributions.Kumaraswamy * tfp.distributions.LKJ * tfp.distributions.Laplace @@ -89,6 +93,7 @@ * tfp.distributions.Normal * tfp.distributions.NormalWithSoftplusScale * tfp.distributions.OneHotCategorical +* tfp.distributions.Pareto * tfp.distributions.Poisson * tfp.distributions.PoissonLogNormalQuadratureCompound * tfp.distributions.QuantizedDistribution @@ -108,6 +113,7 @@ * tfp.distributions.VectorExponentialDiag * tfp.distributions.VectorLaplaceDiag * tfp.distributions.VectorSinhArcsinhDiag +* tfp.distributions.VonMises * tfp.distributions.VonMisesFisher * tfp.distributions.Wishart * tfp.distributions.assign_log_moving_mean_exp @@ -176,9 +182,11 @@ * tfp.edward2.VectorSinhArcsinhDiag * tfp.edward2.Wishart * tfp.edward2.as_random_variable -* tfp.edward2.get_interceptor +* tfp.edward2.get_next_interceptor +* tfp.edward2.interceptable * tfp.edward2.interception * tfp.edward2.make_log_joint_fn +* tfp.edward2.tape * tfp.glm * tfp.glm.Bernoulli * tfp.glm.BernoulliNormalCDF @@ -195,6 +203,9 @@ * tfp.glm.convergence_criteria_small_relative_norm_weights_change * tfp.glm.fit * tfp.glm.fit_one_step +* tfp.glm.fit_sparse +* tfp.glm.fit_sparse_one_step +* tfp.glm.soft_threshold * tfp.layers * tfp.layers.Convolution1DFlipout * tfp.layers.Convolution1DReparameterization @@ -209,6 +220,7 @@ * tfp.layers.default_mean_field_normal_fn * tfp.layers.default_multivariate_normal_fn * tfp.math +* tfp.math.custom_gradient * tfp.math.diag_jacobian * tfp.math.matvecmul * tfp.math.pinv @@ -252,6 +264,14 @@ * tfp.positive_semidefinite_kernels.MaternOneHalf * tfp.positive_semidefinite_kernels.MaternThreeHalves * tfp.positive_semidefinite_kernels.PositiveSemidefiniteKernel +* tfp.sts +* tfp.sts.AdditiveStateSpaceModel +* tfp.sts.LocalLinearTrend +* tfp.sts.LocalLinearTrendStateSpaceModel +* tfp.sts.Seasonal +* tfp.sts.SeasonalStateSpaceModel +* tfp.sts.StructuralTimeSeries +* tfp.sts.Sum * tfp.trainable_distributions * tfp.trainable_distributions.bernoulli * tfp.trainable_distributions.multivariate_normal_tril diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp.md b/tensorflow_probability/g3doc/api_docs/python/tfp.md index b548f2d65b..8fd270692c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp.md @@ -1,5 +1,7 @@
+ +
# Module: tfp @@ -28,9 +30,15 @@ Tools for probabilistic reasoning in TensorFlow. [`positive_semidefinite_kernels`](./tfp/positive_semidefinite_kernels.md) module: Positive-semidefinite kernels package. +[`sts`](./tfp/sts.md) module: Framework for Bayesian structural time series models. + [`trainable_distributions`](./tfp/trainable_distributions.md) module: Trainable distributions. [`util`](./tfp/util.md) module: TensorFlow Probability python utilities. [`vi`](./tfp/vi.md) module: Methods and objectives for variational inference. +## Other Members + +

__version__

+ diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors.md index a204cbd0b1..6cf9bb0267 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors.md @@ -1,5 +1,6 @@
+
@@ -29,6 +30,8 @@ Bijector Ops. [`class ConditionalBijector`](../tfp/bijectors/ConditionalBijector.md): Conditional Bijector is a Bijector that allows intrinsic conditioning. +[`class DiscreteCosineTransform`](../tfp/bijectors/DiscreteCosineTransform.md): Compute `Y = g(X) = DCT(X)`, where DCT type is indicated by the `type` arg. + [`class Exp`](../tfp/bijectors/Exp.md): Compute `Y = g(X) = exp(X)`. [`class FillTriangular`](../tfp/bijectors/FillTriangular.md): Transforms vectors to triangular. @@ -87,5 +90,5 @@ Bijector Ops. ## Other Members -`__all__` +

__all__

diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AbsoluteValue.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AbsoluteValue.md index 84ff552fd2..5da6240b69 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AbsoluteValue.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AbsoluteValue.md @@ -1,5 +1,6 @@
+ @@ -60,6 +61,26 @@ abs.inverse_log_det_jacobian(0.) ==> [0., 0.] ``` +

__init__

+ +``` python +__init__( + validate_args=False, + name='absolute_value' +) +``` + +Instantiates the `AbsoluteValue` bijector. + +#### Args: + +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness, in particular whether inputs to `inverse` and + `inverse_log_det_jacobian` are non-negative. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -101,24 +122,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='absolute_value' -) -``` - -Instantiates the `AbsoluteValue` bijector. - -#### Args: - -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness, in particular whether inputs to `inverse` and - `inverse_log_det_jacobian` are non-negative. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -209,8 +212,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -325,8 +328,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Affine.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Affine.md index 6f4d7cadf0..4b34d0aff6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Affine.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Affine.md @@ -1,5 +1,6 @@
+ @@ -80,60 +81,7 @@ b = Affine(shift=[1., 2, 3], ``` -## Properties - -

adjoint

- -`bool` indicating `scale` should be used as conjugate transpose. - -

dtype

- -dtype of `Tensor`s transformable by this distribution. - -

forward_min_event_ndims

- -Returns the minimal number of dimensions bijector.forward operates on. - -

graph_parents

- -Returns this `Bijector`'s graph_parents as a Python list. - -

inverse_min_event_ndims

- -Returns the minimal number of dimensions bijector.inverse operates on. - -

is_constant_jacobian

- -Returns true iff the Jacobian matrix is not a function of x. - -Note: Jacobian matrix is either constant for both forward and inverse or -neither. - -#### Returns: - -* `is_constant_jacobian`: Python `bool`. - -

name

- -Returns the string name of this `Bijector`. - -

scale

- -The `scale` `LinearOperator` in `Y = scale @ X + shift`. - -

shift

- -The `shift` `Tensor` in `Y = scale @ X + shift`. - -

validate_args

- -Returns True if Tensor arguments will be validated. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -213,6 +161,61 @@ specified then `scale += IdentityMatrix`. Otherwise specifying a * `ValueError`: if `perturb_diag` is specified but not `perturb_factor`. * `TypeError`: if `shift` has different `dtype` from `scale` arguments. + + +## Properties + +

adjoint

+ +`bool` indicating `scale` should be used as conjugate transpose. + +

dtype

+ +dtype of `Tensor`s transformable by this distribution. + +

forward_min_event_ndims

+ +Returns the minimal number of dimensions bijector.forward operates on. + +

graph_parents

+ +Returns this `Bijector`'s graph_parents as a Python list. + +

inverse_min_event_ndims

+ +Returns the minimal number of dimensions bijector.inverse operates on. + +

is_constant_jacobian

+ +Returns true iff the Jacobian matrix is not a function of x. + +Note: Jacobian matrix is either constant for both forward and inverse or +neither. + +#### Returns: + +* `is_constant_jacobian`: Python `bool`. + +

name

+ +Returns the string name of this `Bijector`. + +

scale

+ +The `scale` `LinearOperator` in `Y = scale @ X + shift`. + +

shift

+ +The `shift` `Tensor` in `Y = scale @ X + shift`. + +

validate_args

+ +Returns True if Tensor arguments will be validated. + + + +## Methods +

forward

``` python @@ -303,8 +306,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -419,8 +422,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineLinearOperator.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineLinearOperator.md index b2c54c6ba8..1bc40ea940 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineLinearOperator.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineLinearOperator.md @@ -1,5 +1,6 @@
+ @@ -81,6 +82,41 @@ affine = AffineLinearOperator(shift, scale) y = affine.forward(x) # [3., 7, 11] ``` +

__init__

+ +``` python +__init__( + shift=None, + scale=None, + adjoint=False, + validate_args=False, + name='affine_linear_operator' +) +``` + +Instantiates the `AffineLinearOperator` bijector. + +#### Args: + +* `shift`: Floating-point `Tensor`. +* `scale`: Subclass of `LinearOperator`. Represents the (batch) positive + definite matrix `M` in `R^{k x k}`. +* `adjoint`: Python `bool` indicating whether to use the `scale` matrix as + specified or its adjoint. + Default value: `False`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + +#### Raises: + +* `TypeError`: if `scale` is not a `LinearOperator`. +* `TypeError`: if `shift.dtype` does not match `scale.dtype`. +* `ValueError`: if not `scale.is_non_singular`. + + + ## Properties

adjoint

@@ -134,39 +170,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - shift=None, - scale=None, - adjoint=False, - validate_args=False, - name='affine_linear_operator' -) -``` - -Instantiates the `AffineLinearOperator` bijector. - -#### Args: - -* `shift`: Floating-point `Tensor`. -* `scale`: Subclass of `LinearOperator`. Represents the (batch) positive - definite matrix `M` in `R^{k x k}`. -* `adjoint`: Python `bool` indicating whether to use the `scale` matrix as - specified or its adjoint. - Default value: `False`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. - - -#### Raises: - -* `TypeError`: if `scale` is not a `LinearOperator`. -* `TypeError`: if `shift.dtype` does not match `scale.dtype`. -* `ValueError`: if not `scale.is_non_singular`. -

forward

``` python @@ -257,8 +260,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -373,8 +376,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineScalar.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineScalar.md index a74b688477..2f7f3917c6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineScalar.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/AffineScalar.md @@ -1,5 +1,6 @@
+ @@ -43,6 +44,42 @@ b = AffineScalar( scale=2.) ``` +

__init__

+ +``` python +__init__( + shift=None, + scale=None, + validate_args=False, + name='affine_scalar' +) +``` + +Instantiates the `AffineScalar` bijector. + +This `Bijector` is initialized with `shift` `Tensor` and `scale` arguments, +giving the forward operation: + +```none +Y = g(X) = scale * X + shift +``` + +if `scale` is not specified, then the bijector has the semantics of +`scale = 1.`. Similarly, if `shift` is not specified, then the bijector +has the semantics of `shift = 0.`. + +#### Args: + +* `shift`: Floating-point `Tensor`. If this is set to `None`, no shift is + applied. +* `scale`: Floating-point `Tensor`. If this is set to `None`, no scale is + applied. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -92,40 +129,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - shift=None, - scale=None, - validate_args=False, - name='affine_scalar' -) -``` - -Instantiates the `AffineScalar` bijector. - -This `Bijector` is initialized with `shift` `Tensor` and `scale` arguments, -giving the forward operation: - -```none -Y = g(X) = scale * X + shift -``` - -if `scale` is not specified, then the bijector has the semantics of -`scale = 1.`. Similarly, if `shift` is not specified, then the bijector -has the semantics of `shift = 0.`. - -#### Args: - -* `shift`: Floating-point `Tensor`. If this is set to `None`, no shift is - applied. -* `scale`: Floating-point `Tensor`. If this is set to `None`, no scale is - applied. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -216,8 +219,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -332,8 +335,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/BatchNormalization.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/BatchNormalization.md index 904dc3cfb8..cc4fbb7d8d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/BatchNormalization.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/BatchNormalization.md @@ -1,5 +1,6 @@
+ @@ -47,20 +48,20 @@ computed at training-time. De-normalization is useful for sampling. dist = tfd.TransformedDistribution( distribution=tfd.Normal()), - bijector=tfb.BatchNorm()) + bijector=tfb.BatchNormalization()) y = tfd.MultivariateNormalDiag(loc=1., scale=2.).sample(100) # ~ N(1, 2) x = dist.bijector.inverse(y) # ~ N(0, 1) y = dist.sample() # ~ N(1, 2) ``` -During training time, `BatchNorm.inverse` and `BatchNorm.forward` are not -guaranteed to be inverses of each other because `inverse(y)` uses statistics -of the current minibatch, while `forward(x)` uses running-average statistics -accumulated from training. In other words, -`BatchNorm.inverse(BatchNorm.forward(...))` and -`BatchNorm.forward(BatchNorm.inverse(...))` will be identical when -`training=False` but may be different when `training=True`. +During training time, `BatchNormalization.inverse` and +`BatchNormalization.forward` are not guaranteed to be inverses of each other +because `inverse(y)` uses statistics of the current minibatch, while +`forward(x)` uses running-average statistics accumulated from training. In +other words, `BatchNormalization.inverse(BatchNormalization.forward(...))` and +`BatchNormalization.forward(BatchNormalization.inverse(...))` will be +identical when `training=False` but may be different when `training=True`. #### References @@ -77,6 +78,40 @@ accumulated from training. In other words, Autoregressive Flow for Density Estimation. In _Neural Information Processing Systems_, 2017. https://arxiv.org/abs/1705.07057 +

__init__

+ +``` python +__init__( + batchnorm_layer=None, + training=True, + validate_args=False, + name='batch_normalization' +) +``` + +Instantiates the `BatchNormalization` bijector. + +#### Args: + +* `batchnorm_layer`: `tf.layers.BatchNormalization` layer object. If `None`, + defaults to + `tf.layers.BatchNormalization(gamma_constraint=tf.nn.relu(x) + 1e-6)`. + This ensures positivity of the scale variable. + +* `training`: If True, updates running-average statistics during call to + `inverse()`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + +#### Raises: + +* `ValueError`: If bn_layer is not an instance of + `tf.layers.BatchNormalization`, or if it is specified with `renorm=True` + or a virtual batch size. + + + ## Properties

dtype

@@ -118,38 +153,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - batchnorm_layer=None, - training=True, - validate_args=False, - name='batch_normalization' -) -``` - -Instantiates the `BatchNorm` bijector. - -#### Args: - -* `batchnorm_layer`: `tf.layers.BatchNormalization` layer object. If `None`, - defaults to - `tf.layers.BatchNormalization(gamma_constraint=tf.nn.relu(x) + 1e-6)`. - This ensures positivity of the scale variable. - -* `training`: If True, updates running-average statistics during call to - `inverse()`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. - -#### Raises: - -* `ValueError`: If bn_layer is not an instance of - `tf.layers.BatchNormalization`, or if it is specified with `renorm=True` - or a virtual batch size. -

forward

``` python @@ -240,8 +243,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -356,8 +359,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Bijector.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Bijector.md index 581d387f47..dba9b2a207 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Bijector.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Bijector.md @@ -1,5 +1,6 @@
+ @@ -129,10 +130,10 @@ def transformed_sample(bijector, x): name=name) def _forward(self, x): - return math_ops.exp(x) + return tf.exp(x) def _inverse(self, y): - return math_ops.log(y) + return tf.log(y) def _inverse_log_det_jacobian(self, y): return -self._forward_log_det_jacobian(self._inverse(y)) @@ -279,7 +280,7 @@ The semantics of this argument are the following: return -self._forward_log_det_jacobian(self._inverse(y)) def _forward_log_det_jacobian(self, x): - # The full log jacobian determinant would be array_ops.zero_like(x). + # The full log jacobian determinant would be tf.zero_like(x). # However, we circumvent materializing that, since the jacobian # calculation is input independent, and we specify it for one input. return constant_op.constant(0., x.dtype.base_dtype) @@ -378,48 +379,7 @@ abs.inverse_log_det_jacobian(0., event_ndims=0) ==> (0., 0.) ``` -## Properties - -

dtype

- -dtype of `Tensor`s transformable by this distribution. - -

forward_min_event_ndims

- -Returns the minimal number of dimensions bijector.forward operates on. - -

graph_parents

- -Returns this `Bijector`'s graph_parents as a Python list. - -

inverse_min_event_ndims

- -Returns the minimal number of dimensions bijector.inverse operates on. - -

is_constant_jacobian

- -Returns true iff the Jacobian matrix is not a function of x. - -Note: Jacobian matrix is either constant for both forward and inverse or -neither. - -#### Returns: - -* `is_constant_jacobian`: Python `bool`. - -

name

- -Returns the string name of this `Bijector`. - -

validate_args

- -Returns True if Tensor arguments will be validated. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -474,6 +434,49 @@ See `Bijector` subclass docstring for more details and specific examples. negative. * `ValueError`: If a member of `graph_parents` is not a `Tensor`. + + +## Properties + +

dtype

+ +dtype of `Tensor`s transformable by this distribution. + +

forward_min_event_ndims

+ +Returns the minimal number of dimensions bijector.forward operates on. + +

graph_parents

+ +Returns this `Bijector`'s graph_parents as a Python list. + +

inverse_min_event_ndims

+ +Returns the minimal number of dimensions bijector.inverse operates on. + +

is_constant_jacobian

+ +Returns true iff the Jacobian matrix is not a function of x. + +Note: Jacobian matrix is either constant for both forward and inverse or +neither. + +#### Returns: + +* `is_constant_jacobian`: Python `bool`. + +

name

+ +Returns the string name of this `Bijector`. + +

validate_args

+ +Returns True if Tensor arguments will be validated. + + + +## Methods +

forward

``` python @@ -564,8 +567,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -680,8 +683,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Chain.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Chain.md index abfceac21e..74d076883f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Chain.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Chain.md @@ -1,5 +1,6 @@
+ @@ -57,6 +58,34 @@ Results in: = tf.log(y - 1.) ``` +

__init__

+ +``` python +__init__( + bijectors=None, + validate_args=False, + name=None +) +``` + +Instantiates `Chain` bijector. + +#### Args: + +* `bijectors`: Python `list` of bijector instances. An empty list makes this + bijector equivalent to the `Identity` bijector. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str`, name given to ops managed by this object. Default: + E.g., `Chain([Exp(), Softplus()]).name == "chain_of_exp_of_softplus"`. + + +#### Raises: + +* `ValueError`: if bijectors have different dtypes. + + + ## Properties

bijectors

@@ -102,32 +131,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - bijectors=None, - validate_args=False, - name=None -) -``` - -Instantiates `Chain` bijector. - -#### Args: - -* `bijectors`: Python `list` of bijector instances. An empty list makes this - bijector equivalent to the `Identity` bijector. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str`, name given to ops managed by this object. Default: - E.g., `Chain([Exp(), Softplus()]).name == "chain_of_exp_of_softplus"`. - - -#### Raises: - -* `ValueError`: if bijectors have different dtypes. -

forward

``` python @@ -218,8 +221,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -334,8 +337,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyOuterProduct.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyOuterProduct.md index e83d4989ee..8b2f7c0925 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyOuterProduct.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyOuterProduct.md @@ -1,5 +1,6 @@
+ @@ -56,6 +57,25 @@ bijector.CholeskyOuterProduct().inverse(y=[[1., 2], [2, 5]]) # Result: [[1., 0], [2, 1]], i.e., cholesky(y). ``` +

__init__

+ +``` python +__init__( + validate_args=False, + name='cholesky_outer_product' +) +``` + +Instantiates the `CholeskyOuterProduct` bijector. + +#### Args: + +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -97,23 +117,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='cholesky_outer_product' -) -``` - -Instantiates the `CholeskyOuterProduct` bijector. - -#### Args: - -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -204,8 +207,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -320,8 +323,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyToInvCholesky.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyToInvCholesky.md index 4873edf87e..7cb4d4e979 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyToInvCholesky.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/CholeskyToInvCholesky.md @@ -1,5 +1,6 @@
+ @@ -49,6 +50,19 @@ CholeskyToInvCholesky = tfb.Chain([ However, the actual calculations exploit the triangular structure of the matrices. +

__init__

+ +``` python +__init__( + validate_args=False, + name=None +) +``` + + + + + ## Properties

dtype

@@ -90,17 +104,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name=None -) -``` - - -

forward

``` python @@ -191,8 +194,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -307,8 +310,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ConditionalBijector.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ConditionalBijector.md index 48134d4e28..2fff99d0e4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ConditionalBijector.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ConditionalBijector.md @@ -1,5 +1,6 @@
+ @@ -26,48 +27,7 @@ Inherits From: [`Bijector`](../../tfp/bijectors/Bijector.md) Conditional Bijector is a Bijector that allows intrinsic conditioning. -## Properties - -

dtype

- -dtype of `Tensor`s transformable by this distribution. - -

forward_min_event_ndims

- -Returns the minimal number of dimensions bijector.forward operates on. - -

graph_parents

- -Returns this `Bijector`'s graph_parents as a Python list. - -

inverse_min_event_ndims

- -Returns the minimal number of dimensions bijector.inverse operates on. - -

is_constant_jacobian

- -Returns true iff the Jacobian matrix is not a function of x. - -Note: Jacobian matrix is either constant for both forward and inverse or -neither. - -#### Returns: - -* `is_constant_jacobian`: Python `bool`. - -

name

- -Returns the string name of this `Bijector`. - -

validate_args

- -Returns True if Tensor arguments will be validated. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -122,6 +82,49 @@ See `Bijector` subclass docstring for more details and specific examples. negative. * `ValueError`: If a member of `graph_parents` is not a `Tensor`. + + +## Properties + +

dtype

+ +dtype of `Tensor`s transformable by this distribution. + +

forward_min_event_ndims

+ +Returns the minimal number of dimensions bijector.forward operates on. + +

graph_parents

+ +Returns this `Bijector`'s graph_parents as a Python list. + +

inverse_min_event_ndims

+ +Returns the minimal number of dimensions bijector.inverse operates on. + +

is_constant_jacobian

+ +Returns true iff the Jacobian matrix is not a function of x. + +Note: Jacobian matrix is either constant for both forward and inverse or +neither. + +#### Returns: + +* `is_constant_jacobian`: Python `bool`. + +

name

+ +Returns the string name of this `Bijector`. + +

validate_args

+ +Returns True if Tensor arguments will be validated. + + + +## Methods +

forward

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/DiscreteCosineTransform.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/DiscreteCosineTransform.md new file mode 100644 index 0000000000..674f7f93d7 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/DiscreteCosineTransform.md @@ -0,0 +1,337 @@ +
+ + + + + + + + + + + + + + + + + + +
+ +# tfp.bijectors.DiscreteCosineTransform + +## Class `DiscreteCosineTransform` + +Inherits From: [`Bijector`](../../tfp/bijectors/Bijector.md) + +Compute `Y = g(X) = DCT(X)`, where DCT type is indicated by the `type` arg. + +The [discrete cosine transform]( +https://en.wikipedia.org/wiki/Discrete_cosine_transform) efficiently applies +a unitary DCT operator. This can be useful for mixing and decorrelating across +the innermost event dimension. + +The inverse `X = g^{-1}(Y) = IDCT(Y)`, where IDCT is DCT-III for type==2. + +This bijector can be interleaved with Affine bijectors to build a cascade of +structured efficient linear layers as in [1]. + +Note that the operator applied is orthonormal (i.e. `norm='ortho'`). + +#### References + +[1]: Moczulski M, Denil M, Appleyard J, de Freitas N. ACDC: A structured + efficient linear layer. In _International Conference on Learning + Representations_, 2016. https://arxiv.org/abs/1511.05946 + +

__init__

+ +``` python +__init__( + dct_type=2, + validate_args=False, + name='dct' +) +``` + +Instantiates the `PowerTransform` bijector. + +#### Args: + +* `dct_type`: Python `int`, the DCT type performed by the forward + transformation. Currently, only 2 and 3 are supported. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + +## Properties + +

dtype

+ +dtype of `Tensor`s transformable by this distribution. + +

forward_min_event_ndims

+ +Returns the minimal number of dimensions bijector.forward operates on. + +

graph_parents

+ +Returns this `Bijector`'s graph_parents as a Python list. + +

inverse_min_event_ndims

+ +Returns the minimal number of dimensions bijector.inverse operates on. + +

is_constant_jacobian

+ +Returns true iff the Jacobian matrix is not a function of x. + +Note: Jacobian matrix is either constant for both forward and inverse or +neither. + +#### Returns: + +* `is_constant_jacobian`: Python `bool`. + +

name

+ +Returns the string name of this `Bijector`. + +

validate_args

+ +Returns True if Tensor arguments will be validated. + + + +## Methods + +

forward

+ +``` python +forward( + x, + name='forward' +) +``` + +Returns the forward `Bijector` evaluation, i.e., X = g(Y). + +#### Args: + +* `x`: `Tensor`. The input to the "forward" evaluation. +* `name`: The name to give this op. + + +#### Returns: + +`Tensor`. + + +#### Raises: + +* `TypeError`: if `self.dtype` is specified and `x.dtype` is not + `self.dtype`. +* `NotImplementedError`: if `_forward` is not implemented. + +

forward_event_shape

+ +``` python +forward_event_shape(input_shape) +``` + +Shape of a single sample from a single batch as a `TensorShape`. + +Same meaning as `forward_event_shape_tensor`. May be only partially defined. + +#### Args: + +* `input_shape`: `TensorShape` indicating event-portion shape passed into + `forward` function. + + +#### Returns: + +* `forward_event_shape_tensor`: `TensorShape` indicating event-portion shape + after applying `forward`. Possibly unknown. + +

forward_event_shape_tensor

+ +``` python +forward_event_shape_tensor( + input_shape, + name='forward_event_shape_tensor' +) +``` + +Shape of a single sample from a single batch as an `int32` 1D `Tensor`. + +#### Args: + +* `input_shape`: `Tensor`, `int32` vector indicating event-portion shape + passed into `forward` function. +* `name`: name to give to the op + + +#### Returns: + +* `forward_event_shape_tensor`: `Tensor`, `int32` vector indicating + event-portion shape after applying `forward`. + +

forward_log_det_jacobian

+ +``` python +forward_log_det_jacobian( + x, + event_ndims, + name='forward_log_det_jacobian' +) +``` + +Returns both the forward_log_det_jacobian. + +#### Args: + +* `x`: `Tensor`. The input to the "forward" Jacobian determinant evaluation. +* `event_ndims`: Number of dimensions in the probabilistic events being + transformed. Must be greater than or equal to + `self.forward_min_event_ndims`. The result is summed over the final + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. +* `name`: The name to give this op. + + +#### Returns: + +`Tensor`, if this bijector is injective. + If not injective this is not implemented. + + +#### Raises: + +* `TypeError`: if `self.dtype` is specified and `y.dtype` is not + `self.dtype`. +* `NotImplementedError`: if neither `_forward_log_det_jacobian` + nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented, or + this is a non-injective bijector. + +

inverse

+ +``` python +inverse( + y, + name='inverse' +) +``` + +Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y). + +#### Args: + +* `y`: `Tensor`. The input to the "inverse" evaluation. +* `name`: The name to give this op. + + +#### Returns: + +`Tensor`, if this bijector is injective. + If not injective, returns the k-tuple containing the unique + `k` points `(x1, ..., xk)` such that `g(xi) = y`. + + +#### Raises: + +* `TypeError`: if `self.dtype` is specified and `y.dtype` is not + `self.dtype`. +* `NotImplementedError`: if `_inverse` is not implemented. + +

inverse_event_shape

+ +``` python +inverse_event_shape(output_shape) +``` + +Shape of a single sample from a single batch as a `TensorShape`. + +Same meaning as `inverse_event_shape_tensor`. May be only partially defined. + +#### Args: + +* `output_shape`: `TensorShape` indicating event-portion shape passed into + `inverse` function. + + +#### Returns: + +* `inverse_event_shape_tensor`: `TensorShape` indicating event-portion shape + after applying `inverse`. Possibly unknown. + +

inverse_event_shape_tensor

+ +``` python +inverse_event_shape_tensor( + output_shape, + name='inverse_event_shape_tensor' +) +``` + +Shape of a single sample from a single batch as an `int32` 1D `Tensor`. + +#### Args: + +* `output_shape`: `Tensor`, `int32` vector indicating event-portion shape + passed into `inverse` function. +* `name`: name to give to the op + + +#### Returns: + +* `inverse_event_shape_tensor`: `Tensor`, `int32` vector indicating + event-portion shape after applying `inverse`. + +

inverse_log_det_jacobian

+ +``` python +inverse_log_det_jacobian( + y, + event_ndims, + name='inverse_log_det_jacobian' +) +``` + +Returns the (log o det o Jacobian o inverse)(y). + +Mathematically, returns: `log(det(dX/dY))(Y)`. (Recall that: `X=g^{-1}(Y)`.) + +Note that `forward_log_det_jacobian` is the negative of this function, +evaluated at `g^{-1}(y)`. + +#### Args: + +* `y`: `Tensor`. The input to the "inverse" Jacobian determinant evaluation. +* `event_ndims`: Number of dimensions in the probabilistic events being + transformed. Must be greater than or equal to + `self.inverse_min_event_ndims`. The result is summed over the final + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. +* `name`: The name to give this op. + + +#### Returns: + +`Tensor`, if this bijector is injective. + If not injective, returns the tuple of local log det + Jacobians, `log(det(Dg_i^{-1}(y)))`, where `g_i` is the restriction + of `g` to the `ith` partition `Di`. + + +#### Raises: + +* `TypeError`: if `self.dtype` is specified and `y.dtype` is not + `self.dtype`. +* `NotImplementedError`: if `_inverse_log_det_jacobian` is not implemented. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Exp.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Exp.md index 4621a8a77b..d801b23a16 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Exp.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Exp.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,25 @@ log(x) == exp.inverse(x) Note: the exp(.) is applied element-wise but the Jacobian is a reduction over the event space. +

__init__

+ +``` python +__init__( + validate_args=False, + name='exp' +) +``` + +Instantiates the `Exp` bijector. + +#### Args: + +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -89,23 +109,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='exp' -) -``` - -Instantiates the `Exp` bijector. - -#### Args: - -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -196,8 +199,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -312,8 +315,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/FillTriangular.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/FillTriangular.md index 6f6166b5a4..cf6388309f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/FillTriangular.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/FillTriangular.md @@ -1,5 +1,6 @@
+ @@ -51,6 +52,28 @@ b.forward([1, 2, 3, 4, 5, 6]) ``` +

__init__

+ +``` python +__init__( + upper=False, + validate_args=False, + name='fill_triangular' +) +``` + +Instantiates the `FillTriangular` bijector. + +#### Args: + +* `upper`: Python `bool` representing whether output matrix should be upper + triangular (`True`) or lower triangular (`False`, default). +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -92,26 +115,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - upper=False, - validate_args=False, - name='fill_triangular' -) -``` - -Instantiates the `FillTriangular` bijector. - -#### Args: - -* `upper`: Python `bool` representing whether output matrix should be upper - triangular (`True`) or lower triangular (`False`, default). -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -202,8 +205,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -318,8 +321,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Gumbel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Gumbel.md index e85efa05e9..15621401f4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Gumbel.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Gumbel.md @@ -1,5 +1,6 @@
+ @@ -28,8 +29,8 @@ Inherits From: [`Bijector`](../../tfp/bijectors/Bijector.md) Compute `Y = g(X) = exp(-exp(-(X - loc) / scale))`. -This bijector maps inputs from `[-inf, inf]` to [0, 1]`. The inverse of the -bijector applied to a uniform random variable `X ~ U(0, 1) gives back a +This bijector maps inputs from `[-inf, inf]` to `[0, 1]`. The inverse of the +bijector applied to a uniform random variable `X ~ U(0, 1)` gives back a random variable with the [Gumbel distribution](https://en.wikipedia.org/wiki/Gumbel_distribution): @@ -39,6 +40,33 @@ pdf(y; loc, scale) = exp( -( (y - loc) / scale + exp(- (y - loc) / scale) ) ) / scale ``` +

__init__

+ +``` python +__init__( + loc=0.0, + scale=1.0, + validate_args=False, + name='gumbel' +) +``` + +Instantiates the `Gumbel` bijector. + +#### Args: + +* `loc`: Float-like `Tensor` that is the same dtype and is + broadcastable with `scale`. + This is `loc` in `Y = g(X) = exp(-exp(-(X - loc) / scale))`. +* `scale`: Positive Float-like `Tensor` that is the same dtype and is + broadcastable with `loc`. + This is `scale` in `Y = g(X) = exp(-exp(-(X - loc) / scale))`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -88,31 +116,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - loc=0.0, - scale=1.0, - validate_args=False, - name='gumbel' -) -``` - -Instantiates the `Gumbel` bijector. - -#### Args: - -* `loc`: Float-like `Tensor` that is the same dtype and is - broadcastable with `scale`. - This is `loc` in `Y = g(X) = exp(-exp(-(X - loc) / scale))`. -* `scale`: Positive Float-like `Tensor` that is the same dtype and is - broadcastable with `loc`. - This is `scale` in `Y = g(X) = exp(-exp(-(X - loc) / scale))`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -203,8 +206,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -319,8 +322,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Identity.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Identity.md index 773130df02..983c650131 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Identity.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Identity.md @@ -1,5 +1,6 @@
+ @@ -37,6 +38,19 @@ x = [[1., 2], x == identity.forward(x) == identity.inverse(x) ``` +

__init__

+ +``` python +__init__( + validate_args=False, + name='identity' +) +``` + + + + + ## Properties

dtype

@@ -78,17 +92,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='identity' -) -``` - - -

forward

``` python @@ -179,8 +182,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -295,8 +298,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Inline.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Inline.md index bec8e6191f..c5ab8740cc 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Inline.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Inline.md @@ -1,5 +1,6 @@
+ @@ -39,48 +40,7 @@ exp = Inline( The above example is equivalent to the `Bijector` `Exp()`. -## Properties - -

dtype

- -dtype of `Tensor`s transformable by this distribution. - -

forward_min_event_ndims

- -Returns the minimal number of dimensions bijector.forward operates on. - -

graph_parents

- -Returns this `Bijector`'s graph_parents as a Python list. - -

inverse_min_event_ndims

- -Returns the minimal number of dimensions bijector.inverse operates on. - -

is_constant_jacobian

- -Returns true iff the Jacobian matrix is not a function of x. - -Note: Jacobian matrix is either constant for both forward and inverse or -neither. - -#### Returns: - -* `is_constant_jacobian`: Python `bool`. - -

name

- -Returns the string name of this `Bijector`. - -

validate_args

- -Returns True if Tensor arguments will be validated. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -128,6 +88,49 @@ Creates a `Bijector` from callables. dimensionality this bijector acts on. * `name`: Python `str`, name given to ops managed by this object. + + +## Properties + +

dtype

+ +dtype of `Tensor`s transformable by this distribution. + +

forward_min_event_ndims

+ +Returns the minimal number of dimensions bijector.forward operates on. + +

graph_parents

+ +Returns this `Bijector`'s graph_parents as a Python list. + +

inverse_min_event_ndims

+ +Returns the minimal number of dimensions bijector.inverse operates on. + +

is_constant_jacobian

+ +Returns true iff the Jacobian matrix is not a function of x. + +Note: Jacobian matrix is either constant for both forward and inverse or +neither. + +#### Returns: + +* `is_constant_jacobian`: Python `bool`. + +

name

+ +Returns the string name of this `Bijector`. + +

validate_args

+ +Returns True if Tensor arguments will be validated. + + + +## Methods +

forward

``` python @@ -218,8 +221,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -334,8 +337,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Invert.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Invert.md index f089726f41..1652c5642a 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Invert.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Invert.md @@ -1,5 +1,6 @@
+ @@ -37,6 +38,37 @@ exp_gamma_distribution = TransformedDistribution( bijector=bijector.Invert(bijector.Exp()) ``` +

__init__

+ +``` python +__init__( + bijector, + validate_args=False, + name=None +) +``` + +Creates a `Bijector` which swaps the meaning of `inverse` and `forward`. + +Note: An inverted bijector's `inverse_log_det_jacobian` is often more +efficient if the base bijector implements `_forward_log_det_jacobian`. If +`_forward_log_det_jacobian` is not implemented then the following code is +used: + +```python +y = self.inverse(x, **kwargs) +return -self.inverse_log_det_jacobian(y, **kwargs) +``` + +#### Args: + +* `bijector`: Bijector instance. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str`, name given to ops managed by this object. + + + ## Properties

bijector

@@ -82,35 +114,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - bijector, - validate_args=False, - name=None -) -``` - -Creates a `Bijector` which swaps the meaning of `inverse` and `forward`. - -Note: An inverted bijector's `inverse_log_det_jacobian` is often more -efficient if the base bijector implements `_forward_log_det_jacobian`. If -`_forward_log_det_jacobian` is not implemented then the following code is -used: - -```python -y = self.inverse(x, **kwargs) -return -self.inverse_log_det_jacobian(y, **kwargs) -``` - -#### Args: - -* `bijector`: Bijector instance. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str`, name given to ops managed by this object. -

forward

``` python @@ -201,8 +204,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -317,8 +320,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Kumaraswamy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Kumaraswamy.md index 203bcbad69..dd5907a029 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Kumaraswamy.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Kumaraswamy.md @@ -1,5 +1,6 @@
+ @@ -38,6 +39,33 @@ Y ~ Kumaraswamy(a, b) pdf(y; a, b, 0 <= y <= 1) = a * b * y ** (a - 1) * (1 - y**a) ** (b - 1) ``` +

__init__

+ +``` python +__init__( + concentration1=None, + concentration0=None, + validate_args=False, + name='kumaraswamy' +) +``` + +Instantiates the `Kumaraswamy` bijector. + +#### Args: + +* `concentration1`: Python `float` scalar indicating the transform power, + i.e., `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)` where `a` is + `concentration1`. +* `concentration0`: Python `float` scalar indicating the transform power, + i.e., `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)` where `b` is + `concentration0`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

concentration0

@@ -87,31 +115,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - concentration1=None, - concentration0=None, - validate_args=False, - name='kumaraswamy' -) -``` - -Instantiates the `Kumaraswamy` bijector. - -#### Args: - -* `concentration1`: Python `float` scalar indicating the transform power, - i.e., `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)` where `a` is - `concentration1`. -* `concentration0`: Python `float` scalar indicating the transform power, - i.e., `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)` where `b` is - `concentration0`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -202,8 +205,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -318,8 +321,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MaskedAutoregressiveFlow.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MaskedAutoregressiveFlow.md index c322ca1e6e..457c0c2253 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MaskedAutoregressiveFlow.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MaskedAutoregressiveFlow.md @@ -1,5 +1,6 @@
+ @@ -166,6 +167,45 @@ maf_no_scale_hidden2 = tfd.TransformedDistribution( Autoregressive Flow for Density Estimation. In _Neural Information Processing Systems_, 2017. https://arxiv.org/abs/1705.07057 +

__init__

+ +``` python +__init__( + shift_and_log_scale_fn, + is_constant_jacobian=False, + validate_args=False, + unroll_loop=False, + name=None +) +``` + +Creates the MaskedAutoregressiveFlow bijector. + +#### Args: + +* `shift_and_log_scale_fn`: Python `callable` which computes `shift` and + `log_scale` from both the forward domain (`x`) and the inverse domain + (`y`). Calculation must respect the "autoregressive property" (see class + docstring). Suggested default + `masked_autoregressive_default_template(hidden_layers=...)`. + Typically the function contains `tf.Variables` and is wrapped using + `tf.make_template`. Returning `None` for either (both) `shift`, + `log_scale` is equivalent to (but more efficient than) returning zero. +* `is_constant_jacobian`: Python `bool`. Default: `False`. When `True` the + implementation assumes `log_scale` does not depend on the forward domain + (`x`) or inverse domain (`y`) values. (No validation is made; + `is_constant_jacobian=False` is always safe but possibly computationally + inefficient.) +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `unroll_loop`: Python `bool` indicating whether the `tf.while_loop` in + `_forward` should be replaced with a static for loop. Requires that + the final dimension of `x` be known at graph construction time. Defaults + to `False`. +* `name`: Python `str`, name given to ops managed by this object. + + + ## Properties

dtype

@@ -207,43 +247,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - shift_and_log_scale_fn, - is_constant_jacobian=False, - validate_args=False, - unroll_loop=False, - name=None -) -``` - -Creates the MaskedAutoregressiveFlow bijector. - -#### Args: - -* `shift_and_log_scale_fn`: Python `callable` which computes `shift` and - `log_scale` from both the forward domain (`x`) and the inverse domain - (`y`). Calculation must respect the "autoregressive property" (see class - docstring). Suggested default - `masked_autoregressive_default_template(hidden_layers=...)`. - Typically the function contains `tf.Variables` and is wrapped using - `tf.make_template`. Returning `None` for either (both) `shift`, - `log_scale` is equivalent to (but more efficient than) returning zero. -* `is_constant_jacobian`: Python `bool`. Default: `False`. When `True` the - implementation assumes `log_scale` does not depend on the forward domain - (`x`) or inverse domain (`y`) values. (No validation is made; - `is_constant_jacobian=False` is always safe but possibly computationally - inefficient.) -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `unroll_loop`: Python `bool` indicating whether the `tf.while_loop` in - `_forward` should be replaced with a static for loop. Requires that - the final dimension of `x` be known at graph construction time. Defaults - to `False`. -* `name`: Python `str`, name given to ops managed by this object. -

forward

``` python @@ -334,8 +337,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -450,8 +453,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MatrixInverseTriL.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MatrixInverseTriL.md index 871389dfbd..cf5e610516 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MatrixInverseTriL.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/MatrixInverseTriL.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,25 @@ tfp.bijectors.MatrixInverseTriL().inverse(y=[[1., 0], [-2, 1]]) # Result: [[1., 0], [2, 1]], i.e., inv(y). ``` +

__init__

+ +``` python +__init__( + validate_args=False, + name='matrix_inverse_tril' +) +``` + +Instantiates the `MatrixInverseTriL` bijector. + +#### Args: + +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -85,23 +105,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='matrix_inverse_tril' -) -``` - -Instantiates the `MatrixInverseTriL` bijector. - -#### Args: - -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -192,8 +195,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -308,8 +311,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Permute.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Permute.md index 56548fee02..8b06a62ae3 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Permute.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Permute.md @@ -1,5 +1,6 @@
+ @@ -59,6 +60,43 @@ Permute(permutation=init_once( name="permutation")) ``` +

__init__

+ +``` python +__init__( + permutation, + axis=-1, + validate_args=False, + name=None +) +``` + +Creates the `Permute` bijector. + +#### Args: + +* `permutation`: An `int`-like vector-shaped `Tensor` representing the + permutation to apply to the `axis` dimension of the transformed + `Tensor`. +* `axis`: Scalar `int` `Tensor` representing the dimension over which to + `tf.gather`. `axis` must be relative to the end (reading left to right) + thus must be negative. + Default value: `-1` (i.e., right-most). +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str`, name given to ops managed by this object. + + +#### Raises: + +* `TypeError`: if `not permutation.dtype.is_integer`. +* `ValueError`: if `permutation` does not contain exactly one of each of + `{0, 1, ..., d}`. +* `NotImplementedError`: if `axis` is not known prior to graph execution. +* `NotImplementedError`: if `axis` is not negative. + + + ## Properties

axis

@@ -108,41 +146,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - permutation, - axis=-1, - validate_args=False, - name=None -) -``` - -Creates the `Permute` bijector. - -#### Args: - -* `permutation`: An `int`-like vector-shaped `Tensor` representing the - permutation to apply to the `axis` dimension of the transformed - `Tensor`. -* `axis`: Scalar `int` `Tensor` representing the dimension over which to - `tf.gather`. `axis` must be relative to the end (reading left to right) - thus must be negative. - Default value: `-1` (i.e., right-most). -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str`, name given to ops managed by this object. - - -#### Raises: - -* `TypeError`: if `not permutation.dtype.is_integer`. -* `ValueError`: if `permutation` does not contain exactly one of each of - `{0, 1, ..., d}`. -* `NotImplementedError`: if `axis` is not known prior to graph execution. -* `NotImplementedError`: if `axis` is not negative. -

forward

``` python @@ -233,8 +236,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -349,8 +352,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/PowerTransform.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/PowerTransform.md index 2f532e5aba..1e81956bfd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/PowerTransform.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/PowerTransform.md @@ -1,5 +1,6 @@
+ @@ -33,6 +34,33 @@ of this bijector. This bijector is equivalent to the `Exp` bijector when `c=0`. +

__init__

+ +``` python +__init__( + power=0.0, + validate_args=False, + name='power_transform' +) +``` + +Instantiates the `PowerTransform` bijector. + +#### Args: + +* `power`: Python `float` scalar indicating the transform power, i.e., + `Y = g(X) = (1 + X * c)**(1 / c)` where `c` is the `power`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + +#### Raises: + +* `ValueError`: if `power < 0` or is not known statically. + + + ## Properties

dtype

@@ -78,31 +106,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - power=0.0, - validate_args=False, - name='power_transform' -) -``` - -Instantiates the `PowerTransform` bijector. - -#### Args: - -* `power`: Python `float` scalar indicating the transform power, i.e., - `Y = g(X) = (1 + X * c)**(1 / c)` where `c` is the `power`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. - - -#### Raises: - -* `ValueError`: if `power < 0` or is not known statically. -

forward

``` python @@ -193,8 +196,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -309,8 +312,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/RealNVP.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/RealNVP.md index ea257ba27c..11104473ae 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/RealNVP.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/RealNVP.md @@ -1,5 +1,6 @@
+ @@ -114,6 +115,49 @@ For more examples, see [Jang (2018)][3]. Autoregressive Flow for Density Estimation. In _Neural Information Processing Systems_, 2017. https://arxiv.org/abs/1705.07057 +

__init__

+ +``` python +__init__( + num_masked, + shift_and_log_scale_fn, + is_constant_jacobian=False, + validate_args=False, + name=None +) +``` + +Creates the Real NVP or NICE bijector. + +#### Args: + +* `num_masked`: Python `int` indicating that the first `d` units of the event + should be masked. Must be in the closed interval `[1, D-1]`, where `D` + is the event size of the base distribution. +* `shift_and_log_scale_fn`: Python `callable` which computes `shift` and + `log_scale` from both the forward domain (`x`) and the inverse domain + (`y`). Calculation must respect the "autoregressive property" (see class + docstring). Suggested default + `masked_autoregressive_default_template(hidden_layers=...)`. + Typically the function contains `tf.Variables` and is wrapped using + `tf.make_template`. Returning `None` for either (both) `shift`, + `log_scale` is equivalent to (but more efficient than) returning zero. +* `is_constant_jacobian`: Python `bool`. Default: `False`. When `True` the + implementation assumes `log_scale` does not depend on the forward domain + (`x`) or inverse domain (`y`) values. (No validation is made; + `is_constant_jacobian=False` is always safe but possibly computationally + inefficient.) +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str`, name given to ops managed by this object. + + +#### Raises: + +* `ValueError`: If num_masked < 1. + + + ## Properties

dtype

@@ -155,47 +199,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - num_masked, - shift_and_log_scale_fn, - is_constant_jacobian=False, - validate_args=False, - name=None -) -``` - -Creates the Real NVP or NICE bijector. - -#### Args: - -* `num_masked`: Python `int` indicating that the first `d` units of the event - should be masked. Must be in the closed interval `[1, D-1]`, where `D` - is the event size of the base distribution. -* `shift_and_log_scale_fn`: Python `callable` which computes `shift` and - `log_scale` from both the forward domain (`x`) and the inverse domain - (`y`). Calculation must respect the "autoregressive property" (see class - docstring). Suggested default - `masked_autoregressive_default_template(hidden_layers=...)`. - Typically the function contains `tf.Variables` and is wrapped using - `tf.make_template`. Returning `None` for either (both) `shift`, - `log_scale` is equivalent to (but more efficient than) returning zero. -* `is_constant_jacobian`: Python `bool`. Default: `False`. When `True` the - implementation assumes `log_scale` does not depend on the forward domain - (`x`) or inverse domain (`y`) values. (No validation is made; - `is_constant_jacobian=False` is always safe but possibly computationally - inefficient.) -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str`, name given to ops managed by this object. - - -#### Raises: - -* `ValueError`: If num_masked < 1. -

forward

``` python @@ -286,8 +289,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -402,8 +405,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Reshape.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Reshape.md index bba24d71b4..bcaf442816 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Reshape.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Reshape.md @@ -1,5 +1,6 @@
+ @@ -109,6 +110,42 @@ bijector.forward_event_shape(tf.TensorShape([5, 2, 3, 7])) # Either policy ==> (5, None, None) ``` +

__init__

+ +``` python +__init__( + event_shape_out, + event_shape_in=(-1,), + validate_args=False, + name=None +) +``` + +Creates a `Reshape` bijector. + +#### Args: + +* `event_shape_out`: An `int`-like vector-shaped `Tensor` + representing the event shape of the transformed output. +* `event_shape_in`: An optional `int`-like vector-shape `Tensor` + representing the event shape of the input. This is required in + order to define inverse operations; the default of (-1,) + assumes a vector-shaped input. +* `validate_args`: Python `bool` indicating whether arguments should + be checked for correctness. +* `name`: Python `str`, name given to ops managed by this object. + + +#### Raises: + +* `TypeError`: if either `event_shape_in` or `event_shape_out` has + non-integer `dtype`. +* `ValueError`: if either of `event_shape_in` or `event_shape_out` + has non-vector shape (`rank > 1`), or if their sizes do not + match. + + + ## Properties

dtype

@@ -150,40 +187,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - event_shape_out, - event_shape_in=(-1,), - validate_args=False, - name=None -) -``` - -Creates a `Reshape` bijector. - -#### Args: - -* `event_shape_out`: An `int`-like vector-shaped `Tensor` - representing the event shape of the transformed output. -* `event_shape_in`: An optional `int`-like vector-shape `Tensor` - representing the event shape of the input. This is required in - order to define inverse operations; the default of (-1,) - assumes a vector-shaped input. -* `validate_args`: Python `bool` indicating whether arguments should - be checked for correctness. -* `name`: Python `str`, name given to ops managed by this object. - - -#### Raises: - -* `TypeError`: if either `event_shape_in` or `event_shape_out` has - non-integer `dtype`. -* `ValueError`: if either of `event_shape_in` or `event_shape_out` - has non-vector shape (`rank > 1`), or if their sizes do not - match. -

forward

``` python @@ -274,8 +277,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -390,8 +393,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ScaleTriL.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ScaleTriL.md index 10adb3250b..b35670f225 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ScaleTriL.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/ScaleTriL.md @@ -1,5 +1,6 @@
+ @@ -70,6 +71,38 @@ b = tfb.ScaleTriL( diag_shift=None) ``` +

__init__

+ +``` python +__init__( + diag_bijector=None, + diag_shift=1e-05, + validate_args=False, + name='scale_tril' +) +``` + +Instantiates the `ScaleTriL` bijector. + +#### Args: + +* `diag_bijector`: `Bijector` instance, used to transform the output diagonal + to be positive. + Default value: `None` (i.e., `tfb.Softplus()`). +* `diag_shift`: Float value broadcastable and added to all diagonal entries + after applying the `diag_bijector`. Setting a positive + value forces the output diagonal entries to be positive, but + prevents inverting the transformation for matrices with + diagonal entries less than this value. + Default value: `1e-5` (i.e., no shift is applied). +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. + Default value: `False` (i.e., arguments are not validated). +* `name`: Python `str` name given to ops managed by this object. + Default value: `scale_tril`. + + + ## Properties

bijectors

@@ -115,36 +148,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - diag_bijector=None, - diag_shift=1e-05, - validate_args=False, - name='scale_tril' -) -``` - -Instantiates the `ScaleTriL` bijector. - -#### Args: - -* `diag_bijector`: `Bijector` instance, used to transform the output diagonal - to be positive. - Default value: `None` (i.e., `tfb.Softplus()`). -* `diag_shift`: Float value broadcastable and added to all diagonal entries - after applying the `diag_bijector`. Setting a positive - value forces the output diagonal entries to be positive, but - prevents inverting the transformation for matrices with - diagonal entries less than this value. - Default value: `1e-5` (i.e., no shift is applied). -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. - Default value: `False` (i.e., arguments are not validated). -* `name`: Python `str` name given to ops managed by this object. - Default value: `scale_tril`. -

forward

``` python @@ -235,8 +238,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -351,8 +354,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Sigmoid.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Sigmoid.md index ffc2e9dd24..a94c737c9d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Sigmoid.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Sigmoid.md @@ -1,5 +1,6 @@
+ @@ -26,6 +27,19 @@ Inherits From: [`Bijector`](../../tfp/bijectors/Bijector.md) Bijector which computes `Y = g(X) = 1 / (1 + exp(-X))`. +

__init__

+ +``` python +__init__( + validate_args=False, + name='sigmoid' +) +``` + + + + + ## Properties

dtype

@@ -67,17 +81,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='sigmoid' -) -``` - - -

forward

``` python @@ -168,8 +171,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -284,8 +287,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SinhArcsinh.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SinhArcsinh.md index 4f608ec4f4..c50e5968a4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SinhArcsinh.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SinhArcsinh.md @@ -1,5 +1,6 @@
+ @@ -57,6 +58,31 @@ To see the argument about the tails, note that for `|X| >> 1` and `|X| >> (|skewness| * tailweight)**tailweight`, we have `Y approx 0.5 X**tailweight e**(sign(X) skewness * tailweight)`. +

__init__

+ +``` python +__init__( + skewness=None, + tailweight=None, + validate_args=False, + name='SinhArcsinh' +) +``` + +Instantiates the `SinhArcsinh` bijector. + +#### Args: + +* `skewness`: Skewness parameter. Float-type `Tensor`. Default is `0` + of type `float32`. +* `tailweight`: Tailweight parameter. Positive `Tensor` of same `dtype` as + `skewness` and broadcastable `shape`. Default is `1` of type `float32`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -106,29 +132,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - skewness=None, - tailweight=None, - validate_args=False, - name='SinhArcsinh' -) -``` - -Instantiates the `SinhArcsinh` bijector. - -#### Args: - -* `skewness`: Skewness parameter. Float-type `Tensor`. Default is `0` - of type `float32`. -* `tailweight`: Tailweight parameter. Positive `Tensor` of same `dtype` as - `skewness` and broadcastable `shape`. Default is `1` of type `float32`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -219,8 +222,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -335,8 +338,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SoftmaxCentered.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SoftmaxCentered.md index 47439e0f35..e874c47602 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SoftmaxCentered.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/SoftmaxCentered.md @@ -1,5 +1,6 @@
+ @@ -49,6 +50,19 @@ https://en.wikipedia.org/wiki/Invariance_of_domain) theorem implies this implementation is not a bijection. However, the appended dimension makes the (forward) image non-open and the theorem does not directly apply. +

__init__

+ +``` python +__init__( + validate_args=False, + name='softmax_centered' +) +``` + + + + + ## Properties

dtype

@@ -90,17 +104,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='softmax_centered' -) -``` - - -

forward

``` python @@ -191,8 +194,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -307,8 +310,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softplus.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softplus.md index 16cca8bdb5..4df23bd6b8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softplus.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softplus.md @@ -1,5 +1,6 @@
+ @@ -66,6 +67,21 @@ approaching `max(0, x)`. Note: log(.) and exp(.) are applied element-wise but the Jacobian is a reduction over the event space. +

__init__

+ +``` python +__init__( + *args, + **kwargs +) +``` + +##### `kwargs`: + +* `hinge_softness`: Nonzero floating point `Tensor`. Controls the softness of what would otherwise be a kink at the origin. Default is 1.0 + + + ## Properties

dtype

@@ -111,19 +127,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - *args, - **kwargs -) -``` - -##### `kwargs`: - -* `hinge_softness`: Nonzero floating point `Tensor`. Controls the softness of what would otherwise be a kink at the origin. Default is 1.0 -

forward

``` python @@ -214,8 +217,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -330,8 +333,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softsign.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softsign.md index 464dc9666c..46a24ebe3d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softsign.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Softsign.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,19 @@ x / (1 + abs(x)) == softsign.forward(x) x / (1 - abs(x)) == softsign.inverse(x) ``` +

__init__

+ +``` python +__init__( + validate_args=False, + name='softsign' +) +``` + + + + + ## Properties

dtype

@@ -85,17 +99,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='softsign' -) -``` - - -

forward

``` python @@ -186,8 +189,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -302,8 +305,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Square.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Square.md index d85ad76094..85d24094b2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Square.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Square.md @@ -1,5 +1,6 @@
+ @@ -39,6 +40,25 @@ bijector.Square().inverse(y=[[1., 4], [9, 1]]) # Result: [[1., 2], [3, 1]], i.e., sqrt(y). ``` +

__init__

+ +``` python +__init__( + validate_args=False, + name='square' +) +``` + +Instantiates the `Square` bijector. + +#### Args: + +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -80,23 +100,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='square' -) -``` - -Instantiates the `Square` bijector. - -#### Args: - -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -187,8 +190,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -303,8 +306,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Tanh.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Tanh.md index dcf73d3551..a6a6fe26fb 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Tanh.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Tanh.md @@ -1,5 +1,6 @@
+ @@ -37,6 +38,19 @@ tfb.Chain([tfb.Affine(shift=-1, scale=2.), However, using the `Tanh` bijector directly is slightly faster and more numerically stable. +

__init__

+ +``` python +__init__( + validate_args=False, + name='tanh' +) +``` + + + + + ## Properties

dtype

@@ -78,17 +92,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - validate_args=False, - name='tanh' -) -``` - - -

forward

``` python @@ -179,8 +182,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -295,8 +298,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/TransformDiagonal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/TransformDiagonal.md index bbfeed8b75..d4d666aef6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/TransformDiagonal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/TransformDiagonal.md @@ -1,5 +1,6 @@
+ @@ -37,6 +38,27 @@ b.forward([[1., 0.], [0., 2.718]] ``` +

__init__

+ +``` python +__init__( + diag_bijector, + validate_args=False, + name='transform_diagonal' +) +``` + +Instantiates the `TransformDiagonal` bijector. + +#### Args: + +* `diag_bijector`: `Bijector` instance used to transform the diagonal. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

dtype

@@ -78,25 +100,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - diag_bijector, - validate_args=False, - name='transform_diagonal' -) -``` - -Instantiates the `TransformDiagonal` bijector. - -#### Args: - -* `diag_bijector`: `Bijector` instance used to transform the diagonal. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -187,8 +190,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -303,8 +306,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Transpose.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Transpose.md index 248b426169..b1e0a32d8d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Transpose.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Transpose.md @@ -1,5 +1,6 @@
+ @@ -82,6 +83,48 @@ tfp.bijectors.Transpose(rightmost_transposed_ndims=2).inverse( # ] ``` +

__init__

+ +``` python +__init__( + perm=None, + rightmost_transposed_ndims=None, + validate_args=False, + name='transpose' +) +``` + +Instantiates the `Transpose` bijector. + +#### Args: + +* `perm`: Positive `int32` vector-shaped `Tensor` representing permutation of + rightmost dims (for forward transformation). Note that the `0`th index + represents the first of the rightmost dims and the largest value must be + `rightmost_transposed_ndims - 1` and corresponds to `tf.rank(x) - 1`. + Only one of `perm` and `rightmost_transposed_ndims` can (and must) be + specified. + Default value: + `tf.range(start=rightmost_transposed_ndims, limit=-1, delta=-1)`. +* `rightmost_transposed_ndims`: Positive `int32` scalar-shaped `Tensor` + representing the number of rightmost dimensions to permute. + Only one of `perm` and `rightmost_transposed_ndims` can (and must) be + specified. + Default value: `tf.size(perm)`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + +#### Raises: + +* `ValueError`: if both or neither `perm` and `rightmost_transposed_ndims` are + specified. +* `NotImplementedError`: if `rightmost_transposed_ndims` is not known prior to + graph execution. + + + ## Properties

dtype

@@ -131,46 +174,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - perm=None, - rightmost_transposed_ndims=None, - validate_args=False, - name='transpose' -) -``` - -Instantiates the `Transpose` bijector. - -#### Args: - -* `perm`: Positive `int32` vector-shaped `Tensor` representing permutation of - rightmost dims (for forward transformation). Note that the `0`th index - represents the first of the rightmost dims and the largest value must be - `rightmost_transposed_ndims - 1` and corresponds to `tf.rank(x) - 1`. - Only one of `perm` and `rightmost_transposed_ndims` can (and must) be - specified. - Default value: - `tf.range(start=rightmost_transposed_ndims, limit=-1, delta=-1)`. -* `rightmost_transposed_ndims`: Positive `int32` scalar-shaped `Tensor` - representing the number of rightmost dimensions to permute. - Only one of `perm` and `rightmost_transposed_ndims` can (and must) be - specified. - Default value: `tf.size(perm)`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. - - -#### Raises: - -* `ValueError`: if both or neither `perm` and `rightmost_transposed_ndims` are - specified. -* `NotImplementedError`: if `rightmost_transposed_ndims` is not known prior to - graph execution. -

forward

``` python @@ -261,8 +264,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -377,8 +380,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Weibull.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Weibull.md index 0f32afb8b0..4a6b97b491 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Weibull.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/Weibull.md @@ -1,5 +1,6 @@
+ @@ -40,6 +41,33 @@ pdf(y; scale, concentration, y >= 0) = (scale / concentration) * ( -(y / scale) ** concentration) ``` +

__init__

+ +``` python +__init__( + scale=1.0, + concentration=1.0, + validate_args=False, + name='weibull' +) +``` + +Instantiates the `Weibull` bijector. + +#### Args: + +* `scale`: Positive Float-type `Tensor` that is the same dtype and is + broadcastable with `concentration`. + This is `l` in `Y = g(X) = 1 - exp((-x / l) ** k)`. +* `concentration`: Positive Float-type `Tensor` that is the same dtype and is + broadcastable with `scale`. + This is `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`. +* `validate_args`: Python `bool` indicating whether arguments should be + checked for correctness. +* `name`: Python `str` name given to ops managed by this object. + + + ## Properties

concentration

@@ -89,31 +117,6 @@ Returns True if Tensor arguments will be validated. ## Methods -

__init__

- -``` python -__init__( - scale=1.0, - concentration=1.0, - validate_args=False, - name='weibull' -) -``` - -Instantiates the `Weibull` bijector. - -#### Args: - -* `scale`: Positive Float-type `Tensor` that is the same dtype and is - broadcastable with `concentration`. - This is `l` in `Y = g(X) = 1 - exp((-x / l) ** k)`. -* `concentration`: Positive Float-type `Tensor` that is the same dtype and is - broadcastable with `scale`. - This is `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`. -* `validate_args`: Python `bool` indicating whether arguments should be - checked for correctness. -* `name`: Python `str` name given to ops managed by this object. -

forward

``` python @@ -204,8 +207,8 @@ Returns both the forward_log_det_jacobian. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.forward_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `x.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. @@ -320,8 +323,8 @@ evaluated at `g^{-1}(y)`. * `event_ndims`: Number of dimensions in the probabilistic events being transformed. Must be greater than or equal to `self.inverse_min_event_ndims`. The result is summed over the final - dimensions to produce a scalar Jacobian determinant for each event, - i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + dimensions to produce a scalar Jacobian determinant for each event, i.e. + it has shape `y.shape.ndims - event_ndims` dimensions. * `name`: The name to give this op. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_autoregressive_default_template.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_autoregressive_default_template.md index feecd26bfe..96b452b9a7 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_autoregressive_default_template.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_autoregressive_default_template.md @@ -1,5 +1,6 @@
+
# tfp.bijectors.masked_autoregressive_default_template diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_dense.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_dense.md index b99c861686..b8972da1a0 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_dense.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/masked_dense.md @@ -1,5 +1,6 @@
+
# tfp.bijectors.masked_dense diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/real_nvp_default_template.md b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/real_nvp_default_template.md index 1097c8ada3..59fafe7851 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/real_nvp_default_template.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/bijectors/real_nvp_default_template.md @@ -1,5 +1,6 @@
+
# tfp.bijectors.real_nvp_default_template diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions.md index d4177f2b05..1705b025f1 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions.md @@ -1,5 +1,6 @@
+ @@ -61,6 +62,10 @@ Statistical distributions and bijective transformations. [`class Geometric`](../tfp/distributions/Geometric.md): Geometric distribution. +[`class Gumbel`](../tfp/distributions/Gumbel.md): The scalar Gumbel distribution with location `loc` and `scale` parameters. + +[`class HalfCauchy`](../tfp/distributions/HalfCauchy.md): Half-Cauchy distribution. + [`class HalfNormal`](../tfp/distributions/HalfNormal.md): The Half Normal distribution with scale `scale`. [`class Independent`](../tfp/distributions/Independent.md): Independent distribution from batch of distributions. @@ -69,6 +74,8 @@ Statistical distributions and bijective transformations. [`class InverseGammaWithSoftplusConcentrationRate`](../tfp/distributions/InverseGammaWithSoftplusConcentrationRate.md): `InverseGamma` with softplus of `concentration` and `rate`. +[`class InverseGaussian`](../tfp/distributions/InverseGaussian.md): Inverse Gaussian distribution. + [`class Kumaraswamy`](../tfp/distributions/Kumaraswamy.md): Kumaraswamy distribution. [`class LKJ`](../tfp/distributions/LKJ.md): The LKJ distribution on correlation matrices. @@ -109,6 +116,8 @@ Statistical distributions and bijective transformations. [`class OneHotCategorical`](../tfp/distributions/OneHotCategorical.md): OneHotCategorical distribution. +[`class Pareto`](../tfp/distributions/Pareto.md): Pareto distribution. + [`class Poisson`](../tfp/distributions/Poisson.md): Poisson distribution. [`class PoissonLogNormalQuadratureCompound`](../tfp/distributions/PoissonLogNormalQuadratureCompound.md): `PoissonLogNormalQuadratureCompound` distribution. @@ -147,6 +156,8 @@ Statistical distributions and bijective transformations. [`class VectorSinhArcsinhDiag`](../tfp/distributions/VectorSinhArcsinhDiag.md): The (diagonal) SinhArcsinh transformation of a distribution on `R^k`. +[`class VonMises`](../tfp/distributions/VonMises.md): The von Mises distribution over angles. + [`class VonMisesFisher`](../tfp/distributions/VonMisesFisher.md): The von Mises-Fisher distribution over unit vectors on `S^{n-1}`. [`class Wishart`](../tfp/distributions/Wishart.md): The matrix Wishart distribution on positive definite matrices. @@ -191,9 +202,9 @@ Statistical distributions and bijective transformations. ## Other Members -`FULLY_REPARAMETERIZED` +

FULLY_REPARAMETERIZED

-`NOT_REPARAMETERIZED` +

NOT_REPARAMETERIZED

-`__all__` +

__all__

diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Autoregressive.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Autoregressive.md index 5dcd33dffd..237e23f736 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Autoregressive.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Autoregressive.md @@ -1,5 +1,6 @@
+ @@ -124,6 +125,54 @@ prob_x = ar.prob(x) PixelCNN Decoders. In _Neural Information Processing Systems_, 2016. https://arxiv.org/abs/1606.05328 +

__init__

+ +``` python +__init__( + distribution_fn, + sample0=None, + num_steps=None, + validate_args=False, + allow_nan_stats=True, + name='Autoregressive' +) +``` + +Construct an `Autoregressive` distribution. + +#### Args: + +* `distribution_fn`: Python `callable` which constructs a + `tf.distributions.Distribution`-like instance from a `Tensor` (e.g., + `sample0`). The function must respect the "autoregressive property", + i.e., there exists a permutation of event such that each coordinate is a + diffeomorphic function of on preceding coordinates. +* `sample0`: Initial input to `distribution_fn`; used to + build the distribution in `__init__` which in turn specifies this + distribution's properties, e.g., `event_shape`, `batch_shape`, `dtype`. + If unspecified, then `distribution_fn` should be default constructable. +* `num_steps`: Number of times `distribution_fn` is composed from samples, + e.g., `num_steps=2` implies + `distribution_fn(distribution_fn(sample0).sample(n)).sample()`. +* `validate_args`: Python `bool`. Whether to validate input with asserts. + If `validate_args` is `False`, and the inputs are invalid, + correct behavior is not guaranteed. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: "Autoregressive". + + +#### Raises: + +* `ValueError`: if `num_steps` and + `distribution_fn(sample0).event_shape.num_elements()` are both `None`. +* `ValueError`: if `num_steps < 1`. + + + ## Properties

allow_nan_stats

@@ -213,52 +262,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - distribution_fn, - sample0=None, - num_steps=None, - validate_args=False, - allow_nan_stats=True, - name='Autoregressive' -) -``` - -Construct an `Autoregressive` distribution. - -#### Args: - -* `distribution_fn`: Python `callable` which constructs a - `tf.distributions.Distribution`-like instance from a `Tensor` (e.g., - `sample0`). The function must respect the "autoregressive property", - i.e., there exists a permutation of event such that each coordinate is a - diffeomorphic function of on preceding coordinates. -* `sample0`: Initial input to `distribution_fn`; used to - build the distribution in `__init__` which in turn specifies this - distribution's properties, e.g., `event_shape`, `batch_shape`, `dtype`. - If unspecified, then `distribution_fn` should be default constructable. -* `num_steps`: Number of times `distribution_fn` is composed from samples, - e.g., `num_steps=2` implies - `distribution_fn(distribution_fn(sample0).sample(n)).sample()`. -* `validate_args`: Python `bool`. Whether to validate input with asserts. - If `validate_args` is `False`, and the inputs are invalid, - correct behavior is not guaranteed. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - Default value: "Autoregressive". - - -#### Raises: - -* `ValueError`: if `num_steps` and - `distribution_fn(sample0).event_shape.num_elements()` are both `None`. -* `ValueError`: if `num_steps < 1`. -

batch_shape_tensor

``` python @@ -398,7 +401,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -492,7 +495,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BatchReshape.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BatchReshape.md index a5a1ea9ca8..d14ae127fa 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BatchReshape.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BatchReshape.md @@ -1,5 +1,6 @@
+ @@ -74,6 +75,48 @@ reshape_mvn.log_prob(x).shape # ==> [4, 5, 1, 2, 3] == sample_shape + new_batch_shape ``` +

__init__

+ +``` python +__init__( + distribution, + batch_shape, + validate_args=False, + allow_nan_stats=True, + name=None +) +``` + +Construct BatchReshape distribution. + +#### Args: + +* `distribution`: The base distribution instance to reshape. Typically an + instance of `Distribution`. +* `batch_shape`: Positive `int`-like vector-shaped `Tensor` representing + the new shape of the batch dimensions. Up to one dimension may contain + `-1`, meaning the remainder of the batch size. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: The name to give Ops created by the initializer. + Default value: `"BatchReshape" + distribution.name`. + + +#### Raises: + +* `ValueError`: if `batch_shape` is not a vector. +* `ValueError`: if `batch_shape` has non-positive elements. +* `ValueError`: if `batch_shape` size is not the same as a + `distribution.batch_shape` size. + + + ## Properties

allow_nan_stats

@@ -151,46 +194,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - distribution, - batch_shape, - validate_args=False, - allow_nan_stats=True, - name=None -) -``` - -Construct BatchReshape distribution. - -#### Args: - -* `distribution`: The base distribution instance to reshape. Typically an - instance of `Distribution`. -* `batch_shape`: Positive `int`-like vector-shaped `Tensor` representing - the new shape of the batch dimensions. Up to one dimension may contain - `-1`, meaning the remainder of the batch size. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: The name to give Ops created by the initializer. - Default value: `"BatchReshape" + distribution.name`. - - -#### Raises: - -* `ValueError`: if `batch_shape` is not a vector. -* `ValueError`: if `batch_shape` has non-positive elements. -* `ValueError`: if `batch_shape` size is not the same as a - `distribution.batch_shape` size. -

batch_shape_tensor

``` python @@ -330,7 +333,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -424,7 +427,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Bernoulli.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Bernoulli.md index 493067fa43..02d8f58051 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Bernoulli.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Bernoulli.md @@ -1,5 +1,6 @@
+ @@ -47,6 +48,49 @@ Bernoulli distribution. The Bernoulli distribution with `probs` parameter, i.e., the probability of a `1` outcome (vs a `0` outcome). +

__init__

+ +``` python +__init__( + logits=None, + probs=None, + dtype=dtypes.int32, + validate_args=False, + allow_nan_stats=True, + name='Bernoulli' +) +``` + +Construct Bernoulli distributions. + +#### Args: + +* `logits`: An N-D `Tensor` representing the log-odds of a `1` event. Each + entry in the `Tensor` parametrizes an independent Bernoulli distribution + where the probability of an event is sigmoid(logits). Only one of + `logits` or `probs` should be passed in. +* `probs`: An N-D `Tensor` representing the probability of a `1` + event. Each entry in the `Tensor` parameterizes an independent + Bernoulli distribution. Only one of `logits` or `probs` should be passed + in. +* `dtype`: The type of the event samples. Default: `int32`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: If p and logits are passed, or if neither are passed. + + + ## Properties

allow_nan_stats

@@ -128,47 +172,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - logits=None, - probs=None, - dtype=dtypes.int32, - validate_args=False, - allow_nan_stats=True, - name='Bernoulli' -) -``` - -Construct Bernoulli distributions. - -#### Args: - -* `logits`: An N-D `Tensor` representing the log-odds of a `1` event. Each - entry in the `Tensor` parametrizes an independent Bernoulli distribution - where the probability of an event is sigmoid(logits). Only one of - `logits` or `probs` should be passed in. -* `probs`: An N-D `Tensor` representing the probability of a `1` - event. Each entry in the `Tensor` parameterizes an independent - Bernoulli distribution. Only one of `logits` or `probs` should be passed - in. -* `dtype`: The type of the event samples. Default: `int32`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: If p and logits are passed, or if neither are passed. -

batch_shape_tensor

``` python @@ -308,7 +311,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -402,7 +405,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Beta.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Beta.md index 3585767041..5cfe3c99a5 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Beta.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Beta.md @@ -1,5 +1,6 @@
+ @@ -93,10 +94,13 @@ Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498) #### Examples ```python +import tensorflow_probability as tfp +tfd = tfp.distributions + # Create a batch of three Beta distributions. alpha = [1, 2, 3] beta = [1, 2, 3] -dist = tf.distributions.Beta(alpha, beta) +dist = tfd.Beta(alpha, beta) dist.sample([4, 5]) # Shape [4, 5, 3] @@ -112,7 +116,7 @@ dist.prob(x) # Shape [2, 3] # Create batch_shape=[2, 3] via parameter broadcast: alpha = [[1.], [2]] # Shape [2, 1] beta = [3., 4, 5] # Shape [3] -dist = tf.distributions.Beta(alpha, beta) +dist = tfd.Beta(alpha, beta) # alpha broadcast as: [[1., 1, 1,], # [2, 2, 2]] @@ -133,13 +137,48 @@ Compute the gradients of samples w.r.t. the parameters: ```python alpha = tf.constant(1.0) beta = tf.constant(2.0) -dist = tf.distributions.Beta(alpha, beta) +dist = tfd.Beta(alpha, beta) samples = dist.sample(5) # Shape [5] loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function # Unbiased stochastic gradients of the loss function grads = tf.gradients(loss, [alpha, beta]) ``` +

__init__

+ +``` python +__init__( + concentration1=None, + concentration0=None, + validate_args=False, + allow_nan_stats=True, + name='Beta' +) +``` + +Initialize a batch of Beta distributions. + +#### Args: + +* `concentration1`: Positive floating-point `Tensor` indicating mean + number of successes; aka "alpha". Implies `self.dtype` and + `self.batch_shape`, i.e., + `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. +* `concentration0`: Positive floating-point `Tensor` indicating mean + number of failures; aka "beta". Otherwise has same semantics as + `concentration1`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -225,39 +264,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration1=None, - concentration0=None, - validate_args=False, - allow_nan_stats=True, - name='Beta' -) -``` - -Initialize a batch of Beta distributions. - -#### Args: - -* `concentration1`: Positive floating-point `Tensor` indicating mean - number of successes; aka "alpha". Implies `self.dtype` and - `self.batch_shape`, i.e., - `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. -* `concentration0`: Positive floating-point `Tensor` indicating mean - number of failures; aka "beta". Otherwise has same semantics as - `concentration1`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -403,7 +409,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -497,7 +503,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BetaWithSoftplusConcentration.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BetaWithSoftplusConcentration.md index 1d36254ead..bc22dd05e9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BetaWithSoftplusConcentration.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/BetaWithSoftplusConcentration.md @@ -1,5 +1,6 @@
+ @@ -45,6 +46,22 @@ Inherits From: [`Beta`](../../tfp/distributions/Beta.md) Beta with softplus transform of `concentration1` and `concentration0`. +

__init__

+ +``` python +__init__( + concentration1, + concentration0, + validate_args=False, + allow_nan_stats=True, + name='BetaWithSoftplusConcentration' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -130,20 +147,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration1, - concentration0, - validate_args=False, - allow_nan_stats=True, - name='BetaWithSoftplusConcentration' -) -``` - - -

batch_shape_tensor

``` python @@ -289,7 +292,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -383,7 +386,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Binomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Binomial.md index b70df73bdc..c22806660e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Binomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Binomial.md @@ -1,5 +1,6 @@
+ @@ -107,6 +108,48 @@ counts = [[...]] # Shape [5, 7, 3] dist.prob(counts) # Shape [5, 7, 3] ``` +

__init__

+ +``` python +__init__( + total_count, + logits=None, + probs=None, + validate_args=False, + allow_nan_stats=True, + name='Binomial' +) +``` + +Initialize a batch of Binomial distributions. + +#### Args: + +* `total_count`: Non-negative floating point tensor with shape broadcastable + to `[N1,..., Nm]` with `m >= 0` and the same dtype as `probs` or + `logits`. Defines this as a batch of `N1 x ... x Nm` different Binomial + distributions. Its components should be equal to integer values. +* `logits`: Floating point tensor representing the log-odds of a + positive event with shape broadcastable to `[N1,..., Nm]` `m >= 0`, and + the same dtype as `total_count`. Each entry represents logits for the + probability of success for independent Binomial distributions. Only one + of `logits` or `probs` should be passed in. +* `probs`: Positive floating point tensor with shape broadcastable to + `[N1,..., Nm]` `m >= 0`, `probs in [0, 1]`. Each entry represents the + probability of success for independent Binomial distributions. Only one + of `logits` or `probs` should be passed in. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -192,46 +235,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - total_count, - logits=None, - probs=None, - validate_args=False, - allow_nan_stats=True, - name='Binomial' -) -``` - -Initialize a batch of Binomial distributions. - -#### Args: - -* `total_count`: Non-negative floating point tensor with shape broadcastable - to `[N1,..., Nm]` with `m >= 0` and the same dtype as `probs` or - `logits`. Defines this as a batch of `N1 x ... x Nm` different Binomial - distributions. Its components should be equal to integer values. -* `logits`: Floating point tensor representing the log-odds of a - positive event with shape broadcastable to `[N1,..., Nm]` `m >= 0`, and - the same dtype as `total_count`. Each entry represents logits for the - probability of success for independent Binomial distributions. Only one - of `logits` or `probs` should be passed in. -* `probs`: Positive floating point tensor with shape broadcastable to - `[N1,..., Nm]` `m >= 0`, `probs in [0, 1]`. Each entry represents the - probability of success for independent Binomial distributions. Only one - of `logits` or `probs` should be passed in. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -371,7 +374,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -465,7 +468,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Categorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Categorical.md index 7d5f31dc8a..1ce0ffbf34 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Categorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Categorical.md @@ -1,5 +1,6 @@
+ @@ -52,7 +53,7 @@ log-probabilities of a set of `K` classes. It is defined over the integers The Categorical distribution is closely related to the `OneHotCategorical` and `Multinomial` distributions. The Categorical distribution can be intuited as generating samples according to `argmax{ OneHotCategorical(probs) }` itself -being identical to `argmax{ Multinomial(probs, total_count=1) }. +being identical to `argmax{ Multinomial(probs, total_count=1) }`. #### Mathematical Details @@ -66,7 +67,7 @@ pmf(k; pi) = prod_j pi_j**[k == j] The number of classes, `K`, must not exceed: - the largest integer representable by `self.dtype`, i.e., - `2**(mantissa_bits+1)` (IEE754), + `2**(mantissa_bits+1)` (IEEE 754), - the maximum `Tensor` index, i.e., `2**31-1`. In other words, @@ -130,6 +131,46 @@ counts = [[...]] # Shape [5, 7, 3] dist.prob(counts) # Shape [5, 7, 3] ``` +

__init__

+ +``` python +__init__( + logits=None, + probs=None, + dtype=dtypes.int32, + validate_args=False, + allow_nan_stats=True, + name='Categorical' +) +``` + +Initialize Categorical distributions using class log-probabilities. + +#### Args: + +* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities + of a set of Categorical distributions. The first `N - 1` dimensions + index into a batch of independent distributions and the last dimension + represents a vector of logits for each class. Only one of `logits` or + `probs` should be passed in. +* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities + of a set of Categorical distributions. The first `N - 1` dimensions + index into a batch of independent distributions and the last dimension + represents a vector of probabilities for each class. Only one of + `logits` or `probs` should be passed in. +* `dtype`: The type of the event samples (default: int32). +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -215,44 +256,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - logits=None, - probs=None, - dtype=dtypes.int32, - validate_args=False, - allow_nan_stats=True, - name='Categorical' -) -``` - -Initialize Categorical distributions using class log-probabilities. - -#### Args: - -* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities - of a set of Categorical distributions. The first `N - 1` dimensions - index into a batch of independent distributions and the last dimension - represents a vector of logits for each class. Only one of `logits` or - `probs` should be passed in. -* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities - of a set of Categorical distributions. The first `N - 1` dimensions - index into a batch of independent distributions and the last dimension - represents a vector of probabilities for each class. Only one of - `logits` or `probs` should be passed in. -* `dtype`: The type of the event samples (default: int32). -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -392,7 +395,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -486,7 +489,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Cauchy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Cauchy.md index 44cc021cee..657947d12d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Cauchy.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Cauchy.md @@ -1,5 +1,6 @@
+ @@ -96,6 +97,45 @@ dist = tfd.Cauchy(loc=1., scale=[11, 22.]) dist.prob(3.) ``` +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='Cauchy' +) +``` + +Construct Cauchy distributions. + +The parameters `loc` and `scale` must be shaped in a way that supports +broadcasting (e.g. `loc + scale` is a valid operation). + +#### Args: + +* `loc`: Floating point tensor; the modes of the distribution(s). +* `scale`: Floating point tensor; the locations of the distribution(s). + Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if `loc` and `scale` have different `dtype`. + + + ## Properties

allow_nan_stats

@@ -143,7 +183,7 @@ May be partially defined or unknown.

loc

-Distribution parameter for the mean. +Distribution parameter for the location.

name

@@ -167,7 +207,7 @@ An instance of `ReparameterizationType`.

scale

-Distribution parameter for standard deviation. +Distribution parameter for the scale.

validate_args

@@ -177,43 +217,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='Cauchy' -) -``` - -Construct Cauchy distributions. - -The parameters `loc` and `scale` must be shaped in a way that supports -broadcasting (e.g. `loc + scale` is a valid operation). - -#### Args: - -* `loc`: Floating point tensor; the modes of the distribution(s). -* `scale`: Floating point tensor; the locations of the distribution(s). - Must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if `loc` and `scale` have different `dtype`. -

batch_shape_tensor

``` python @@ -353,7 +356,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -447,7 +450,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2.md index 7033defb1e..7dfc5a110f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2.md @@ -1,5 +1,6 @@
+ @@ -70,6 +71,35 @@ The Chi2 distribution is a special case of the Gamma distribution, i.e., Chi2(df) = Gamma(concentration=0.5 * df, rate=0.5) ``` +

__init__

+ +``` python +__init__( + df, + validate_args=False, + allow_nan_stats=True, + name='Chi2' +) +``` + +Construct Chi2 distributions with parameter `df`. + +#### Args: + +* `df`: Floating point tensor, the degrees of freedom of the + distribution(s). `df` must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -155,33 +185,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - df, - validate_args=False, - allow_nan_stats=True, - name='Chi2' -) -``` - -Construct Chi2 distributions with parameter `df`. - -#### Args: - -* `df`: Floating point tensor, the degrees of freedom of the - distribution(s). `df` must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -321,7 +324,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -415,7 +418,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2WithAbsDf.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2WithAbsDf.md index 690c3fd62c..d7d7901dfc 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2WithAbsDf.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Chi2WithAbsDf.md @@ -1,5 +1,6 @@
+ @@ -45,6 +46,21 @@ Inherits From: [`Chi2`](../../tfp/distributions/Chi2.md) Chi2 with parameter transform `df = floor(abs(df))`. +

__init__

+ +``` python +__init__( + df, + validate_args=False, + allow_nan_stats=True, + name='Chi2WithAbsDf' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -130,19 +146,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - df, - validate_args=False, - allow_nan_stats=True, - name='Chi2WithAbsDf' -) -``` - - -

batch_shape_tensor

``` python @@ -282,7 +285,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -376,7 +379,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalDistribution.md index 766e57b39a..46f84e1218 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalDistribution.md @@ -1,5 +1,6 @@
+ @@ -45,6 +46,55 @@ Distribution that supports intrinsic parameters (local latents). Subclasses of this distribution may have additional keyword arguments passed to their sample-based methods (i.e. `sample`, `log_prob`, etc.). +

__init__

+ +``` python +__init__( + dtype, + reparameterization_type, + validate_args, + allow_nan_stats, + parameters=None, + graph_parents=None, + name=None +) +``` + +Constructs the `Distribution`. + +**This is a private method for subclass use.** + +#### Args: + +* `dtype`: The type of the event samples. `None` implies no type-enforcement. +* `reparameterization_type`: Instance of `ReparameterizationType`. + If `distributions.FULLY_REPARAMETERIZED`, this + `Distribution` can be reparameterized in terms of some standard + distribution with a function whose Jacobian is constant for the support + of the standard distribution. If `distributions.NOT_REPARAMETERIZED`, + then no such reparameterization is available. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `parameters`: Python `dict` of parameters used to instantiate this + `Distribution`. +* `graph_parents`: Python `list` of graph prerequisites of this + `Distribution`. +* `name`: Python `str` name prefixed to Ops created by this class. Default: + subclass name. + + +#### Raises: + +* `ValueError`: if any member of graph_parents is `None` or not a `Tensor`. + + + ## Properties

allow_nan_stats

@@ -118,53 +168,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - dtype, - reparameterization_type, - validate_args, - allow_nan_stats, - parameters=None, - graph_parents=None, - name=None -) -``` - -Constructs the `Distribution`. - -**This is a private method for subclass use.** - -#### Args: - -* `dtype`: The type of the event samples. `None` implies no type-enforcement. -* `reparameterization_type`: Instance of `ReparameterizationType`. - If `distributions.FULLY_REPARAMETERIZED`, this - `Distribution` can be reparameterized in terms of some standard - distribution with a function whose Jacobian is constant for the support - of the standard distribution. If `distributions.NOT_REPARAMETERIZED`, - then no such reparameterization is available. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `parameters`: Python `dict` of parameters used to instantiate this - `Distribution`. -* `graph_parents`: Python `list` of graph prerequisites of this - `Distribution`. -* `name`: Python `str` name prefixed to Ops created by this class. Default: - subclass name. - - -#### Raises: - -* `ValueError`: if any member of graph_parents is `None` or not a `Tensor`. -

batch_shape_tensor

``` python @@ -289,7 +292,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -383,7 +386,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalTransformedDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalTransformedDistribution.md index 035c7e7a4a..57c3e8aa0e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalTransformedDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ConditionalTransformedDistribution.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,40 @@ Inherits From: [`ConditionalDistribution`](../../tfp/distributions/ConditionalDi A TransformedDistribution that allows intrinsic conditioning. +

__init__

+ +``` python +__init__( + distribution, + bijector=None, + batch_shape=None, + event_shape=None, + validate_args=False, + name=None +) +``` + +Construct a Transformed Distribution. + +#### Args: + +* `distribution`: The base distribution instance to transform. Typically an + instance of `Distribution`. +* `bijector`: The object responsible for calculating the transformation. + Typically an instance of `Bijector`. `None` means `Identity()`. +* `batch_shape`: `integer` vector `Tensor` which overrides `distribution` + `batch_shape`; valid only if `distribution.is_scalar_batch()`. +* `event_shape`: `integer` vector `Tensor` which overrides `distribution` + `event_shape`; valid only if `distribution.is_scalar_event()`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `name`: Python `str` name prefixed to Ops created by this class. Default: + `bijector.name + distribution.name`. + + + ## Properties

allow_nan_stats

@@ -125,38 +160,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - distribution, - bijector=None, - batch_shape=None, - event_shape=None, - validate_args=False, - name=None -) -``` - -Construct a Transformed Distribution. - -#### Args: - -* `distribution`: The base distribution instance to transform. Typically an - instance of `Distribution`. -* `bijector`: The object responsible for calculating the transformation. - Typically an instance of `Bijector`. `None` means `Identity()`. -* `batch_shape`: `integer` vector `Tensor` which overrides `distribution` - `batch_shape`; valid only if `distribution.is_scalar_batch()`. -* `event_shape`: `integer` vector `Tensor` which overrides `distribution` - `event_shape`; valid only if `distribution.is_scalar_event()`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `name`: Python `str` name prefixed to Ops created by this class. Default: - `bijector.name + distribution.name`. -

batch_shape_tensor

``` python @@ -284,7 +287,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -378,7 +381,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Deterministic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Deterministic.md index d9933298f1..3616841862 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Deterministic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Deterministic.md @@ -1,5 +1,6 @@
+ @@ -79,6 +80,52 @@ constant.prob(x) ==> [[1., 0.], [0., 1.]] ``` +

__init__

+ +``` python +__init__( + loc, + atol=None, + rtol=None, + validate_args=False, + allow_nan_stats=True, + name='Deterministic' +) +``` + +Initialize a scalar `Deterministic` distribution. + +The `atol` and `rtol` parameters allow for some slack in `pmf`, `cdf` +computations, e.g. due to floating-point error. + +``` +pmf(x; loc) + = 1, if Abs(x - loc) <= atol + rtol * Abs(loc), + = 0, otherwise. +``` + +#### Args: + +* `loc`: Numeric `Tensor` of shape `[B1, ..., Bb]`, with `b >= 0`. + The point (or batch of points) on which this distribution is supported. +* `atol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable + shape. The absolute tolerance for comparing closeness to `loc`. + Default is `0`. +* `rtol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable + shape. The relative tolerance for comparing closeness to `loc`. + Default is `0`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -164,50 +211,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - atol=None, - rtol=None, - validate_args=False, - allow_nan_stats=True, - name='Deterministic' -) -``` - -Initialize a scalar `Deterministic` distribution. - -The `atol` and `rtol` parameters allow for some slack in `pmf`, `cdf` -computations, e.g. due to floating-point error. - -``` -pmf(x; loc) - = 1, if Abs(x - loc) <= atol + rtol * Abs(loc), - = 0, otherwise. -``` - -#### Args: - -* `loc`: Numeric `Tensor` of shape `[B1, ..., Bb]`, with `b >= 0`. - The point (or batch of points) on which this distribution is supported. -* `atol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable - shape. The absolute tolerance for comparing closeness to `loc`. - Default is `0`. -* `rtol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable - shape. The relative tolerance for comparing closeness to `loc`. - Default is `0`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -347,7 +350,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -441,7 +444,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Dirichlet.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Dirichlet.md index 4eed558082..22e47dcd0d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Dirichlet.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Dirichlet.md @@ -1,5 +1,6 @@
+ @@ -100,10 +101,13 @@ Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498) #### Examples ```python +import tensorflow_probability as tfp +tfd = tfp.distributions + # Create a single trivariate Dirichlet, with the 3rd class being three times # more frequent than the first. I.e., batch_shape=[], event_shape=[3]. alpha = [1., 2, 3] -dist = tf.distributions.Dirichlet(alpha) +dist = tfd.Dirichlet(alpha) dist.sample([4, 5]) # shape: [4, 5, 3] @@ -125,7 +129,7 @@ dist.prob(x) # shape: [5, 7] # Create batch_shape=[2], event_shape=[3]: alpha = [[1., 2, 3], [4, 5, 6]] # shape: [2, 3] -dist = tf.distributions.Dirichlet(alpha) +dist = tfd.Dirichlet(alpha) dist.sample([4, 5]) # shape: [4, 5, 2, 3] @@ -140,13 +144,46 @@ Compute the gradients of samples w.r.t. the parameters: ```python alpha = tf.constant([1.0, 2.0, 3.0]) -dist = tf.distributions.Dirichlet(alpha) +dist = tfd.Dirichlet(alpha) samples = dist.sample(5) # Shape [5, 3] loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function # Unbiased stochastic gradients of the loss function grads = tf.gradients(loss, alpha) ``` +

__init__

+ +``` python +__init__( + concentration, + validate_args=False, + allow_nan_stats=True, + name='Dirichlet' +) +``` + +Initialize a batch of Dirichlet distributions. + +#### Args: + +* `concentration`: Positive floating-point `Tensor` indicating mean number + of class occurrences; aka "alpha". Implies `self.dtype`, and + `self.batch_shape`, `self.event_shape`, i.e., if + `concentration.shape = [N1, N2, ..., Nm, k]` then + `batch_shape = [N1, N2, ..., Nm]` and + `event_shape = [k]`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -228,37 +265,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration, - validate_args=False, - allow_nan_stats=True, - name='Dirichlet' -) -``` - -Initialize a batch of Dirichlet distributions. - -#### Args: - -* `concentration`: Positive floating-point `Tensor` indicating mean number - of class occurrences; aka "alpha". Implies `self.dtype`, and - `self.batch_shape`, `self.event_shape`, i.e., if - `concentration.shape = [N1, N2, ..., Nm, k]` then - `batch_shape = [N1, N2, ..., Nm]` and - `event_shape = [k]`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -398,7 +404,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -492,7 +498,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/DirichletMultinomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/DirichletMultinomial.md index f675adf880..cd9e4769a6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/DirichletMultinomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/DirichletMultinomial.md @@ -1,5 +1,6 @@
+ @@ -150,6 +151,43 @@ counts = [2., 1., 0.] dist.prob(counts) # Shape [2] ``` +

__init__

+ +``` python +__init__( + total_count, + concentration, + validate_args=False, + allow_nan_stats=True, + name='DirichletMultinomial' +) +``` + +Initialize a batch of DirichletMultinomial distributions. + +#### Args: + +* `total_count`: Non-negative floating point tensor, whose dtype is the same + as `concentration`. The shape is broadcastable to `[N1,..., Nm]` with + `m >= 0`. Defines this as a batch of `N1 x ... x Nm` different + Dirichlet multinomial distributions. Its components should be equal to + integer values. +* `concentration`: Positive floating point tensor, whose dtype is the + same as `n` with shape broadcastable to `[N1,..., Nm, K]` `m >= 0`. + Defines this as a batch of `N1 x ... x Nm` different `K` class Dirichlet + multinomial distributions. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -235,41 +273,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - total_count, - concentration, - validate_args=False, - allow_nan_stats=True, - name='DirichletMultinomial' -) -``` - -Initialize a batch of DirichletMultinomial distributions. - -#### Args: - -* `total_count`: Non-negative floating point tensor, whose dtype is the same - as `concentration`. The shape is broadcastable to `[N1,..., Nm]` with - `m >= 0`. Defines this as a batch of `N1 x ... x Nm` different - Dirichlet multinomial distributions. Its components should be equal to - integer values. -* `concentration`: Positive floating point tensor, whose dtype is the - same as `n` with shape broadcastable to `[N1,..., Nm, K]` `m >= 0`. - Defines this as a batch of `N1 x ... x Nm` different `K` class Dirichlet - multinomial distributions. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -429,7 +432,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -523,7 +526,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Distribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Distribution.md index 3a43033830..dea783e2fd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Distribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Distribution.md @@ -1,5 +1,6 @@
+ @@ -174,6 +175,55 @@ dist = distributions.beta(negative_a, b, allow_nan_stats=True) dist.mean().eval() ``` +

__init__

+ +``` python +__init__( + dtype, + reparameterization_type, + validate_args, + allow_nan_stats, + parameters=None, + graph_parents=None, + name=None +) +``` + +Constructs the `Distribution`. + +**This is a private method for subclass use.** + +#### Args: + +* `dtype`: The type of the event samples. `None` implies no type-enforcement. +* `reparameterization_type`: Instance of `ReparameterizationType`. + If `distributions.FULLY_REPARAMETERIZED`, this + `Distribution` can be reparameterized in terms of some standard + distribution with a function whose Jacobian is constant for the support + of the standard distribution. If `distributions.NOT_REPARAMETERIZED`, + then no such reparameterization is available. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `parameters`: Python `dict` of parameters used to instantiate this + `Distribution`. +* `graph_parents`: Python `list` of graph prerequisites of this + `Distribution`. +* `name`: Python `str` name prefixed to Ops created by this class. Default: + subclass name. + + +#### Raises: + +* `ValueError`: if any member of graph_parents is `None` or not a `Tensor`. + + + ## Properties

allow_nan_stats

@@ -247,53 +297,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - dtype, - reparameterization_type, - validate_args, - allow_nan_stats, - parameters=None, - graph_parents=None, - name=None -) -``` - -Constructs the `Distribution`. - -**This is a private method for subclass use.** - -#### Args: - -* `dtype`: The type of the event samples. `None` implies no type-enforcement. -* `reparameterization_type`: Instance of `ReparameterizationType`. - If `distributions.FULLY_REPARAMETERIZED`, this - `Distribution` can be reparameterized in terms of some standard - distribution with a function whose Jacobian is constant for the support - of the standard distribution. If `distributions.NOT_REPARAMETERIZED`, - then no such reparameterization is available. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `parameters`: Python `dict` of parameters used to instantiate this - `Distribution`. -* `graph_parents`: Python `list` of graph prerequisites of this - `Distribution`. -* `name`: Python `str` name prefixed to Ops created by this class. Default: - subclass name. - - -#### Raises: - -* `ValueError`: if any member of graph_parents is `None` or not a `Tensor`. -

batch_shape_tensor

``` python @@ -433,7 +436,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -527,7 +530,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExpRelaxedOneHotCategorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExpRelaxedOneHotCategorical.md index 8d49ad3ba0..857d65ef6b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExpRelaxedOneHotCategorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExpRelaxedOneHotCategorical.md @@ -1,5 +1,6 @@
+ @@ -134,6 +135,51 @@ exp_samples = tf.exp(samples) Chris J. Maddison, Andriy Mnih, and Yee Whye Teh. The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables. 2016. +

__init__

+ +``` python +__init__( + temperature, + logits=None, + probs=None, + dtype=None, + validate_args=False, + allow_nan_stats=True, + name='ExpRelaxedOneHotCategorical' +) +``` + +Initialize ExpRelaxedOneHotCategorical using class log-probabilities. + +#### Args: + +* `temperature`: An 0-D `Tensor`, representing the temperature + of a set of ExpRelaxedCategorical distributions. The temperature should + be positive. +* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities + of a set of ExpRelaxedCategorical distributions. The first + `N - 1` dimensions index into a batch of independent distributions and + the last dimension represents a vector of logits for each class. Only + one of `logits` or `probs` should be passed in. +* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities + of a set of ExpRelaxedCategorical distributions. The first + `N - 1` dimensions index into a batch of independent distributions and + the last dimension represents a vector of probabilities for each + class. Only one of `logits` or `probs` should be passed in. +* `dtype`: The type of the event samples (default: inferred from + logits/probs). +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -223,49 +269,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - temperature, - logits=None, - probs=None, - dtype=None, - validate_args=False, - allow_nan_stats=True, - name='ExpRelaxedOneHotCategorical' -) -``` - -Initialize ExpRelaxedOneHotCategorical using class log-probabilities. - -#### Args: - -* `temperature`: An 0-D `Tensor`, representing the temperature - of a set of ExpRelaxedCategorical distributions. The temperature should - be positive. -* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities - of a set of ExpRelaxedCategorical distributions. The first - `N - 1` dimensions index into a batch of independent distributions and - the last dimension represents a vector of logits for each class. Only - one of `logits` or `probs` should be passed in. -* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities - of a set of ExpRelaxedCategorical distributions. The first - `N - 1` dimensions index into a batch of independent distributions and - the last dimension represents a vector of probabilities for each - class. Only one of `logits` or `probs` should be passed in. -* `dtype`: The type of the event samples (default: inferred from - logits/probs). -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -405,7 +408,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -499,7 +502,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Exponential.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Exponential.md index c5acf54e48..67e472fe1a 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Exponential.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Exponential.md @@ -1,5 +1,6 @@
+ @@ -72,6 +73,35 @@ X ~ Exponential(rate=1) Y = X / rate ``` +

__init__

+ +``` python +__init__( + rate, + validate_args=False, + allow_nan_stats=True, + name='Exponential' +) +``` + +Construct Exponential distribution with parameter `rate`. + +#### Args: + +* `rate`: Floating point tensor, equivalent to `1 / mean`. Must contain only + positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -153,33 +183,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - rate, - validate_args=False, - allow_nan_stats=True, - name='Exponential' -) -``` - -Construct Exponential distribution with parameter `rate`. - -#### Args: - -* `rate`: Floating point tensor, equivalent to `1 / mean`. Must contain only - positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -319,7 +322,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -413,7 +416,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExponentialWithSoftplusRate.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExponentialWithSoftplusRate.md index c689e9f3c9..b689cc5582 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExponentialWithSoftplusRate.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ExponentialWithSoftplusRate.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,21 @@ Inherits From: [`Exponential`](../../tfp/distributions/Exponential.md) Exponential with softplus transform on `rate`. +

__init__

+ +``` python +__init__( + rate, + validate_args=False, + allow_nan_stats=True, + name='ExponentialWithSoftplusRate' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -125,19 +141,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - rate, - validate_args=False, - allow_nan_stats=True, - name='ExponentialWithSoftplusRate' -) -``` - - -

batch_shape_tensor

``` python @@ -277,7 +280,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -371,7 +374,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gamma.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gamma.md index 28b2c507cd..2c47423bb7 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gamma.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gamma.md @@ -1,5 +1,6 @@
+ @@ -98,8 +99,11 @@ Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498) #### Examples ```python -dist = tf.distributions.Gamma(concentration=3.0, rate=2.0) -dist2 = tf.distributions.Gamma(concentration=[3.0, 4.0], rate=[2.0, 3.0]) +import tensorflow_probability as tfp +tfd = tfp.distributions + +dist = tfd.Gamma(concentration=3.0, rate=2.0) +dist2 = tfd.Gamma(concentration=[3.0, 4.0], rate=[2.0, 3.0]) ``` Compute the gradients of samples w.r.t. the parameters: @@ -107,13 +111,53 @@ Compute the gradients of samples w.r.t. the parameters: ```python concentration = tf.constant(3.0) rate = tf.constant(2.0) -dist = tf.distributions.Gamma(concentration, rate) +dist = tfd.Gamma(concentration, rate) samples = dist.sample(5) # Shape [5] loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function # Unbiased stochastic gradients of the loss function grads = tf.gradients(loss, [concentration, rate]) ``` +

__init__

+ +``` python +__init__( + concentration, + rate, + validate_args=False, + allow_nan_stats=True, + name='Gamma' +) +``` + +Construct Gamma with `concentration` and `rate` parameters. + +The parameters `concentration` and `rate` must be shaped in a way that +supports broadcasting (e.g. `concentration + rate` is a valid operation). + +#### Args: + +* `concentration`: Floating point tensor, the concentration params of the + distribution(s). Must contain only positive values. +* `rate`: Floating point tensor, the inverse scale params of the + distribution(s). Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if `concentration` and `rate` are different dtypes. + + + ## Properties

allow_nan_stats

@@ -195,44 +239,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration, - rate, - validate_args=False, - allow_nan_stats=True, - name='Gamma' -) -``` - -Construct Gamma with `concentration` and `rate` parameters. - -The parameters `concentration` and `rate` must be shaped in a way that -supports broadcasting (e.g. `concentration + rate` is a valid operation). - -#### Args: - -* `concentration`: Floating point tensor, the concentration params of the - distribution(s). Must contain only positive values. -* `rate`: Floating point tensor, the inverse scale params of the - distribution(s). Must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if `concentration` and `rate` are different dtypes. -

batch_shape_tensor

``` python @@ -372,7 +378,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -466,7 +472,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaGamma.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaGamma.md index 41f98694b5..9263014a91 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaGamma.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaGamma.md @@ -1,5 +1,6 @@
+ @@ -76,6 +77,56 @@ where the normalizing constant `Z = Beta(alpha, alpha0) * beta0**(-alpha0)`. See: http://www.brucehardie.com/notes/025/gamma_gamma.pdf +Samples of this distribution are reparameterized as samples of the Gamma +distribution are reparameterized using the technique described in the paper + +[Michael Figurnov, Shakir Mohamed, Andriy Mnih. +Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498) + +

__init__

+ +``` python +__init__( + concentration, + mixing_concentration, + mixing_rate, + validate_args=False, + allow_nan_stats=True, + name='GammaGamma' +) +``` + +Initializes a batch of Gamma-Gamma distributions. + +The parameters `concentration` and `rate` must be shaped in a way that +supports broadcasting (e.g. +`concentration + mixing_concentration + mixing_rate` is a valid operation). + +#### Args: + +* `concentration`: Floating point tensor, the concentration params of the + distribution(s). Must contain only positive values. +* `mixing_concentration`: Floating point tensor, the concentration params of + the mixing Gamma distribution(s). Must contain only positive values. +* `mixing_rate`: Floating point tensor, the rate params of the mixing Gamma + distribution(s). Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or more + of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if `concentration` and `rate` are different dtypes. + + + ## Properties

allow_nan_stats

@@ -161,48 +212,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration, - mixing_concentration, - mixing_rate, - validate_args=False, - allow_nan_stats=True, - name='GammaGamma' -) -``` - -Initializes a batch of Gamma-Gamma distributions. - -The parameters `concentration` and `rate` must be shaped in a way that -supports broadcasting (e.g. -`concentration + mixing_concentration + mixing_rate` is a valid operation). - -#### Args: - -* `concentration`: Floating point tensor, the concentration params of the - distribution(s). Must contain only positive values. -* `mixing_concentration`: Floating point tensor, the concentration params of - the mixing Gamma distribution(s). Must contain only positive values. -* `mixing_rate`: Floating point tensor, the rate params of the mixing Gamma - distribution(s). Must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or more - of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if `concentration` and `rate` are different dtypes. -

batch_shape_tensor

``` python @@ -342,7 +351,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -436,7 +445,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaWithSoftplusConcentrationRate.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaWithSoftplusConcentrationRate.md index 17e24be5ea..17e518bf46 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaWithSoftplusConcentrationRate.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GammaWithSoftplusConcentrationRate.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,22 @@ Inherits From: [`Gamma`](../../tfp/distributions/Gamma.md) `Gamma` with softplus of `concentration` and `rate`. +

__init__

+ +``` python +__init__( + concentration, + rate, + validate_args=False, + allow_nan_stats=True, + name='GammaWithSoftplusConcentrationRate' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -125,20 +142,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration, - rate, - validate_args=False, - allow_nan_stats=True, - name='GammaWithSoftplusConcentrationRate' -) -``` - - -

batch_shape_tensor

``` python @@ -278,7 +281,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -372,7 +375,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcess.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcess.md index dc28e33117..6e4d02cf8e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcess.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcess.md @@ -1,5 +1,6 @@
+ @@ -198,6 +199,69 @@ with tf.Session() as sess: print("Final NLL = {}".format(nll_)) ``` +

__init__

+ +``` python +__init__( + kernel, + index_points, + mean_fn=None, + observation_noise_variance=0.0, + jitter=1e-06, + validate_args=False, + allow_nan_stats=False, + name='GaussianProcess' +) +``` + +Instantiate a GaussianProcess Distribution. + +#### Args: + +* `kernel`: `PositiveSemidefiniteKernel`-like instance representing the + GP's covariance function. +* `index_points`: `float` `Tensor` representing finite (batch of) vector(s) of + points in the index set over which the GP is defined. Shape has the form + `[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature + dimensions and must equal `kernel.feature_ndims` and `e` is the number + (size) of index points in each batch. Ultimately this distribution + corresponds to a `e`-dimensional multivariate normal. The batch shape + must be broadcastable with `kernel.batch_shape` and any batch dims + yielded by `mean_fn`. +* `mean_fn`: Python `callable` that acts on `index_points` to produce a (batch + of) vector(s) of mean values at `index_points`. Takes a `Tensor` of + shape `[b1, ..., bB, f1, ..., fF]` and returns a `Tensor` whose shape is + broadcastable with `[b1, ..., bB]`. Default value: `None` implies + constant zero function. +* `observation_noise_variance`: `float` `Tensor` representing the variance + of the noise in the Normal likelihood distribution of the model. May be + batched, in which case the batch shape must be broadcastable with the + shapes of all other batched parameters (`kernel.batch_shape`, + `index_points`, etc.). + Default value: `0.` +* `jitter`: `float` scalar `Tensor` added to the diagonal of the covariance + matrix to ensure positive definiteness of the covariance matrix. + Default value: `1e-6`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + Default value: `False`. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + Default value: `False`. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: "GaussianProcess". + + +#### Raises: + +* `ValueError`: if `mean_fn` is not `None` and is not callable. + + + ## Properties

allow_nan_stats

@@ -307,67 +371,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - kernel, - index_points, - mean_fn=None, - observation_noise_variance=0.0, - jitter=1e-06, - validate_args=False, - allow_nan_stats=False, - name='GaussianProcess' -) -``` - -Instantiate a GaussianProcess Distribution. - -#### Args: - -* `kernel`: `PositiveSemidefiniteKernel`-like instance representing the - GP's covariance function. -* `index_points`: `float` `Tensor` representing finite (batch of) vector(s) of - points in the index set over which the GP is defined. Shape has the form - `[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature - dimensions and must equal `kernel.feature_ndims` and `e` is the number - (size) of index points in each batch. Ultimately this distribution - corresponds to a `e`-dimensional multivariate normal. The batch shape - must be broadcastable with `kernel.batch_shape` and any batch dims - yielded by `mean_fn`. -* `mean_fn`: Python `callable` that acts on `index_points` to produce a (batch - of) vector(s) of mean values at `index_points`. Takes a `Tensor` of - shape `[b1, ..., bB, f1, ..., fF]` and returns a `Tensor` whose shape is - broadcastable with `[b1, ..., bB]`. Default value: `None` implies - constant zero function. -* `observation_noise_variance`: `float` `Tensor` representing the variance - of the noise in the Normal likelihood distribution of the model. May be - batched, in which case the batch shape must be broadcastable with the - shapes of all other batched parameters (`kernel.batch_shape`, - `index_points`, etc.). - Default value: `0.` -* `jitter`: `float` scalar `Tensor` added to the diagonal of the covariance - matrix to ensure positive definiteness of the covariance matrix. - Default value: `1e-6`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. - Default value: `False`. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. - Default value: `False`. -* `name`: Python `str` name prefixed to Ops created by this class. - Default value: "GaussianProcess". - - -#### Raises: - -* `ValueError`: if `mean_fn` is not `None` and is not callable. -

batch_shape_tensor

``` python @@ -507,7 +510,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -601,7 +604,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcessRegressionModel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcessRegressionModel.md index 5cbff6b640..06f439868b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcessRegressionModel.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/GaussianProcessRegressionModel.md @@ -1,5 +1,6 @@
+ @@ -306,7 +307,7 @@ num_results = 200 # of index points. gprm = tfd.GaussianProcessRegressionModel( # Batch of `num_results` kernels parameterized by the MCMC samples. - kernel=psd_kernels.ExponentiatedQuadratic(amplitudes, length_scales) + kernel=psd_kernels.ExponentiatedQuadratic(amplitudes, length_scales), index_points=np.linspace(-2., 2., 200)[..., np.newaxis], observation_index_points=observation_index_points, observations=observations, @@ -334,6 +335,103 @@ with tf.Session() as sess: [1]: Carl Rasmussen, Chris Williams. Gaussian Processes For Machine Learning, 2006. +

__init__

+ +``` python +__init__( + kernel, + index_points, + observation_index_points=None, + observations=None, + observation_noise_variance=0.0, + predictive_noise_variance=None, + mean_fn=None, + jitter=1e-06, + validate_args=False, + allow_nan_stats=False, + name='GaussianProcessRegressionModel' +) +``` + +Construct a GaussianProcessRegressionModel instance. + +#### Args: + +* `kernel`: `PositiveSemidefiniteKernel`-like instance representing the + GP's covariance function. +* `index_points`: `float` `Tensor` representing finite collection, or batch of + collections, of points in the index set over which the GP is defined. + Shape has the form `[b1, ..., bB, e, f1, ..., fF]` where `F` is the + number of feature dimensions and must equal `kernel.feature_ndims` and + `e` is the number (size) of index points in each batch. Ultimately this + distribution corresponds to an `e`-dimensional multivariate normal. The + batch shape must be broadcastable with `kernel.batch_shape` and any + batch dims yielded by `mean_fn`. +* `observation_index_points`: `float` `Tensor` representing finite collection, + or batch of collections, of points in the index set for which some data + has been observed. Shape has the form `[b1, ..., bB, e, f1, ..., fF]` + where `F` is the number of feature dimensions and must equal + `kernel.feature_ndims`, and `e` is the number (size) of index points in + each batch. `[b1, ..., bB, e]` must be broadcastable with the shape of + `observations`, and `[b1, ..., bB]` must be broadcastable with the + shapes of all other batched parameters (`kernel.batch_shape`, + `index_points`, etc). The default value is `None`, which corresponds to + the empty set of observations, and simply results in the prior + predictive model (a GP with noise of variance + `predictive_noise_variance`). +* `observations`: `float` `Tensor` representing collection, or batch of + collections, of observations corresponding to + `observation_index_points`. Shape has the form `[b1, ..., bB, e]`, which + must be brodcastable with the batch and example shapes of + `observation_index_points`. The batch shape `[b1, ..., bB]` must be + broadcastable with the shapes of all other batched parameters + (`kernel.batch_shape`, `index_points`, etc.). The default value is + `None`, which corresponds to the empty set of observations, and simply + results in the prior predictive model (a GP with noise of variance + `predictive_noise_variance`). +* `observation_noise_variance`: `float` `Tensor` representing the variance + of the noise in the Normal likelihood distribution of the model. May be + batched, in which case the batch shape must be broadcastable with the + shapes of all other batched parameters (`kernel.batch_shape`, + `index_points`, etc.). + Default value: `0.` +* `predictive_noise_variance`: `float` `Tensor` representing the variance in + the posterior predictive model. If `None`, we simply re-use + `observation_noise_variance` for the posterior predictive noise. If set + explicitly, however, we use this value. This allows us, for example, to + omit predictive noise variance (by setting this to zero) to obtain + noiseless posterior predictions of function values, conditioned on noisy + observations. +* `mean_fn`: Python `callable` that acts on `index_points` to produce a + collection, or batch of collections, of mean values at `index_points`. + Takes a `Tensor` of shape `[b1, ..., bB, f1, ..., fF]` and returns a + `Tensor` whose shape is broadcastable with `[b1, ..., bB]`. + Default value: `None` implies the constant zero function. +* `jitter`: `float` scalar `Tensor` added to the diagonal of the covariance + matrix to ensure positive definiteness of the covariance matrix. + Default value: `1e-6`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + Default value: `False`. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value `NaN` to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + Default value: `False`. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: 'GaussianProcessRegressionModel'. + + +#### Raises: + +* `ValueError`: if either + - only one of `observations` and `observation_index_points` is given, or + - `mean_fn` is not `None` and not callable. + + + ## Properties

allow_nan_stats

@@ -455,101 +553,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - kernel, - index_points, - observation_index_points=None, - observations=None, - observation_noise_variance=0.0, - predictive_noise_variance=None, - mean_fn=None, - jitter=1e-06, - validate_args=False, - allow_nan_stats=False, - name='GaussianProcessRegressionModel' -) -``` - -Construct a GaussianProcessRegressionModel instance. - -#### Args: - -* `kernel`: `PositiveSemidefiniteKernel`-like instance representing the - GP's covariance function. -* `index_points`: `float` `Tensor` representing finite collection, or batch of - collections, of points in the index set over which the GP is defined. - Shape has the form `[b1, ..., bB, e, f1, ..., fF]` where `F` is the - number of feature dimensions and must equal `kernel.feature_ndims` and - `e` is the number (size) of index points in each batch. Ultimately this - distribution corresponds to an `e`-dimensional multivariate normal. The - batch shape must be broadcastable with `kernel.batch_shape` and any - batch dims yielded by `mean_fn`. -* `observation_index_points`: `float` `Tensor` representing finite collection, - or batch of collections, of points in the index set for which some data - has been observed. Shape has the form `[b1, ..., bB, e, f1, ..., fF]` - where `F` is the number of feature dimensions and must equal - `kernel.feature_ndims`, and `e` is the number (size) of index points in - each batch. `[b1, ..., bB, e]` must be broadcastable with the shape of - `observations`, and `[b1, ..., bB]` must be broadcastable with the - shapes of all other batched parameters (`kernel.batch_shape`, - `index_points`, etc). The default value is `None`, which corresponds to - the empty set of observations, and simply results in the prior - predictive model (a GP with noise of variance - `predictive_noise_variance`). -* `observations`: `float` `Tensor` representing collection, or batch of - collections, of observations corresponding to - `observation_index_points`. Shape has the form `[b1, ..., bB, e]`, which - must be brodcastable with the batch and example shapes of - `observation_index_points`. The batch shape `[b1, ..., bB]` must be - broadcastable with the shapes of all other batched parameters - (`kernel.batch_shape`, `index_points`, etc.). The default value is - `None`, which corresponds to the empty set of observations, and simply - results in the prior predictive model (a GP with noise of variance - `predictive_noise_variance`). -* `observation_noise_variance`: `float` `Tensor` representing the variance - of the noise in the Normal likelihood distribution of the model. May be - batched, in which case the batch shape must be broadcastable with the - shapes of all other batched parameters (`kernel.batch_shape`, - `index_points`, etc.). - Default value: `0.` -* `predictive_noise_variance`: `float` `Tensor` representing the variance in - the posterior predictive model. If `None`, we simply re-use - `observation_noise_variance` for the posterior predictive noise. If set - explicitly, however, we use this value. This allows us, for example, to - omit predictive noise variance (by setting this to zero) to obtain - noiseless posterior predictions of function values, conditioned on noisy - observations. -* `mean_fn`: Python `callable` that acts on `index_points` to produce a - collection, or batch of collections, of mean values at `index_points`. - Takes a `Tensor` of shape `[b1, ..., bB, f1, ..., fF]` and returns a - `Tensor` whose shape is broadcastable with `[b1, ..., bB]`. - Default value: `None` implies the constant zero function. -* `jitter`: `float` scalar `Tensor` added to the diagonal of the covariance - matrix to ensure positive definiteness of the covariance matrix. - Default value: `1e-6`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. - Default value: `False`. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value `NaN` to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. - Default value: `False`. -* `name`: Python `str` name prefixed to Ops created by this class. - Default value: 'GaussianProcessRegressionModel'. - - -#### Raises: - -* `ValueError`: if either - - only one of `observations` and `observation_index_points` is given, or - - `mean_fn` is not `None` and not callable. -

batch_shape_tensor

``` python @@ -689,7 +692,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -783,7 +786,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Geometric.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Geometric.md index 5e9986f085..dac99e1878 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Geometric.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Geometric.md @@ -1,5 +1,6 @@
+ @@ -61,6 +62,44 @@ where: * `p` is the success probability, `0 < p <= 1`, and, * `k` is a non-negative integer. +

__init__

+ +``` python +__init__( + logits=None, + probs=None, + validate_args=False, + allow_nan_stats=True, + name='Geometric' +) +``` + +Construct Geometric distributions. + +#### Args: + +* `logits`: Floating-point `Tensor` with shape `[B1, ..., Bb]` where `b >= 0` + indicates the number of batch dimensions. Each entry represents logits + for the probability of success for independent Geometric distributions + and must be in the range `(-inf, inf]`. Only one of `logits` or `probs` + should be specified. +* `probs`: Positive floating-point `Tensor` with shape `[B1, ..., Bb]` + where `b >= 0` indicates the number of batch dimensions. Each entry + represents the probability of success for independent Geometric + distributions and must be in the range `(0, 1]`. Only one of `logits` + or `probs` should be specified. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -142,42 +181,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - logits=None, - probs=None, - validate_args=False, - allow_nan_stats=True, - name='Geometric' -) -``` - -Construct Geometric distributions. - -#### Args: - -* `logits`: Floating-point `Tensor` with shape `[B1, ..., Bb]` where `b >= 0` - indicates the number of batch dimensions. Each entry represents logits - for the probability of success for independent Geometric distributions - and must be in the range `(-inf, inf]`. Only one of `logits` or `probs` - should be specified. -* `probs`: Positive floating-point `Tensor` with shape `[B1, ..., Bb]` - where `b >= 0` indicates the number of batch dimensions. Each entry - represents the probability of success for independent Geometric - distributions and must be in the range `(0, 1]`. Only one of `logits` - or `probs` should be specified. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -317,7 +320,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -411,7 +414,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gumbel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gumbel.md new file mode 100644 index 0000000000..5903ce2751 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Gumbel.md @@ -0,0 +1,811 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.distributions.Gumbel + +## Class `Gumbel` + +Inherits From: [`TransformedDistribution`](../../tfp/distributions/TransformedDistribution.md) + +The scalar Gumbel distribution with location `loc` and `scale` parameters. + +#### Mathematical details + +The probability density function (pdf) of this distribution is, + +```none +pdf(x; mu, sigma) = exp(-(x - mu) / sigma - exp(-(x - mu) / sigma)) +``` + +where `loc = mu` and `scale = sigma`. + +The cumulative density function of this distribution is, + +```cdf(x; mu, sigma) = exp(-exp(-(x - mu) / sigma))``` + +The Gumbel distribution is a member of the [location-scale family]( +https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be +constructed as, + +```none +X ~ Gumbel(loc=0, scale=1) +Y = loc + scale * X +``` + +#### Examples + +Examples of initialization of one or a batch of distributions. + +```python +tfd = tfp.distributions + +# Define a single scalar Gumbel distribution. +dist = tfd.Gumbel(loc=0., scale=3.) + +# Evaluate the cdf at 1, returning a scalar. +dist.cdf(1.) + +# Define a batch of two scalar valued Gumbels. +# The first has mean 1 and scale 11, the second 2 and 22. +dist = tfd.Gumbel(loc=[1, 2.], scale=[11, 22.]) + +# Evaluate the pdf of the first distribution on 0, and the second on 1.5, +# returning a length two tensor. +dist.prob([0, 1.5]) + +# Get 3 samples, returning a 3 x 2 tensor. +dist.sample([3]) +``` + +Arguments are broadcast when possible. + +```python +# Define a batch of two scalar valued Logistics. +# Both have mean 1, but different scales. +dist = tfd.Gumbel(loc=1., scale=[11, 22.]) + +# Evaluate the pdf of both distributions on the same point, 3.0, +# returning a length 2 tensor. +dist.prob(3.0) +``` + +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='Gumbel' +) +``` + +Construct Gumbel distributions with location and scale `loc` and `scale`. + +The parameters `loc` and `scale` must be shaped in a way that supports +broadcasting (e.g. `loc + scale` is a valid operation). + +#### Args: + +* `loc`: Floating point tensor, the means of the distribution(s). +* `scale`: Floating point tensor, the scales of the distribution(s). + scale must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + Default value: `False`. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + Default value: `True`. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: `'Gumbel'`. + + +#### Raises: + +* `TypeError`: if loc and scale are different dtypes. + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

bijector

+ +Function transforming x => y. + +

distribution

+ +Base distribution, p(x). + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

loc

+ +Distribution parameter for the location. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

scale

+ +Distribution parameter for scale. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfCauchy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfCauchy.md new file mode 100644 index 0000000000..cbd165a84d --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfCauchy.md @@ -0,0 +1,754 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.distributions.HalfCauchy + +## Class `HalfCauchy` + +Inherits From: [`Distribution`](../../tfp/distributions/Distribution.md) + +Half-Cauchy distribution. + +The half-Cauchy distribution is parameterized by a `loc` and a +`scale` parameter. It represents the right half of the two symmetric halves in +a [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution). + +#### Mathematical Details +The probability density function (pdf) for the half-Cauchy distribution +is given by + +```none +pdf(x; loc, scale) = 2 / (pi scale (1 + z**2)) +z = (x - loc) / scale +``` + +where `loc` is a scalar in `R` and `scale` is a positive scalar in `R`. + +The support of the distribution is given by the interval `[loc, infinity)`. + +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='HalfCauchy' +) +``` + +Construct a half-Cauchy distribution with `loc` and `scale`. + +#### Args: + +* `loc`: Floating-point `Tensor`; the location(s) of the distribution(s). +* `scale`: Floating-point `Tensor`; the scale(s) of the distribution(s). + Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. Default value: `False` (i.e. do not validate args). +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + Default value: `True`. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: 'HalfCauchy'. + + +#### Raises: + +* `TypeError`: if `loc` and `scale` have different `dtype`. + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

loc

+ +Distribution parameter for the location. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

scale

+ +Distribution parameter for the scale. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfNormal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfNormal.md index 3825b95f37..ba19e8f842 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfNormal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/HalfNormal.md @@ -1,5 +1,6 @@
+ @@ -85,6 +86,35 @@ dist.prob([1.0, 1.5]) dist.sample([3]) ``` +

__init__

+ +``` python +__init__( + scale, + validate_args=False, + allow_nan_stats=True, + name='HalfNormal' +) +``` + +Construct HalfNormals with scale `scale`. + +#### Args: + +* `scale`: Floating point tensor; the scales of the distribution(s). + Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -162,33 +192,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - scale, - validate_args=False, - allow_nan_stats=True, - name='HalfNormal' -) -``` - -Construct HalfNormals with scale `scale`. - -#### Args: - -* `scale`: Floating point tensor; the scales of the distribution(s). - Must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -328,7 +331,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -422,7 +425,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Independent.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Independent.md index 492a9e230b..b766e85ffd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Independent.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Independent.md @@ -1,5 +1,6 @@
+ @@ -102,6 +103,41 @@ ind.batch_shape # ==> [] ind.event_shape # ==> [2, 2] ``` +

__init__

+ +``` python +__init__( + distribution, + reinterpreted_batch_ndims=None, + validate_args=False, + name=None +) +``` + +Construct a `Independent` distribution. + +#### Args: + +* `distribution`: The base distribution instance to transform. Typically an + instance of `Distribution`. +* `reinterpreted_batch_ndims`: Scalar, integer number of rightmost batch dims + which will be regarded as event dims. When `None` all but the first + batch axis (batch axis 0) will be transferred to event dimensions + (analogous to `tf.layers.flatten`). +* `validate_args`: Python `bool`. Whether to validate input with asserts. + If `validate_args` is `False`, and the inputs are invalid, + correct behavior is not guaranteed. +* `name`: The name for ops managed by the distribution. + Default value: `Independent + distribution.name`. + + +#### Raises: + +* `ValueError`: if `reinterpreted_batch_ndims` exceeds + `distribution.batch_ndims` + + + ## Properties

allow_nan_stats

@@ -183,39 +219,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - distribution, - reinterpreted_batch_ndims=None, - validate_args=False, - name=None -) -``` - -Construct a `Independent` distribution. - -#### Args: - -* `distribution`: The base distribution instance to transform. Typically an - instance of `Distribution`. -* `reinterpreted_batch_ndims`: Scalar, integer number of rightmost batch dims - which will be regarded as event dims. When `None` all but the first - batch axis (batch axis 0) will be transferred to event dimensions - (analogous to `tf.layers.flatten`). -* `validate_args`: Python `bool`. Whether to validate input with asserts. - If `validate_args` is `False`, and the inputs are invalid, - correct behavior is not guaranteed. -* `name`: The name for ops managed by the distribution. - Default value: `Independent + distribution.name`. - - -#### Raises: - -* `ValueError`: if `reinterpreted_batch_ndims` exceeds - `distribution.batch_ndims` -

batch_shape_tensor

``` python @@ -355,7 +358,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -449,7 +452,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGamma.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGamma.md index 23dd1b15e1..0837a4a2cc 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGamma.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGamma.md @@ -1,5 +1,6 @@
+ @@ -73,11 +74,19 @@ cdf(x; alpha, beta, x > 0) = GammaInc(alpha, beta / x) / Gamma(alpha) where `GammaInc` is the [upper incomplete Gamma function]( https://en.wikipedia.org/wiki/Incomplete_gamma_function). -The parameters can be intuited via their relationship to mean and stddev, +The parameters can be intuited via their relationship to mean and variance +when these moments exist, ```none -concentration = alpha = (mean / stddev)**2 -rate = beta = mean / stddev**2 +mean = beta / (alpha - 1) when alpha > 1 +variance = beta**2 / (alpha - 1)**2 / (alpha - 2) when alpha > 2 +``` + +i.e., under the same conditions: + +```none +alpha = mean**2 / variance + 2 +beta = mean * (mean**2 / variance + 1) ``` Distribution parameters are automatically broadcast in all functions; see @@ -110,6 +119,47 @@ loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function grads = tf.gradients(loss, [concentration, rate]) ``` +

__init__

+ +``` python +__init__( + concentration, + rate, + validate_args=False, + allow_nan_stats=True, + name='InverseGamma' +) +``` + +Construct InverseGamma with `concentration` and `rate` parameters. + +The parameters `concentration` and `rate` must be shaped in a way that +supports broadcasting (e.g. `concentration + rate` is a valid operation). + +#### Args: + +* `concentration`: Floating point tensor, the concentration params of the + distribution(s). Must contain only positive values. +* `rate`: Floating point tensor, the inverse scale params of the + distribution(s). Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + +#### Raises: + +* `TypeError`: if `concentration` and `rate` are different dtypes. + + + ## Properties

allow_nan_stats

@@ -191,45 +241,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration, - rate, - validate_args=False, - allow_nan_stats=True, - name='InverseGamma' -) -``` - -Construct InverseGamma with `concentration` and `rate` parameters. - -The parameters `concentration` and `rate` must be shaped in a way that -supports broadcasting (e.g. `concentration + rate` is a valid operation). - -#### Args: - -* `concentration`: Floating point tensor, the concentration params of the - distribution(s). Must contain only positive values. -* `rate`: Floating point tensor, the inverse scale params of the - distribution(s). Must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - - -#### Raises: - -* `TypeError`: if `concentration` and `rate` are different dtypes. -

batch_shape_tensor

``` python @@ -369,7 +380,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -463,7 +474,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGammaWithSoftplusConcentrationRate.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGammaWithSoftplusConcentrationRate.md index a625923b28..151084e9b0 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGammaWithSoftplusConcentrationRate.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGammaWithSoftplusConcentrationRate.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,22 @@ Inherits From: [`InverseGamma`](../../tfp/distributions/InverseGamma.md) `InverseGamma` with softplus of `concentration` and `rate`. +

__init__

+ +``` python +__init__( + concentration, + rate, + validate_args=False, + allow_nan_stats=True, + name='InverseGammaWithSoftplusConcentrationRate' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -125,20 +142,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration, - rate, - validate_args=False, - allow_nan_stats=True, - name='InverseGammaWithSoftplusConcentrationRate' -) -``` - - -

batch_shape_tensor

``` python @@ -278,7 +281,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -372,7 +375,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGaussian.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGaussian.md new file mode 100644 index 0000000000..b865f3f774 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/InverseGaussian.md @@ -0,0 +1,778 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.distributions.InverseGaussian + +## Class `InverseGaussian` + +Inherits From: [`Distribution`](../../tfp/distributions/Distribution.md) + +Inverse Gaussian distribution. + +The [inverse Gaussian distribution] +(https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution) +is parameterized by a `loc` and a `concentration` parameter. It's also known +as the Wald distribution. Some, e.g., the Python scipy package, refer to the +special case when `loc` is 1 as the Wald distribution. + +The "inverse" in the name does not refer to the distribution associated to +the multiplicative inverse of a random variable. Rather, the cumulant +generating function of this distribution is the inverse to that of a Gaussian +random variable. + +#### Mathematical Details + +The probability density function (pdf) is, + +```none +pdf(x; mu, lambda) = [lambda / (2 pi x ** 3)] ** 0.5 + exp{-lambda(x - mu) ** 2 / (2 mu ** 2 x)} +``` + +where +* `loc = mu` +* `concentration = lambda`. + +The support of the distribution is defined on `(0, infinity)`. + +Mapping to R and Python scipy's parameterization: +* R: statmod::invgauss + - mean = loc + - shape = concentration + - dispersion = 1 / concentration. Used only if shape is NULL. +* Python: scipy.stats.invgauss + - mu = loc / concentration + - scale = concentration + +

__init__

+ +``` python +__init__( + loc, + concentration, + validate_args=False, + allow_nan_stats=True, + name='InverseGaussian' +) +``` + +Constructs inverse Gaussian distribution with `loc` and `concentration`. + +#### Args: + +* `loc`: Floating-point `Tensor`, the loc params. Must contain only positive + values. +* `concentration`: Floating-point `Tensor`, the concentration params. + Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + Default value: `False` (i.e. do not validate args). +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + Default value: `True`. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: 'InverseGaussian'. + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

concentration

+ +Concentration parameter. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

loc

+ +Location parameter. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +Additional documentation from `InverseGaussian`: + +The mean of inverse Gaussian is the `loc` parameter. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + + +Additional documentation from `InverseGaussian`: + +The variance of inverse Gaussian is `loc` ** 3 / `concentration`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Kumaraswamy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Kumaraswamy.md index 710fab2c1e..eff2fde199 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Kumaraswamy.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Kumaraswamy.md @@ -1,5 +1,6 @@
+ @@ -106,6 +107,41 @@ x = [.2, .3, .5] dist.prob(x) # Shape [2, 3] ``` +

__init__

+ +``` python +__init__( + concentration1=None, + concentration0=None, + validate_args=False, + allow_nan_stats=True, + name='Kumaraswamy' +) +``` + +Initialize a batch of Kumaraswamy distributions. + +#### Args: + +* `concentration1`: Positive floating-point `Tensor` indicating mean + number of successes; aka "alpha". Implies `self.dtype` and + `self.batch_shape`, i.e., + `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. +* `concentration0`: Positive floating-point `Tensor` indicating mean + number of failures; aka "beta". Otherwise has same semantics as + `concentration1`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -195,39 +231,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - concentration1=None, - concentration0=None, - validate_args=False, - allow_nan_stats=True, - name='Kumaraswamy' -) -``` - -Initialize a batch of Kumaraswamy distributions. - -#### Args: - -* `concentration1`: Positive floating-point `Tensor` indicating mean - number of successes; aka "alpha". Implies `self.dtype` and - `self.batch_shape`, i.e., - `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. -* `concentration0`: Positive floating-point `Tensor` indicating mean - number of failures; aka "beta". Otherwise has same semantics as - `concentration1`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -367,7 +370,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -461,7 +464,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LKJ.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LKJ.md index 937614b990..4a35d392c2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LKJ.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LKJ.md @@ -1,5 +1,6 @@
+ @@ -68,6 +69,44 @@ ans = dist.sample(sample_shape=[2, 3], seed=42) # shape of ans is [2, 3, 3, 3] ``` +

__init__

+ +``` python +__init__( + dimension, + concentration, + validate_args=False, + allow_nan_stats=True, + name='LKJ' +) +``` + +Construct LKJ distributions. + +#### Args: + +* `dimension`: Python `int`. The dimension of the correlation matrices + to sample. +* `concentration`: `float` or `double` `Tensor`. The positive concentration + parameter of the LKJ distributions. The pdf of a sample matrix `X` is + proportional to `det(X) ** (concentration - 1)`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value `NaN` to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: If `dimension` is negative. + + + ## Properties

allow_nan_stats

@@ -149,42 +188,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - dimension, - concentration, - validate_args=False, - allow_nan_stats=True, - name='LKJ' -) -``` - -Construct LKJ distributions. - -#### Args: - -* `dimension`: Python `int`. The dimension of the correlation matrices - to sample. -* `concentration`: `float` or `double` `Tensor`. The positive concentration - parameter of the LKJ distributions. The pdf of a sample matrix `X` is - proportional to `det(X) ** (concentration - 1)`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value `NaN` to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: If `dimension` is negative. -

batch_shape_tensor

``` python @@ -324,7 +327,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -418,7 +421,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Laplace.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Laplace.md index e885e8e176..58a3019774 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Laplace.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Laplace.md @@ -1,5 +1,6 @@
+ @@ -67,6 +68,46 @@ X ~ Laplace(loc=0, scale=1) Y = loc + scale * X ``` +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='Laplace' +) +``` + +Construct Laplace distribution with parameters `loc` and `scale`. + +The parameters `loc` and `scale` must be shaped in a way that supports +broadcasting (e.g., `loc / scale` is a valid operation). + +#### Args: + +* `loc`: Floating point tensor which characterizes the location (center) + of the distribution. +* `scale`: Positive floating point tensor which characterizes the spread of + the distribution. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if `loc` and `scale` are of different dtype. + + + ## Properties

allow_nan_stats

@@ -148,44 +189,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='Laplace' -) -``` - -Construct Laplace distribution with parameters `loc` and `scale`. - -The parameters `loc` and `scale` must be shaped in a way that supports -broadcasting (e.g., `loc / scale` is a valid operation). - -#### Args: - -* `loc`: Floating point tensor which characterizes the location (center) - of the distribution. -* `scale`: Positive floating point tensor which characterizes the spread of - the distribution. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if `loc` and `scale` are of different dtype. -

batch_shape_tensor

``` python @@ -325,7 +328,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -419,7 +422,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LaplaceWithSoftplusScale.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LaplaceWithSoftplusScale.md index faa0c9b033..94f95a2b43 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LaplaceWithSoftplusScale.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LaplaceWithSoftplusScale.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,22 @@ Inherits From: [`Laplace`](../../tfp/distributions/Laplace.md) Laplace with softplus applied to `scale`. +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='LaplaceWithSoftplusScale' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -125,20 +142,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='LaplaceWithSoftplusScale' -) -``` - - -

batch_shape_tensor

``` python @@ -278,7 +281,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -372,7 +375,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LinearGaussianStateSpaceModel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LinearGaussianStateSpaceModel.md index 453a3ab5a3..6d858bd5f0 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LinearGaussianStateSpaceModel.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LinearGaussianStateSpaceModel.md @@ -1,5 +1,6 @@
+ @@ -154,6 +155,68 @@ final_step = tfd.MultivariateNormalFullCovariance( * TODO(davmre): show example of fitting parameters. +

__init__

+ +``` python +__init__( + num_timesteps, + transition_matrix, + transition_noise, + observation_matrix, + observation_noise, + initial_state_prior, + initial_step=0, + validate_args=False, + allow_nan_stats=True, + name='LinearGaussianStateSpaceModel' +) +``` + +Initialize a `LinearGaussianStateSpaceModel. + +#### Args: + +* `num_timesteps`: Python `int` total number of timesteps. +* `transition_matrix`: A transition operator, represented by a Tensor or + LinearOperator of shape `[latent_size, latent_size]`, or by a + callable taking as argument a scalar integer Tensor `t` and + returning a Tensor or LinearOperator representing the transition + operator from latent state at time `t` to time `t + 1`. +* `transition_noise`: An instance of + `tfd.MultivariateNormalLinearOperator` with event shape + `[latent_size]`, representing the mean and covariance of the + transition noise model, or a callable taking as argument a + scalar integer Tensor `t` and returning such a distribution + representing the noise in the transition from time `t` to time `t + 1`. +* `observation_matrix`: An observation operator, represented by a Tensor + or LinearOperator of shape `[observation_size, latent_size]`, + or by a callable taking as argument a scalar integer Tensor + `t` and returning a timestep-specific Tensor or + LinearOperator. +* `observation_noise`: An instance of + `tfd.MultivariateNormalLinearOperator` with event shape + `[observation_size]`, representing the mean and covariance of + the observation noise model, or a callable taking as argument + a scalar integer Tensor `t` and returning a timestep-specific + noise model. +* `initial_state_prior`: An instance of `MultivariateNormalLinearOperator` + representing the prior distribution on latent states; must + have event shape `[latent_size]`. +* `initial_step`: optional `int` specifying the time of the first + modeled timestep. This is added as an offset when passing + timesteps `t` to (optional) callables specifying + timestep-specific transition and observation models. +* `validate_args`: Python `bool`, default `False`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are + invalid, correct behavior is not guaranteed. +* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. +* `name`: The name to give Ops created by the initializer. + + + ## Properties

allow_nan_stats

@@ -227,65 +290,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - num_timesteps, - transition_matrix, - transition_noise, - observation_matrix, - observation_noise, - initial_state_prior, - initial_step=0, - validate_args=False, - allow_nan_stats=True, - name='LinearGaussianStateSpaceModel' -) -``` - -Initialize a `LinearGaussianStateSpaceModel. - -#### Args: - -* `num_timesteps`: Python `int` total number of timesteps. -* `transition_matrix`: A transition operator, represented by a Tensor or - LinearOperator of shape `[latent_size, latent_size]`, or by a - callable taking as argument a scalar integer Tensor `t` and - returning a timestep-specific Tensor or LinearOperator. -* `transition_noise`: An instance of - `tfd.MultivariateNormalLinearOperator` with event shape - `[latent_size]`, representing the mean and covariance of the - transition noise model, or a callable taking as argument a - scalar integer Tensor `t` and returning a timestep-specific - noise model. -* `observation_matrix`: An observation operator, represented by a Tensor - or LinearOperator of shape `[observation_size, latent_size]`, - or by a callable taking as argument a scalar integer Tensor - `t` and returning a timestep-specific Tensor or - LinearOperator. -* `observation_noise`: An instance of - `tfd.MultivariateNormalLinearOperator` with event shape - `[observation_size]`, representing the mean and covariance of - the observation noise model, or a callable taking as argument - a scalar integer Tensor `t` and returning a timestep-specific - noise model. -* `initial_state_prior`: An instance of `MultivariateNormalLinearOperator` - representing the prior distribution on latent states; must - have event shape `[latent_size]`. -* `initial_step`: optional `int` specifying the time of the first - modeled timestep. This is added as an offset when passing - timesteps `t` to (optional) callables specifying - timestep-specific transition and observation models. -* `validate_args`: Python `bool`, default `False`. Whether to validate input - with asserts. If `validate_args` is `False`, and the inputs are - invalid, correct behavior is not guaranteed. -* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an - exception if a statistic (e.g. mean/mode/etc...) is undefined for any - batch member If `True`, batch members with valid parameters leading to - undefined statistics will return NaN for this statistic. -* `name`: The name to give Ops created by the initializer. -

batch_shape_tensor

``` python @@ -425,7 +429,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -467,6 +471,15 @@ forward_filter(x) Run a Kalman filter over a provided sequence of outputs. +Note that the returned values `filtered_means`, `predicted_means`, and +`observation_means` depend on the observed time series `x`, while the +corresponding covariances are independent of the observed series; i.e., they +depend only on the model itself. This means that the mean values have shape +`concat([sample_shape(x), batch_shape, [num_timesteps, +{latent/observation}_size]])`, while the covariances have shape +`concat[(batch_shape, [num_timesteps, {latent/observation}_size, +{latent/observation}_size]])`, which does not depend on the sample shape. + #### Args: * `x`: a float-type `Tensor` with rightmost dimensions @@ -483,21 +496,22 @@ Run a Kalman filter over a provided sequence of outputs. of shape `sample_shape(x) + batch_shape + [num_timesteps].` * `filtered_means`: Means of the per-timestep filtered marginal distributions p(z_t | x_{:t}), as a Tensor of shape - `batch_shape + [num_timesteps, latent_size]`. + `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`. * `filtered_covs`: Covariances of the per-timestep filtered marginal distributions p(z_t | x_{:t}), as a Tensor of shape `batch_shape + [num_timesteps, latent_size, latent_size]`. * `predicted_means`: Means of the per-timestep predictive distributions over latent states, p(z_{t+1} | x_{:t}), as a - Tensor of shape `batch_shape + [num_timesteps, latent_size]`. + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, latent_size]`. * `predicted_covs`: Covariances of the per-timestep predictive distributions over latent states, p(z_{t+1} | x_{:t}), as a Tensor of shape `batch_shape + [num_timesteps, latent_size, latent_size]`. * `observation_means`: Means of the per-timestep predictive distributions over observations, p(x_{t} | x_{:t-1}), as a - Tensor of shape `batch_shape + [num_timesteps, - observation_size]`. + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, observation_size]`. * `observation_covs`: Covariances of the per-timestep predictive distributions over observations, p(x_{t} | x_{:t-1}), as a Tensor of shape `batch_shape + [num_timesteps, @@ -563,7 +577,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LogNormal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LogNormal.md index 5285e60ea1..c59cb1630a 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LogNormal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/LogNormal.md @@ -1,5 +1,6 @@
+ @@ -46,6 +47,42 @@ Inherits From: [`TransformedDistribution`](../../tfp/distributions/TransformedDi The log-normal distribution. +

__init__

+ +``` python +__init__( + loc=None, + scale=None, + validate_args=False, + allow_nan_stats=True, + name='LogNormal' +) +``` + +Construct a log-normal distribution. + +The LogNormal distribution models positive-valued random variables +whose logarithm is normally distributed with mean `loc` and +standard deviation `scale`. It is constructed as the exponential +transformation of a Normal distribution. + +#### Args: + +* `loc`: Floating-point `Tensor`; the means of the underlying + Normal distribution(s). +* `scale`: Floating-point `Tensor`; the stddevs of the underlying + Normal distribution(s). +* `validate_args`: Python `bool`, default `False`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are + invalid, correct behavior is not guaranteed. +* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. +* `name`: The name to give Ops created by the initializer. + + + ## Properties

allow_nan_stats

@@ -135,40 +172,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale=None, - validate_args=False, - allow_nan_stats=True, - name='LogNormal' -) -``` - -Construct a log-normal distribution. - -The LogNormal distribution models positive-valued random variables -whose logarithm is normally distributed with mean `loc` and -standard deviation `scale`. It is constructed as the exponential -transformation of a Normal distribution. - -#### Args: - -* `loc`: Floating-point `Tensor`; the means of the underlying - Normal distribution(s). -* `scale`: Floating-point `Tensor`; the stddevs of the underlying - Normal distribution(s). -* `validate_args`: Python `bool`, default `False`. Whether to validate input - with asserts. If `validate_args` is `False`, and the inputs are - invalid, correct behavior is not guaranteed. -* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an - exception if a statistic (e.g. mean/mode/etc...) is undefined for any - batch member If `True`, batch members with valid parameters leading to - undefined statistics will return NaN for this statistic. -* `name`: The name to give Ops created by the initializer. -

batch_shape_tensor

``` python @@ -308,7 +311,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -402,7 +405,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Logistic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Logistic.md index 03d9e966cc..31192d7318 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Logistic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Logistic.md @@ -1,5 +1,6 @@
+ @@ -97,6 +98,45 @@ dist = tfd.Logistic(loc=1., scale=[11, 22.]) dist.prob(3.0) ``` +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='Logistic' +) +``` + +Construct Logistic distributions with mean and scale `loc` and `scale`. + +The parameters `loc` and `scale` must be shaped in a way that supports +broadcasting (e.g. `loc + scale` is a valid operation). + +#### Args: + +* `loc`: Floating point tensor, the means of the distribution(s). +* `scale`: Floating point tensor, the scales of the distribution(s). Must + contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: The name to give Ops created by the initializer. + + +#### Raises: + +* `TypeError`: if loc and scale are different dtypes. + + + ## Properties

allow_nan_stats

@@ -178,43 +218,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='Logistic' -) -``` - -Construct Logistic distributions with mean and scale `loc` and `scale`. - -The parameters `loc` and `scale` must be shaped in a way that supports -broadcasting (e.g. `loc + scale` is a valid operation). - -#### Args: - -* `loc`: Floating point tensor, the means of the distribution(s). -* `scale`: Floating point tensor, the scales of the distribution(s). Must - contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: The name to give Ops created by the initializer. - - -#### Raises: - -* `TypeError`: if loc and scale are different dtypes. -

batch_shape_tensor

``` python @@ -354,7 +357,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -448,7 +451,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Mixture.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Mixture.md index 9c2de894f1..9f6dcf2a17 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Mixture.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Mixture.md @@ -1,5 +1,6 @@
+ @@ -73,6 +74,67 @@ x = tf.linspace(-2., 3., int(1e4)).eval() plt.plot(x, bimix_gauss.prob(x).eval()); ``` +

__init__

+ +``` python +__init__( + cat, + components, + validate_args=False, + allow_nan_stats=True, + use_static_graph=False, + name='Mixture' +) +``` + +Initialize a Mixture distribution. + +A `Mixture` is defined by a `Categorical` (`cat`, representing the +mixture probabilities) and a list of `Distribution` objects +all having matching dtype, batch shape, event shape, and continuity +properties (the components). + +The `num_classes` of `cat` must be possible to infer at graph construction +time and match `len(components)`. + +#### Args: + +* `cat`: A `Categorical` distribution instance, representing the probabilities + of `distributions`. +* `components`: A list or tuple of `Distribution` instances. + Each instance must have the same type, be defined on the same domain, + and have matching `event_shape` and `batch_shape`. +* `validate_args`: Python `bool`, default `False`. If `True`, raise a runtime + error if batch or event ranks are inconsistent between cat and any of + the distributions. This is only checked if the ranks cannot be + determined statically at graph construction time. +* `allow_nan_stats`: Boolean, default `True`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member. If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. +* `use_static_graph`: Calls to `sample` will not rely on dynamic tensor + indexing, allowing for some static graph compilation optimizations, but + at the expense of sampling all underlying distributions in the mixture. + (Possibly useful when running on TPUs). + Default value: `False` (i.e., use dynamic indexing). +* `name`: A name for this distribution (optional). + + +#### Raises: + +* `TypeError`: If cat is not a `Categorical`, or `components` is not + a list or tuple, or the elements of `components` are not + instances of `Distribution`, or do not have matching `dtype`. +* `ValueError`: If `components` is an empty list or tuple, or its + elements do not have a statically known event rank. + If `cat.num_classes` cannot be inferred at graph creation time, + or the constant value of `cat.num_classes` is not equal to + `len(components)`, or all `components` and `cat` do not have + matching static batch shapes, or all components do not + have matching static event shapes. + + + ## Properties

allow_nan_stats

@@ -158,65 +220,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - cat, - components, - validate_args=False, - allow_nan_stats=True, - use_static_graph=False, - name='Mixture' -) -``` - -Initialize a Mixture distribution. - -A `Mixture` is defined by a `Categorical` (`cat`, representing the -mixture probabilities) and a list of `Distribution` objects -all having matching dtype, batch shape, event shape, and continuity -properties (the components). - -The `num_classes` of `cat` must be possible to infer at graph construction -time and match `len(components)`. - -#### Args: - -* `cat`: A `Categorical` distribution instance, representing the probabilities - of `distributions`. -* `components`: A list or tuple of `Distribution` instances. - Each instance must have the same type, be defined on the same domain, - and have matching `event_shape` and `batch_shape`. -* `validate_args`: Python `bool`, default `False`. If `True`, raise a runtime - error if batch or event ranks are inconsistent between cat and any of - the distributions. This is only checked if the ranks cannot be - determined statically at graph construction time. -* `allow_nan_stats`: Boolean, default `True`. If `False`, raise an - exception if a statistic (e.g. mean/mode/etc...) is undefined for any - batch member. If `True`, batch members with valid parameters leading to - undefined statistics will return NaN for this statistic. -* `use_static_graph`: Calls to `sample` will not rely on dynamic tensor - indexing, allowing for some static graph compilation optimizations, but - at the expense of sampling all underlying distributions in the mixture. - (Possibly useful when running on TPUs). - Default value: `False` (i.e., use dynamic indexing). -* `name`: A name for this distribution (optional). - - -#### Raises: - -* `TypeError`: If cat is not a `Categorical`, or `components` is not - a list or tuple, or the elements of `components` are not - instances of `Distribution`, or do not have matching `dtype`. -* `ValueError`: If `components` is an empty list or tuple, or its - elements do not have a statically known event rank. - If `cat.num_classes` cannot be inferred at graph creation time, - or the constant value of `cat.num_classes` is not equal to - `len(components)`, or all `components` and `cat` do not have - matching static batch shapes, or all components do not - have matching static event shapes. -

batch_shape_tensor

``` python @@ -356,7 +359,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -497,7 +500,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MixtureSameFamily.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MixtureSameFamily.md index 6ed2d87dc8..cb744f33fe 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MixtureSameFamily.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MixtureSameFamily.md @@ -1,5 +1,6 @@
+ @@ -104,6 +105,52 @@ plt.contour(grid[..., 0], grid[..., 1], gm.prob(grid).eval()); ``` +

__init__

+ +``` python +__init__( + mixture_distribution, + components_distribution, + validate_args=False, + allow_nan_stats=True, + name='MixtureSameFamily' +) +``` + +Construct a `MixtureSameFamily` distribution. + +#### Args: + +* `mixture_distribution`: `tf.distributions.Categorical`-like instance. + Manages the probability of selecting components. The number of + categories must match the rightmost batch dimension of the + `components_distribution`. Must have either scalar `batch_shape` or + `batch_shape` matching `components_distribution.batch_shape[:-1]`. +* `components_distribution`: `tf.distributions.Distribution`-like instance. + Right-most batch dimension indexes components. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: `if not mixture_distribution.dtype.is_integer`. +* `ValueError`: if mixture_distribution does not have scalar `event_shape`. +* `ValueError`: if `mixture_distribution.batch_shape` and + `components_distribution.batch_shape[:-1]` are both fully defined and + the former is neither scalar nor equal to the latter. +* `ValueError`: if `mixture_distribution` categories does not equal + `components_distribution` rightmost batch shape. + + + ## Properties

allow_nan_stats

@@ -185,50 +232,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - mixture_distribution, - components_distribution, - validate_args=False, - allow_nan_stats=True, - name='MixtureSameFamily' -) -``` - -Construct a `MixtureSameFamily` distribution. - -#### Args: - -* `mixture_distribution`: `tf.distributions.Categorical`-like instance. - Manages the probability of selecting components. The number of - categories must match the rightmost batch dimension of the - `components_distribution`. Must have either scalar `batch_shape` or - `batch_shape` matching `components_distribution.batch_shape[:-1]`. -* `components_distribution`: `tf.distributions.Distribution`-like instance. - Right-most batch dimension indexes components. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: `if not mixture_distribution.dtype.is_integer`. -* `ValueError`: if mixture_distribution does not have scalar `event_shape`. -* `ValueError`: if `mixture_distribution.batch_shape` and - `components_distribution.batch_shape[:-1]` are both fully defined and - the former is neither scalar nor equal to the latter. -* `ValueError`: if `mixture_distribution` categories does not equal - `components_distribution` rightmost batch shape. -

batch_shape_tensor

``` python @@ -368,7 +371,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -462,7 +465,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Multinomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Multinomial.md index 7654d3f0a9..f51c75c240 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Multinomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Multinomial.md @@ -1,5 +1,6 @@
+ @@ -137,6 +138,49 @@ dist.prob(counts) # Shape [2] dist.sample(5) # Shape [5, 2, 3] ``` +

__init__

+ +``` python +__init__( + total_count, + logits=None, + probs=None, + validate_args=False, + allow_nan_stats=True, + name='Multinomial' +) +``` + +Initialize a batch of Multinomial distributions. + +#### Args: + +* `total_count`: Non-negative floating point tensor with shape broadcastable + to `[N1,..., Nm]` with `m >= 0`. Defines this as a batch of + `N1 x ... x Nm` different Multinomial distributions. Its components + should be equal to integer values. +* `logits`: Floating point tensor representing unnormalized log-probabilities + of a positive event with shape broadcastable to + `[N1,..., Nm, K]` `m >= 0`, and the same dtype as `total_count`. Defines + this as a batch of `N1 x ... x Nm` different `K` class Multinomial + distributions. Only one of `logits` or `probs` should be passed in. +* `probs`: Positive floating point tensor with shape broadcastable to + `[N1,..., Nm, K]` `m >= 0` and same dtype as `total_count`. Defines + this as a batch of `N1 x ... x Nm` different `K` class Multinomial + distributions. `probs`'s components in the last portion of its shape + should sum to `1`. Only one of `logits` or `probs` should be passed in. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -222,47 +266,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - total_count, - logits=None, - probs=None, - validate_args=False, - allow_nan_stats=True, - name='Multinomial' -) -``` - -Initialize a batch of Multinomial distributions. - -#### Args: - -* `total_count`: Non-negative floating point tensor with shape broadcastable - to `[N1,..., Nm]` with `m >= 0`. Defines this as a batch of - `N1 x ... x Nm` different Multinomial distributions. Its components - should be equal to integer values. -* `logits`: Floating point tensor representing unnormalized log-probabilities - of a positive event with shape broadcastable to - `[N1,..., Nm, K]` `m >= 0`, and the same dtype as `total_count`. Defines - this as a batch of `N1 x ... x Nm` different `K` class Multinomial - distributions. Only one of `logits` or `probs` should be passed in. -* `probs`: Positive floating point tensor with shape broadcastable to - `[N1,..., Nm, K]` `m >= 0` and same dtype as `total_count`. Defines - this as a batch of `N1 x ... x Nm` different `K` class Multinomial - distributions. `probs`'s components in the last portion of its shape - should sum to `1`. Only one of `logits` or `probs` should be passed in. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -402,7 +405,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -496,7 +499,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiag.md index 7f6679188c..8276ddc3fb 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiag.md @@ -1,5 +1,6 @@
+ @@ -144,6 +145,76 @@ x = [[-1., 0, 1], mvn.prob(x).eval() # shape: [2] ``` +

__init__

+ +``` python +__init__( + loc=None, + scale_diag=None, + scale_identity_multiplier=None, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalDiag' +) +``` + +Construct Multivariate Normal distribution on `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this. + +Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is: + +```none +scale = diag(scale_diag + scale_identity_multiplier * ones(k)) +``` + +where: + +* `scale_diag.shape = [k]`, and, +* `scale_identity_multiplier.shape = []`. + +Additional leading dimensions (if any) will index batches. + +If both `scale_diag` and `scale_identity_multiplier` are `None`, then +`scale` is the Identity matrix. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal + matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, + and characterizes `b`-batches of `k x k` diagonal matrices added to + `scale`. When both `scale_identity_multiplier` and `scale_diag` are + `None` then `scale` is the `Identity`. +* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing + a scaled-identity-matrix added to `scale`. May have shape + `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled + `k x k` identity matrices added to `scale`. When both + `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is + the `Identity`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if at most `scale_identity_multiplier` is specified. + + + ## Properties

allow_nan_stats

@@ -233,74 +304,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale_diag=None, - scale_identity_multiplier=None, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalDiag' -) -``` - -Construct Multivariate Normal distribution on `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this. - -Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is: - -```none -scale = diag(scale_diag + scale_identity_multiplier * ones(k)) -``` - -where: - -* `scale_diag.shape = [k]`, and, -* `scale_identity_multiplier.shape = []`. - -Additional leading dimensions (if any) will index batches. - -If both `scale_diag` and `scale_identity_multiplier` are `None`, then -`scale` is the Identity matrix. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal - matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, - and characterizes `b`-batches of `k x k` diagonal matrices added to - `scale`. When both `scale_identity_multiplier` and `scale_diag` are - `None` then `scale` is the `Identity`. -* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing - a scaled-identity-matrix added to `scale`. May have shape - `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled - `k x k` identity matrices added to `scale`. When both - `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is - the `Identity`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if at most `scale_identity_multiplier` is specified. -

batch_shape_tensor

``` python @@ -440,7 +443,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -534,7 +537,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagPlusLowRank.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagPlusLowRank.md index bd79ce4bbf..9144c9fae3 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagPlusLowRank.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagPlusLowRank.md @@ -1,5 +1,6 @@
+ @@ -152,6 +153,91 @@ x = [[-0.9, 0, 0.1], mvn.prob(x).eval() # shape: [2] ``` +

__init__

+ +``` python +__init__( + loc=None, + scale_diag=None, + scale_identity_multiplier=None, + scale_perturb_factor=None, + scale_perturb_diag=None, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalDiagPlusLowRank' +) +``` + +Construct Multivariate Normal distribution on `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this. + +Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is: + +```none +scale = diag(scale_diag + scale_identity_multiplier ones(k)) + + scale_perturb_factor @ diag(scale_perturb_diag) @ scale_perturb_factor.T +``` + +where: + +* `scale_diag.shape = [k]`, +* `scale_identity_multiplier.shape = []`, +* `scale_perturb_factor.shape = [k, r]`, typically `k >> r`, and, +* `scale_perturb_diag.shape = [r]`. + +Additional leading dimensions (if any) will index batches. + +If both `scale_diag` and `scale_identity_multiplier` are `None`, then +`scale` is the Identity matrix. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal + matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, + and characterizes `b`-batches of `k x k` diagonal matrices added to + `scale`. When both `scale_identity_multiplier` and `scale_diag` are + `None` then `scale` is the `Identity`. +* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing + a scaled-identity-matrix added to `scale`. May have shape + `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled + `k x k` identity matrices added to `scale`. When both + `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is + the `Identity`. +* `scale_perturb_factor`: Floating-point `Tensor` representing a rank-`r` + perturbation added to `scale`. May have shape `[B1, ..., Bb, k, r]`, + `b >= 0`, and characterizes `b`-batches of rank-`r` updates to `scale`. + When `None`, no rank-`r` update is added to `scale`. +* `scale_perturb_diag`: Floating-point `Tensor` representing a diagonal matrix + inside the rank-`r` perturbation added to `scale`. May have shape + `[B1, ..., Bb, r]`, `b >= 0`, and characterizes `b`-batches of `r x r` + diagonal matrices inside the perturbation added to `scale`. When + `None`, an identity matrix is used inside the perturbation. Can only be + specified if `scale_perturb_factor` is also specified. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if at most `scale_identity_multiplier` is specified. + + + ## Properties

allow_nan_stats

@@ -241,89 +327,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale_diag=None, - scale_identity_multiplier=None, - scale_perturb_factor=None, - scale_perturb_diag=None, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalDiagPlusLowRank' -) -``` - -Construct Multivariate Normal distribution on `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this. - -Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is: - -```none -scale = diag(scale_diag + scale_identity_multiplier ones(k)) + - scale_perturb_factor @ diag(scale_perturb_diag) @ scale_perturb_factor.T -``` - -where: - -* `scale_diag.shape = [k]`, -* `scale_identity_multiplier.shape = []`, -* `scale_perturb_factor.shape = [k, r]`, typically `k >> r`, and, -* `scale_perturb_diag.shape = [r]`. - -Additional leading dimensions (if any) will index batches. - -If both `scale_diag` and `scale_identity_multiplier` are `None`, then -`scale` is the Identity matrix. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal - matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, - and characterizes `b`-batches of `k x k` diagonal matrices added to - `scale`. When both `scale_identity_multiplier` and `scale_diag` are - `None` then `scale` is the `Identity`. -* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing - a scaled-identity-matrix added to `scale`. May have shape - `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled - `k x k` identity matrices added to `scale`. When both - `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is - the `Identity`. -* `scale_perturb_factor`: Floating-point `Tensor` representing a rank-`r` - perturbation added to `scale`. May have shape `[B1, ..., Bb, k, r]`, - `b >= 0`, and characterizes `b`-batches of rank-`r` updates to `scale`. - When `None`, no rank-`r` update is added to `scale`. -* `scale_perturb_diag`: Floating-point `Tensor` representing a diagonal matrix - inside the rank-`r` perturbation added to `scale`. May have shape - `[B1, ..., Bb, r]`, `b >= 0`, and characterizes `b`-batches of `r x r` - diagonal matrices inside the perturbation added to `scale`. When - `None`, an identity matrix is used inside the perturbation. Can only be - specified if `scale_perturb_factor` is also specified. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if at most `scale_identity_multiplier` is specified. -

batch_shape_tensor

``` python @@ -463,7 +466,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -557,7 +560,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagWithSoftplusScale.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagWithSoftplusScale.md index a754825593..2783bc1b9e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagWithSoftplusScale.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalDiagWithSoftplusScale.md @@ -1,5 +1,6 @@
+ @@ -46,6 +47,22 @@ Inherits From: [`MultivariateNormalDiag`](../../tfp/distributions/MultivariateNo MultivariateNormalDiag with `diag_stddev = softplus(diag_stddev)`. +

__init__

+ +``` python +__init__( + loc, + scale_diag, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalDiagWithSoftplusScale' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -135,20 +152,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale_diag, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalDiagWithSoftplusScale' -) -``` - - -

batch_shape_tensor

``` python @@ -288,7 +291,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -382,7 +385,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalFullCovariance.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalFullCovariance.md index 4fa6197660..9ba5c21222 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalFullCovariance.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalFullCovariance.md @@ -1,5 +1,6 @@
+ @@ -122,6 +123,60 @@ mvn.prob(x).eval() # shape: [2] ``` +

__init__

+ +``` python +__init__( + loc=None, + covariance_matrix=None, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalFullCovariance' +) +``` + +Construct Multivariate Normal distribution on `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and +`covariance_matrix` arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`covariance_matrix`. The last dimension of `loc` (if provided) must +broadcast with this. + +A non-batch `covariance_matrix` matrix is a `k x k` symmetric positive +definite matrix. In other words it is (real) symmetric with all eigenvalues +strictly positive. + +Additional leading dimensions (if any) will index batches. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `covariance_matrix`: Floating-point, symmetric positive definite `Tensor` of + same `dtype` as `loc`. The strict upper triangle of `covariance_matrix` + is ignored, so if `covariance_matrix` is not symmetric no error will be + raised (unless `validate_args is True`). `covariance_matrix` has shape + `[B1, ..., Bb, k, k]` where `b >= 0` and `k` is the event size. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if neither `loc` nor `covariance_matrix` are specified. + + + ## Properties

allow_nan_stats

@@ -211,58 +266,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - covariance_matrix=None, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalFullCovariance' -) -``` - -Construct Multivariate Normal distribution on `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and -`covariance_matrix` arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`covariance_matrix`. The last dimension of `loc` (if provided) must -broadcast with this. - -A non-batch `covariance_matrix` matrix is a `k x k` symmetric positive -definite matrix. In other words it is (real) symmetric with all eigenvalues -strictly positive. - -Additional leading dimensions (if any) will index batches. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `covariance_matrix`: Floating-point, symmetric positive definite `Tensor` of - same `dtype` as `loc`. The strict upper triangle of `covariance_matrix` - is ignored, so if `covariance_matrix` is not symmetric no error will be - raised (unless `validate_args is True`). `covariance_matrix` has shape - `[B1, ..., Bb, k, k]` where `b >= 0` and `k` is the event size. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if neither `loc` nor `covariance_matrix` are specified. -

batch_shape_tensor

``` python @@ -402,7 +405,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -496,7 +499,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalLinearOperator.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalLinearOperator.md index cfc1712611..7bf1a74767 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalLinearOperator.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalLinearOperator.md @@ -1,5 +1,6 @@
+ @@ -121,6 +122,54 @@ x = [[-0.9, 0, 0.1], mvn.prob(x).eval() # shape: [2] ``` +

__init__

+ +``` python +__init__( + loc=None, + scale=None, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalLinearOperator' +) +``` + +Construct Multivariate Normal distribution on `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this. + +Recall that `covariance = scale @ scale.T`. + +Additional leading dimensions (if any) will index batches. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale`: Instance of `LinearOperator` with same `dtype` as `loc` and shape + `[B1, ..., Bb, k, k]`. +* `validate_args`: Python `bool`, default `False`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are + invalid, correct behavior is not guaranteed. +* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. +* `name`: The name to give Ops created by the initializer. + + +#### Raises: + +* `ValueError`: if `scale` is unspecified. +* `TypeError`: if not `scale.dtype.is_floating` + + + ## Properties

allow_nan_stats

@@ -210,52 +259,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale=None, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalLinearOperator' -) -``` - -Construct Multivariate Normal distribution on `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this. - -Recall that `covariance = scale @ scale.T`. - -Additional leading dimensions (if any) will index batches. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale`: Instance of `LinearOperator` with same `dtype` as `loc` and shape - `[B1, ..., Bb, k, k]`. -* `validate_args`: Python `bool`, default `False`. Whether to validate input - with asserts. If `validate_args` is `False`, and the inputs are - invalid, correct behavior is not guaranteed. -* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an - exception if a statistic (e.g. mean/mode/etc...) is undefined for any - batch member If `True`, batch members with valid parameters leading to - undefined statistics will return NaN for this statistic. -* `name`: The name to give Ops created by the initializer. - - -#### Raises: - -* `ValueError`: if `scale` is unspecified. -* `TypeError`: if not `scale.dtype.is_floating` -

batch_shape_tensor

``` python @@ -395,7 +398,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -489,7 +492,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalTriL.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalTriL.md index bbf02e9b70..9078ef47c8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalTriL.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/MultivariateNormalTriL.md @@ -1,5 +1,6 @@
+ @@ -145,6 +146,62 @@ with tf.variable_scope("model"): dtype=tf.float32, name="chol_Sigma"))) ``` +

__init__

+ +``` python +__init__( + loc=None, + scale_tril=None, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalTriL' +) +``` + +Construct Multivariate Normal distribution on `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this. + +Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is: + +```none +scale = scale_tril +``` + +where `scale_tril` is lower-triangular `k x k` matrix with non-zero +diagonal, i.e., `tf.diag_part(scale_tril) != 0`. + +Additional leading dimensions (if any) will index batches. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale_tril`: Floating-point, lower-triangular `Tensor` with non-zero + diagonal elements. `scale_tril` has shape `[B1, ..., Bb, k, k]` where + `b >= 0` and `k` is the event size. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if neither `loc` nor `scale_tril` are specified. + + + ## Properties

allow_nan_stats

@@ -234,60 +291,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale_tril=None, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalTriL' -) -``` - -Construct Multivariate Normal distribution on `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this. - -Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is: - -```none -scale = scale_tril -``` - -where `scale_tril` is lower-triangular `k x k` matrix with non-zero -diagonal, i.e., `tf.diag_part(scale_tril) != 0`. - -Additional leading dimensions (if any) will index batches. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale_tril`: Floating-point, lower-triangular `Tensor` with non-zero - diagonal elements. `scale_tril` has shape `[B1, ..., Bb, k, k]` where - `b >= 0` and `k` is the event size. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if neither `loc` nor `scale_tril` are specified. -

batch_shape_tensor

``` python @@ -427,7 +430,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -521,7 +524,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NegativeBinomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NegativeBinomial.md index 1be003e7ab..30b2902c77 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NegativeBinomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NegativeBinomial.md @@ -1,5 +1,6 @@
+ @@ -63,6 +64,53 @@ where: * `Z` is the normalizaing constant, and, * `n!` is the factorial of `n`. +

__init__

+ +``` python +__init__( + total_count, + logits=None, + probs=None, + validate_args=False, + allow_nan_stats=True, + name='NegativeBinomial' +) +``` + +Construct NegativeBinomial distributions. + +#### Args: + +* `total_count`: Non-negative floating-point `Tensor` with shape + broadcastable to `[B1,..., Bb]` with `b >= 0` and the same dtype as + `probs` or `logits`. Defines this as a batch of `N1 x ... x Nm` + different Negative Binomial distributions. In practice, this represents + the number of negative Bernoulli trials to stop at (the `total_count` + of failures), but this is still a valid distribution when + `total_count` is a non-integer. +* `logits`: Floating-point `Tensor` with shape broadcastable to + `[B1, ..., Bb]` where `b >= 0` indicates the number of batch dimensions. + Each entry represents logits for the probability of success for + independent Negative Binomial distributions and must be in the open + interval `(-inf, inf)`. Only one of `logits` or `probs` should be + specified. +* `probs`: Positive floating-point `Tensor` with shape broadcastable to + `[B1, ..., Bb]` where `b >= 0` indicates the number of batch dimensions. + Each entry represents the probability of success for independent + Negative Binomial distributions and must be in the open interval + `(0, 1)`. Only one of `logits` or `probs` should be specified. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -148,51 +196,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - total_count, - logits=None, - probs=None, - validate_args=False, - allow_nan_stats=True, - name='NegativeBinomial' -) -``` - -Construct NegativeBinomial distributions. - -#### Args: - -* `total_count`: Non-negative floating-point `Tensor` with shape - broadcastable to `[B1,..., Bb]` with `b >= 0` and the same dtype as - `probs` or `logits`. Defines this as a batch of `N1 x ... x Nm` - different Negative Binomial distributions. In practice, this represents - the number of negative Bernoulli trials to stop at (the `total_count` - of failures), but this is still a valid distribution when - `total_count` is a non-integer. -* `logits`: Floating-point `Tensor` with shape broadcastable to - `[B1, ..., Bb]` where `b >= 0` indicates the number of batch dimensions. - Each entry represents logits for the probability of success for - independent Negative Binomial distributions and must be in the open - interval `(-inf, inf)`. Only one of `logits` or `probs` should be - specified. -* `probs`: Positive floating-point `Tensor` with shape broadcastable to - `[B1, ..., Bb]` where `b >= 0` indicates the number of batch dimensions. - Each entry represents the probability of success for independent - Negative Binomial distributions and must be in the open interval - `(0, 1)`. Only one of `logits` or `probs` should be specified. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -332,7 +335,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -426,7 +429,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Normal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Normal.md index ce109c094c..195788f5e1 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Normal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Normal.md @@ -1,5 +1,6 @@
+ @@ -70,15 +71,18 @@ Y = loc + scale * X Examples of initialization of one or a batch of distributions. ```python +import tensorflow_probability as tfp +tfd = tfp.distributions + # Define a single scalar Normal distribution. -dist = tf.distributions.Normal(loc=0., scale=3.) +dist = tfd.Normal(loc=0., scale=3.) # Evaluate the cdf at 1, returning a scalar. dist.cdf(1.) # Define a batch of two scalar valued Normals. # The first has mean 1 and standard deviation 11, the second 2 and 22. -dist = tf.distributions.Normal(loc=[1, 2.], scale=[11, 22.]) +dist = tfd.Normal(loc=[1, 2.], scale=[11, 22.]) # Evaluate the pdf of the first distribution on 0, and the second on 1.5, # returning a length two tensor. @@ -93,13 +97,52 @@ Arguments are broadcast when possible. ```python # Define a batch of two scalar valued Normals. # Both have mean 1, but different standard deviations. -dist = tf.distributions.Normal(loc=1., scale=[11, 22.]) +dist = tfd.Normal(loc=1., scale=[11, 22.]) # Evaluate the pdf of both distributions on the same point, 3.0, # returning a length 2 tensor. dist.prob(3.0) ``` +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='Normal' +) +``` + +Construct Normal distributions with mean and stddev `loc` and `scale`. + +The parameters `loc` and `scale` must be shaped in a way that supports +broadcasting (e.g. `loc + scale` is a valid operation). + +#### Args: + +* `loc`: Floating point tensor; the means of the distribution(s). +* `scale`: Floating point tensor; the stddevs of the distribution(s). + Must contain only positive values. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if `loc` and `scale` have different `dtype`. + + + ## Properties

allow_nan_stats

@@ -181,43 +224,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='Normal' -) -``` - -Construct Normal distributions with mean and stddev `loc` and `scale`. - -The parameters `loc` and `scale` must be shaped in a way that supports -broadcasting (e.g. `loc + scale` is a valid operation). - -#### Args: - -* `loc`: Floating point tensor; the means of the distribution(s). -* `scale`: Floating point tensor; the stddevs of the distribution(s). - Must contain only positive values. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if `loc` and `scale` have different `dtype`. -

batch_shape_tensor

``` python @@ -357,7 +363,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -451,7 +457,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NormalWithSoftplusScale.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NormalWithSoftplusScale.md index 9eddd1b5e2..41f545ef37 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NormalWithSoftplusScale.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/NormalWithSoftplusScale.md @@ -1,5 +1,6 @@
+ @@ -44,6 +45,22 @@ Inherits From: [`Normal`](../../tfp/distributions/Normal.md) Normal with softplus applied to `scale`. +

__init__

+ +``` python +__init__( + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='NormalWithSoftplusScale' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -125,20 +142,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='NormalWithSoftplusScale' -) -``` - - -

batch_shape_tensor

``` python @@ -278,7 +281,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -372,7 +375,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/OneHotCategorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/OneHotCategorical.md index 21e2f40411..6a7f6d83f7 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/OneHotCategorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/OneHotCategorical.md @@ -1,5 +1,6 @@
+ @@ -92,6 +93,46 @@ samples = [[0,1,0], [1,0,0]] dist.prob(samples) # Shape [2] ``` +

__init__

+ +``` python +__init__( + logits=None, + probs=None, + dtype=tf.int32, + validate_args=False, + allow_nan_stats=True, + name='OneHotCategorical' +) +``` + +Initialize OneHotCategorical distributions using class log-probabilities. + +#### Args: + +* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a + set of Categorical distributions. The first `N - 1` dimensions index + into a batch of independent distributions and the last dimension + represents a vector of logits for each class. Only one of `logits` or + `probs` should be passed in. +* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities of a set + of Categorical distributions. The first `N - 1` dimensions index into a + batch of independent distributions and the last dimension represents a + vector of probabilities for each class. Only one of `logits` or `probs` + should be passed in. +* `dtype`: The type of the event samples (default: int32). +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -177,44 +218,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - logits=None, - probs=None, - dtype=tf.int32, - validate_args=False, - allow_nan_stats=True, - name='OneHotCategorical' -) -``` - -Initialize OneHotCategorical distributions using class log-probabilities. - -#### Args: - -* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a - set of Categorical distributions. The first `N - 1` dimensions index - into a batch of independent distributions and the last dimension - represents a vector of logits for each class. Only one of `logits` or - `probs` should be passed in. -* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities of a set - of Categorical distributions. The first `N - 1` dimensions index into a - batch of independent distributions and the last dimension represents a - vector of probabilities for each class. Only one of `logits` or `probs` - should be passed in. -* `dtype`: The type of the event samples (default: int32). -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -354,7 +357,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -448,7 +451,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Pareto.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Pareto.md new file mode 100644 index 0000000000..56406d31f4 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Pareto.md @@ -0,0 +1,762 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.distributions.Pareto + +## Class `Pareto` + +Inherits From: [`Distribution`](../../tfp/distributions/Distribution.md) + +Pareto distribution. + +The Pareto distribution is parameterized by a `scale` and a +`concentration` parameter. + +#### Mathematical Details + +The probability density function (pdf) is, + +```none +pdf(x; alpha, scale, x >= scale) = alpha * scale ** alpha / x ** (alpha + 1) +``` + +where `concentration = alpha`. + +Note that `scale` acts as a scaling parameter, since +`Pareto(c, scale).pdf(x) == Pareto(c, 1.).pdf(x / scale)`. + +The support of the distribution is defined on `[scale, infinity)`. + +

__init__

+ +``` python +__init__( + concentration, + scale=1.0, + validate_args=False, + allow_nan_stats=True, + name='Pareto' +) +``` + +Construct Pareto distribution with `concentration` and `scale`. + +#### Args: + +* `concentration`: Floating point tensor. Must contain only positive values. +* `scale`: Floating point tensor, equivalent to `mode`. `scale` also + restricts the domain of this distribution to be in `[scale, inf)`. + Must contain only positive values. Default value: `1`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. Default value: `False` (i.e. do not validate args). +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + Default value: `True`. +* `name`: Python `str` name prefixed to Ops created by this class. + Default value: 'Pareto'. + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

concentration

+ +Concentration parameter for this distribution. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

scale

+ +Scale parameter and also the lower bound of the support. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +Additional documentation from `Pareto`: + +The mean of Pareto is defined` if `concentration > 1.`, otherwise it +is `Inf`. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + + +Additional documentation from `Pareto`: + +The variance of Pareto is defined` if `concentration > 2.`, otherwise +it is `Inf`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Poisson.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Poisson.md index fb39f5b850..941b8ad8d4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Poisson.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Poisson.md @@ -1,5 +1,6 @@
+ @@ -57,6 +58,45 @@ Z = exp(lambda). where `rate = lambda` and `Z` is the normalizing constant. +

__init__

+ +``` python +__init__( + rate=None, + log_rate=None, + validate_args=False, + allow_nan_stats=True, + name='Poisson' +) +``` + +Initialize a batch of Poisson distributions. + +#### Args: + +* `rate`: Floating point tensor, the rate parameter. `rate` must be positive. + Must specify exactly one of `rate` and `log_rate`. +* `log_rate`: Floating point tensor, the log of the rate parameter. + Must specify exactly one of `rate` and `log_rate`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if none or both of `rate`, `log_rate` are specified. +* `TypeError`: if `rate` is not a float-type. +* `TypeError`: if `log_rate` is not a float-type. + + + ## Properties

allow_nan_stats

@@ -138,43 +178,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - rate=None, - log_rate=None, - validate_args=False, - allow_nan_stats=True, - name='Poisson' -) -``` - -Initialize a batch of Poisson distributions. - -#### Args: - -* `rate`: Floating point tensor, the rate parameter. `rate` must be positive. - Must specify exactly one of `rate` and `log_rate`. -* `log_rate`: Floating point tensor, the log of the rate parameter. - Must specify exactly one of `rate` and `log_rate`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if none or both of `rate`, `log_rate` are specified. -* `TypeError`: if `rate` is not a float-type. -* `TypeError`: if `log_rate` is not a float-type. -

batch_shape_tensor

``` python @@ -212,19 +215,6 @@ Given random variable `X`, the cumulative distribution function `cdf` is: cdf(x) := P[X <= x] ``` - -Additional documentation from `Poisson`: - -The Poisson distribution is technically only defined for non-negative integer -values. When `validate_args=False`, non-integral inputs trigger an assertion. - -When `validate_args=False` calculations are otherwise unchanged despite -integral or non-integral inputs. - -When `validate_args=False`, evaluating the pmf at non-integral values, -corresponds to evaluations of an unnormalized distribution, that does not -correspond to evaluations of the cdf. - #### Args: * `value`: `float` or `double` `Tensor`. @@ -327,7 +317,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -421,7 +411,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -452,19 +442,6 @@ Often, a numerical approximation can be used for `log_cdf(x)` that yields a more accurate answer than simply taking the logarithm of the `cdf` when `x << -1`. - -Additional documentation from `Poisson`: - -The Poisson distribution is technically only defined for non-negative integer -values. When `validate_args=False`, non-integral inputs trigger an assertion. - -When `validate_args=False` calculations are otherwise unchanged despite -integral or non-integral inputs. - -When `validate_args=False`, evaluating the pmf at non-integral values, -corresponds to evaluations of an unnormalized distribution, that does not -correspond to evaluations of the cdf. - #### Args: * `value`: `float` or `double` `Tensor`. @@ -487,19 +464,6 @@ log_prob( Log probability density/mass function. - -Additional documentation from `Poisson`: - -The Poisson distribution is technically only defined for non-negative integer -values. When `validate_args=False`, non-integral inputs trigger an assertion. - -When `validate_args=False` calculations are otherwise unchanged despite -integral or non-integral inputs. - -When `validate_args=False`, evaluating the pmf at non-integral values, -corresponds to evaluations of an unnormalized distribution, that does not -correspond to evaluations of the cdf. - #### Args: * `value`: `float` or `double` `Tensor`. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/PoissonLogNormalQuadratureCompound.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/PoissonLogNormalQuadratureCompound.md index 49cffc658a..63086bbd88 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/PoissonLogNormalQuadratureCompound.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/PoissonLogNormalQuadratureCompound.md @@ -1,5 +1,6 @@
+ @@ -106,6 +107,58 @@ pln = tfd.PoissonLogNormalQuadratureCompound( quadrature_size=10, validate_args=True) +

__init__

+ +``` python +__init__( + loc, + scale, + quadrature_size=8, + quadrature_fn=tfp.distributions.quadrature_scheme_lognormal_quantiles, + validate_args=False, + allow_nan_stats=True, + name='PoissonLogNormalQuadratureCompound' +) +``` + +Constructs the PoissonLogNormalQuadratureCompound`. + +Note: `probs` returned by (optional) `quadrature_fn` are presumed to be +either a length-`quadrature_size` vector or a batch of vectors in 1-to-1 +correspondence with the returned `grid`. (I.e., broadcasting is only +partially supported.) + +#### Args: + +* `loc`: `float`-like (batch of) scalar `Tensor`; the location parameter of + the LogNormal prior. +* `scale`: `float`-like (batch of) scalar `Tensor`; the scale parameter of + the LogNormal prior. +* `quadrature_size`: Python `int` scalar representing the number of quadrature + points. +* `quadrature_fn`: Python callable taking `loc`, `scale`, + `quadrature_size`, `validate_args` and returning `tuple(grid, probs)` + representing the LogNormal grid and corresponding normalized weight. + normalized) weight. + Default value: `quadrature_scheme_lognormal_quantiles`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if `quadrature_grid` and `quadrature_probs` have different base + `dtype`. + + + ## Properties

allow_nan_stats

@@ -199,56 +252,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - quadrature_size=8, - quadrature_fn=tfp.distributions.quadrature_scheme_lognormal_quantiles, - validate_args=False, - allow_nan_stats=True, - name='PoissonLogNormalQuadratureCompound' -) -``` - -Constructs the PoissonLogNormalQuadratureCompound`. - -Note: `probs` returned by (optional) `quadrature_fn` are presumed to be -either a length-`quadrature_size` vector or a batch of vectors in 1-to-1 -correspondence with the returned `grid`. (I.e., broadcasting is only -partially supported.) - -#### Args: - -* `loc`: `float`-like (batch of) scalar `Tensor`; the location parameter of - the LogNormal prior. -* `scale`: `float`-like (batch of) scalar `Tensor`; the scale parameter of - the LogNormal prior. -* `quadrature_size`: Python `int` scalar representing the number of quadrature - points. -* `quadrature_fn`: Python callable taking `loc`, `scale`, - `quadrature_size`, `validate_args` and returning `tuple(grid, probs)` - representing the LogNormal grid and corresponding normalized weight. - normalized) weight. - Default value: `quadrature_scheme_lognormal_quantiles`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if `quadrature_grid` and `quadrature_probs` have different base - `dtype`. -

batch_shape_tensor

``` python @@ -388,7 +391,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -482,7 +485,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/QuantizedDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/QuantizedDistribution.md index a7a0c8a7d0..98aac9cb7c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/QuantizedDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/QuantizedDistribution.md @@ -1,5 +1,6 @@
+ @@ -144,6 +145,52 @@ calculating its log-probability of audio samples as `target` and optimizing. Synthesis. _arXiv preprint arXiv:1711.10433_, 2017. https://arxiv.org/abs/1711.10433 +

__init__

+ +``` python +__init__( + distribution, + low=None, + high=None, + validate_args=False, + name='QuantizedDistribution' +) +``` + +Construct a Quantized Distribution representing `Y = ceiling(X)`. + +Some properties are inherited from the distribution defining `X`. Example: +`allow_nan_stats` is determined for this `QuantizedDistribution` by reading +the `distribution`. + +#### Args: + +* `distribution`: The base distribution class to transform. Typically an + instance of `Distribution`. +* `low`: `Tensor` with same `dtype` as this distribution and shape + able to be added to samples. Should be a whole number. Default `None`. + If provided, base distribution's `prob` should be defined at + `low`. +* `high`: `Tensor` with same `dtype` as this distribution and shape + able to be added to samples. Should be a whole number. Default `None`. + If provided, base distribution's `prob` should be defined at + `high - 1`. + `high` must be strictly greater than `low`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: If `dist_cls` is not a subclass of + `Distribution` or continuous. +* `NotImplementedError`: If the base distribution does not implement `cdf`. + + + ## Properties

allow_nan_stats

@@ -229,50 +276,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - distribution, - low=None, - high=None, - validate_args=False, - name='QuantizedDistribution' -) -``` - -Construct a Quantized Distribution representing `Y = ceiling(X)`. - -Some properties are inherited from the distribution defining `X`. Example: -`allow_nan_stats` is determined for this `QuantizedDistribution` by reading -the `distribution`. - -#### Args: - -* `distribution`: The base distribution class to transform. Typically an - instance of `Distribution`. -* `low`: `Tensor` with same `dtype` as this distribution and shape - able to be added to samples. Should be a whole number. Default `None`. - If provided, base distribution's `prob` should be defined at - `low`. -* `high`: `Tensor` with same `dtype` as this distribution and shape - able to be added to samples. Should be a whole number. Default `None`. - If provided, base distribution's `prob` should be defined at - `high - 1`. - `high` must be strictly greater than `low`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: If `dist_cls` is not a subclass of - `Distribution` or continuous. -* `NotImplementedError`: If the base distribution does not implement `cdf`. -

batch_shape_tensor

``` python @@ -430,7 +433,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -524,7 +527,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RegisterKL.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RegisterKL.md index 7f0b3e6f11..1bc8a2d6ad 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RegisterKL.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RegisterKL.md @@ -1,5 +1,6 @@
+
@@ -18,9 +19,7 @@ Usage: def _kl_normal_mvn(norm_a, norm_b): # Return KL(norm_a || norm_b) -## Methods - -

__init__

+

__init__

``` python __init__( @@ -36,6 +35,10 @@ Initialize the KL registrar. * `dist_cls_a`: the class of the first argument of the KL divergence. * `dist_cls_b`: the class of the second argument of the KL divergence. + + +## Methods +

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedBernoulli.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedBernoulli.md index 0b91d4f6e9..d79cfbb533 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedBernoulli.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedBernoulli.md @@ -1,5 +1,6 @@
+ @@ -144,6 +145,51 @@ A Continuous Relaxation of Discrete Random Variables. 2016. Eric Jang, Shixiang Gu, and Ben Poole. Categorical Reparameterization with Gumbel-Softmax. 2016. +

__init__

+ +``` python +__init__( + temperature, + logits=None, + probs=None, + validate_args=False, + allow_nan_stats=True, + name='RelaxedBernoulli' +) +``` + +Construct RelaxedBernoulli distributions. + +#### Args: + +* `temperature`: An 0-D `Tensor`, representing the temperature + of a set of RelaxedBernoulli distributions. The temperature should be + positive. +* `logits`: An N-D `Tensor` representing the log-odds + of a positive event. Each entry in the `Tensor` parametrizes + an independent RelaxedBernoulli distribution where the probability of an + event is sigmoid(logits). Only one of `logits` or `probs` should be + passed in. +* `probs`: An N-D `Tensor` representing the probability of a positive event. + Each entry in the `Tensor` parameterizes an independent Bernoulli + distribution. Only one of `logits` or `probs` should be passed in. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: If both `probs` and `logits` are passed, or if neither. + + + ## Properties

allow_nan_stats

@@ -237,49 +283,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - temperature, - logits=None, - probs=None, - validate_args=False, - allow_nan_stats=True, - name='RelaxedBernoulli' -) -``` - -Construct RelaxedBernoulli distributions. - -#### Args: - -* `temperature`: An 0-D `Tensor`, representing the temperature - of a set of RelaxedBernoulli distributions. The temperature should be - positive. -* `logits`: An N-D `Tensor` representing the log-odds - of a positive event. Each entry in the `Tensor` parametrizes - an independent RelaxedBernoulli distribution where the probability of an - event is sigmoid(logits). Only one of `logits` or `probs` should be - passed in. -* `probs`: An N-D `Tensor` representing the probability of a positive event. - Each entry in the `Tensor` parameterizes an independent Bernoulli - distribution. Only one of `logits` or `probs` should be passed in. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: If both `probs` and `logits` are passed, or if neither. -

batch_shape_tensor

``` python @@ -419,7 +422,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -513,7 +516,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedOneHotCategorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedOneHotCategorical.md index a8a48ed981..0a6af9a2d5 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedOneHotCategorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/RelaxedOneHotCategorical.md @@ -1,5 +1,6 @@
+ @@ -111,6 +112,48 @@ Gumbel-Softmax. 2016. Chris J. Maddison, Andriy Mnih, and Yee Whye Teh. The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables. 2016. +

__init__

+ +``` python +__init__( + temperature, + logits=None, + probs=None, + dtype=None, + validate_args=False, + allow_nan_stats=True, + name='RelaxedOneHotCategorical' +) +``` + +Initialize RelaxedOneHotCategorical using class log-probabilities. + +#### Args: + +* `temperature`: An 0-D `Tensor`, representing the temperature + of a set of RelaxedOneHotCategorical distributions. The temperature + should be positive. +* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities + of a set of RelaxedOneHotCategorical distributions. The first + `N - 1` dimensions index into a batch of independent distributions and + the last dimension represents a vector of logits for each class. Only + one of `logits` or `probs` should be passed in. +* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities + of a set of RelaxedOneHotCategorical distributions. The first `N - 1` + dimensions index into a batch of independent distributions and the last + dimension represents a vector of probabilities for each class. Only one + of `logits` or `probs` should be passed in. +* `dtype`: The type of the event samples (default: inferred from + logits/probs). +* `validate_args`: Unused in this distribution. +* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member. If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. +* `name`: A name for this distribution (optional). + + + ## Properties

allow_nan_stats

@@ -192,46 +235,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - temperature, - logits=None, - probs=None, - dtype=None, - validate_args=False, - allow_nan_stats=True, - name='RelaxedOneHotCategorical' -) -``` - -Initialize RelaxedOneHotCategorical using class log-probabilities. - -#### Args: - -* `temperature`: An 0-D `Tensor`, representing the temperature - of a set of RelaxedOneHotCategorical distributions. The temperature - should be positive. -* `logits`: An N-D `Tensor`, `N >= 1`, representing the log probabilities - of a set of RelaxedOneHotCategorical distributions. The first - `N - 1` dimensions index into a batch of independent distributions and - the last dimension represents a vector of logits for each class. Only - one of `logits` or `probs` should be passed in. -* `probs`: An N-D `Tensor`, `N >= 1`, representing the probabilities - of a set of RelaxedOneHotCategorical distributions. The first `N - 1` - dimensions index into a batch of independent distributions and the last - dimension represents a vector of probabilities for each class. Only one - of `logits` or `probs` should be passed in. -* `dtype`: The type of the event samples (default: inferred from - logits/probs). -* `validate_args`: Unused in this distribution. -* `allow_nan_stats`: Python `bool`, default `True`. If `False`, raise an - exception if a statistic (e.g. mean/mode/etc...) is undefined for any - batch member. If `True`, batch members with valid parameters leading to - undefined statistics will return NaN for this statistic. -* `name`: A name for this distribution (optional). -

batch_shape_tensor

``` python @@ -371,7 +374,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -465,7 +468,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ReparameterizationType.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ReparameterizationType.md index 1c7ad46617..2597b7cf2e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ReparameterizationType.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/ReparameterizationType.md @@ -1,5 +1,6 @@
+
@@ -25,9 +26,7 @@ one of two possible properties for samples from a distribution: sample results in a `stop_gradients` call and use policy gradients / surrogate loss instead. -## Methods - -

__init__

+

__init__

``` python __init__(rep_type) @@ -35,6 +34,10 @@ __init__(rep_type) + + +## Methods +

__eq__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SeedStream.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SeedStream.md index 1d93e0a95e..03acd07cfb 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SeedStream.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SeedStream.md @@ -1,5 +1,6 @@
+ @@ -145,21 +146,7 @@ seeds seen by `foo`'s callees will differ from those seen by `bar`'s callees, even if `foo` and `bar` are invoked with the same input seed. -## Properties - -

original_seed

- - - -

salt

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -181,6 +168,22 @@ Initializes a `SeedStream`. and TensorFlow Probability code base. See class docstring for rationale. + + +## Properties + +

original_seed

+ + + +

salt

+ + + + + +## Methods +

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SinhArcsinh.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SinhArcsinh.md index cf3ecf6919..2b8ba6bd4e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SinhArcsinh.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/SinhArcsinh.md @@ -1,5 +1,6 @@
+ @@ -107,6 +108,53 @@ P[(Y - loc) / scale <= 2] = P[F(Z) * (2 / F_0(2)) <= 2] = P[Z <= 2] (if F = F_0). ``` +

__init__

+ +``` python +__init__( + loc, + scale, + skewness=None, + tailweight=None, + distribution=None, + validate_args=False, + allow_nan_stats=True, + name='SinhArcsinh' +) +``` + +Construct SinhArcsinh distribution on `(-inf, inf)`. + +Arguments `(loc, scale, skewness, tailweight)` must have broadcastable shape +(indexing batch dimensions). They must all have the same `dtype`. + +#### Args: + +* `loc`: Floating-point `Tensor`. +* `scale`: `Tensor` of same `dtype` as `loc`. +* `skewness`: Skewness parameter. Default is `0.0` (no skew). +* `tailweight`: Tailweight parameter. Default is `1.0` (unchanged tailweight) +* `distribution`: `tf.Distribution`-like instance. Distribution that is + transformed to produce this distribution. + Default is `tf.distributions.Normal(0., 1.)`. + Must be a scalar-batch, scalar-event distribution. Typically + `distribution.reparameterization_type = FULLY_REPARAMETERIZED` or it is + a function of non-trainable parameters. WARNING: If you backprop through + a `SinhArcsinh` sample and `distribution` is not + `FULLY_REPARAMETERIZED` yet is a function of trainable variables, then + the gradient will be incorrect! +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -204,51 +252,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - skewness=None, - tailweight=None, - distribution=None, - validate_args=False, - allow_nan_stats=True, - name='SinhArcsinh' -) -``` - -Construct SinhArcsinh distribution on `(-inf, inf)`. - -Arguments `(loc, scale, skewness, tailweight)` must have broadcastable shape -(indexing batch dimensions). They must all have the same `dtype`. - -#### Args: - -* `loc`: Floating-point `Tensor`. -* `scale`: `Tensor` of same `dtype` as `loc`. -* `skewness`: Skewness parameter. Default is `0.0` (no skew). -* `tailweight`: Tailweight parameter. Default is `1.0` (unchanged tailweight) -* `distribution`: `tf.Distribution`-like instance. Distribution that is - transformed to produce this distribution. - Default is `tf.distributions.Normal(0., 1.)`. - Must be a scalar-batch, scalar-event distribution. Typically - `distribution.reparameterization_type = FULLY_REPARAMETERIZED` or it is - a function of non-trainable parameters. WARNING: If you backprop through - a `SinhArcsinh` sample and `distribution` is not - `FULLY_REPARAMETERIZED` yet is a function of trainable variables, then - the gradient will be incorrect! -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -388,7 +391,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -482,7 +485,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentT.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentT.md index 5848f2eec6..b3e599043f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentT.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentT.md @@ -1,5 +1,6 @@
+ @@ -90,8 +91,11 @@ Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498) Examples of initialization of one or a batch of distributions. ```python +import tensorflow_probability as tfp +tfd = tfp.distributions + # Define a single scalar Student t distribution. -single_dist = tf.distributions.StudentT(df=3) +single_dist = tfd.StudentT(df=3) # Evaluate the pdf at 1, returning a scalar Tensor. single_dist.prob(1.) @@ -99,9 +103,7 @@ single_dist.prob(1.) # Define a batch of two scalar valued Student t's. # The first has degrees of freedom 2, mean 1, and scale 11. # The second 3, 2 and 22. -multi_dist = tf.distributions.StudentT(df=[2, 3], - loc=[1, 2.], - scale=[11, 22.]) +multi_dist = tfd.StudentT(df=[2, 3], loc=[1, 2.], scale=[11, 22.]) # Evaluate the pdf of the first distribution on 0, and the second on 1.5, # returning a length two tensor. @@ -116,7 +118,7 @@ Arguments are broadcast when possible. ```python # Define a batch of two Student's t distributions. # Both have df 2 and mean 1, but different scales. -dist = tf.distributions.StudentT(df=2, loc=1, scale=[11, 22.]) +dist = tfd.StudentT(df=2, loc=1, scale=[11, 22.]) # Evaluate the pdf of both distributions on the same point, 3.0, # returning a length 2 tensor. @@ -129,13 +131,60 @@ Compute the gradients of samples w.r.t. the parameters: df = tf.constant(2.0) loc = tf.constant(2.0) scale = tf.constant(11.0) -dist = tf.distributions.StudentT(df=df, loc=loc, scale=scale) +dist = tfd.StudentT(df=df, loc=loc, scale=scale) samples = dist.sample(5) # Shape [5] loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function # Unbiased stochastic gradients of the loss function grads = tf.gradients(loss, [df, loc, scale]) ``` +

__init__

+ +``` python +__init__( + df, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='StudentT' +) +``` + +Construct Student's t distributions. + +The distributions have degree of freedom `df`, mean `loc`, and scale +`scale`. + +The parameters `df`, `loc`, and `scale` must be shaped in a way that +supports broadcasting (e.g. `df + loc + scale` is a valid operation). + +#### Args: + +* `df`: Floating-point `Tensor`. The degrees of freedom of the + distribution(s). `df` must contain only positive values. +* `loc`: Floating-point `Tensor`. The mean(s) of the distribution(s). +* `scale`: Floating-point `Tensor`. The scaling factor(s) for the + distribution(s). Note that `scale` is not technically the standard + deviation of this distribution but has semantics more similar to + standard deviation than variance. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if loc and scale are different dtypes. + + + ## Properties

allow_nan_stats

@@ -221,51 +270,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - df, - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='StudentT' -) -``` - -Construct Student's t distributions. - -The distributions have degree of freedom `df`, mean `loc`, and scale -`scale`. - -The parameters `df`, `loc`, and `scale` must be shaped in a way that -supports broadcasting (e.g. `df + loc + scale` is a valid operation). - -#### Args: - -* `df`: Floating-point `Tensor`. The degrees of freedom of the - distribution(s). `df` must contain only positive values. -* `loc`: Floating-point `Tensor`. The mean(s) of the distribution(s). -* `scale`: Floating-point `Tensor`. The scaling factor(s) for the - distribution(s). Note that `scale` is not technically the standard - deviation of this distribution but has semantics more similar to - standard deviation than variance. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `TypeError`: if loc and scale are different dtypes. -

batch_shape_tensor

``` python @@ -405,7 +409,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -499,7 +503,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentTWithAbsDfSoftplusScale.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentTWithAbsDfSoftplusScale.md index 97bd58fc56..c7e728dbfa 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentTWithAbsDfSoftplusScale.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/StudentTWithAbsDfSoftplusScale.md @@ -1,5 +1,6 @@
+ @@ -45,6 +46,23 @@ Inherits From: [`StudentT`](../../tfp/distributions/StudentT.md) StudentT with `df = floor(abs(df))` and `scale = softplus(scale)`. +

__init__

+ +``` python +__init__( + df, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name='StudentTWithAbsDfSoftplusScale' +) +``` + + + + + ## Properties

allow_nan_stats

@@ -130,21 +148,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - df, - loc, - scale, - validate_args=False, - allow_nan_stats=True, - name='StudentTWithAbsDfSoftplusScale' -) -``` - - -

batch_shape_tensor

``` python @@ -284,7 +287,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -378,7 +381,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TransformedDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TransformedDistribution.md index dceae64e91..fa226bce29 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TransformedDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TransformedDistribution.md @@ -1,5 +1,6 @@
+ @@ -89,22 +90,20 @@ A simple example constructing a Log-Normal distribution from a Normal distribution: ```python -tfd = tfp.distributions -tfb = tfp.bijectors -log_normal = tfd.TransformedDistribution( - distribution=tfd.Normal(loc=0., scale=1.), - bijector=tfb.Exp(), +ds = tf.contrib.distributions +log_normal = ds.TransformedDistribution( + distribution=ds.Normal(loc=0., scale=1.), + bijector=ds.bijectors.Exp(), name="LogNormalTransformedDistribution") ``` A `LogNormal` made from callables: ```python -tfd = tfp.distributions -tfb = tfp.bijectors -log_normal = tfd.TransformedDistribution( - distribution=tfd.Normal(loc=0., scale=1.), - bijector=tfb.Inline( +ds = tf.contrib.distributions +log_normal = ds.TransformedDistribution( + distribution=ds.Normal(loc=0., scale=1.), + bijector=ds.bijectors.Inline( forward_fn=tf.exp, inverse_fn=tf.log, inverse_log_det_jacobian_fn=( @@ -115,11 +114,10 @@ log_normal = tfd.TransformedDistribution( Another example constructing a Normal from a StandardNormal: ```python -tfd = tfp.distributions -tfb = tfp.bijectors -normal = tfd.TransformedDistribution( - distribution=tfd.Normal(loc=0., scale=1.), - bijector=tfb.Affine( +ds = tf.contrib.distributions +normal = ds.TransformedDistribution( + distribution=ds.Normal(loc=0., scale=1.), + bijector=ds.bijectors.Affine( shift=-1., scale_identity_multiplier=2.) name="NormalTransformedDistribution") @@ -134,8 +132,7 @@ the overridden shape(s). The following example demonstrates how to construct a multivariate Normal as a `TransformedDistribution`. ```python -tfd = tfp.distributions -tfb = tfp.bijectors +ds = tf.contrib.distributions # We will create two MVNs with batch_shape = event_shape = 2. mean = [[-1., 0], # batch:0 [0., 1]] # batch:1 @@ -143,15 +140,49 @@ chol_cov = [[[1., 0], [0, 1]], # batch:0 [[1, 0], [2, 2]]] # batch:1 -mvn1 = tfd.TransformedDistribution( - distribution=tfd.Normal(loc=0., scale=1.), - bijector=tfb.Affine(shift=mean, scale_tril=chol_cov), +mvn1 = ds.TransformedDistribution( + distribution=ds.Normal(loc=0., scale=1.), + bijector=ds.bijectors.Affine(shift=mean, scale_tril=chol_cov), batch_shape=[2], # Valid because base_distribution.batch_shape == []. event_shape=[2]) # Valid because base_distribution.event_shape == []. -mvn2 = tfd.MultivariateNormalTriL(loc=mean, scale_tril=chol_cov) +mvn2 = ds.MultivariateNormalTriL(loc=mean, scale_tril=chol_cov) # mvn1.log_prob(x) == mvn2.log_prob(x) ``` +

__init__

+ +``` python +__init__( + distribution, + bijector=None, + batch_shape=None, + event_shape=None, + validate_args=False, + name=None +) +``` + +Construct a Transformed Distribution. + +#### Args: + +* `distribution`: The base distribution instance to transform. Typically an + instance of `Distribution`. +* `bijector`: The object responsible for calculating the transformation. + Typically an instance of `Bijector`. `None` means `Identity()`. +* `batch_shape`: `integer` vector `Tensor` which overrides `distribution` + `batch_shape`; valid only if `distribution.is_scalar_batch()`. +* `event_shape`: `integer` vector `Tensor` which overrides `distribution` + `event_shape`; valid only if `distribution.is_scalar_event()`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `name`: Python `str` name prefixed to Ops created by this class. Default: + `bijector.name + distribution.name`. + + + ## Properties

allow_nan_stats

@@ -233,38 +264,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - distribution, - bijector=None, - batch_shape=None, - event_shape=None, - validate_args=False, - name=None -) -``` - -Construct a Transformed Distribution. - -#### Args: - -* `distribution`: The base distribution instance to transform. Typically an - instance of `Distribution`. -* `bijector`: The object responsible for calculating the transformation. - Typically an instance of `Bijector`. `None` means `Identity()`. -* `batch_shape`: `integer` vector `Tensor` which overrides `distribution` - `batch_shape`; valid only if `distribution.is_scalar_batch()`. -* `event_shape`: `integer` vector `Tensor` which overrides `distribution` - `event_shape`; valid only if `distribution.is_scalar_event()`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `name`: Python `str` name prefixed to Ops created by this class. Default: - `bijector.name + distribution.name`. -

batch_shape_tensor

``` python @@ -404,7 +403,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -498,7 +497,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TruncatedNormal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TruncatedNormal.md index d2fd7cd70a..11863f012b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TruncatedNormal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/TruncatedNormal.md @@ -1,5 +1,6 @@
+ @@ -51,9 +52,9 @@ The Truncated Normal distribution. The truncated normal is a normal distribution bounded between `low` and `high` (the pdf is 0 outside these bounds and renormalized). -Samples from this distribution are differentiable with respect to -`loc` and `scale` but not `low` and `high`, i.e., this distribution is -partially reparameterizeable. +Samples from this distribution are differentiable with respect to `loc`, +`scale` as well as the bounds, `low` and `high`, i.e., this +implementation is fully reparameterizeable. For more details, see [here]( https://en.wikipedia.org/wiki/Truncated_normal_distribution). @@ -63,7 +64,7 @@ https://en.wikipedia.org/wiki/Truncated_normal_distribution). The probability density function (pdf) of this distribution is: ```none pdf(x; loc, scale, low, high) = - { (2 pi)**(-0.5) exp(-0.5 y) / (scale z) for low <= x <= high + { (2 pi)**(-0.5) exp(-0.5 y**2) / (scale * z) for low <= x <= high { 0 otherwise y = (x - loc)/scale z = NormalCDF((high - loc) / scale) - NormalCDF((lower - loc) / scale) @@ -72,7 +73,7 @@ The probability density function (pdf) of this distribution is: where: * `NormalCDF` is the cumulative density function of the Normal distribution - with 0. mean and unit variance. + with 0 mean and unit variance. This is a scalar distribution so the event shape is always scalar and the dimensions of the parameters defined the batch_shape. @@ -94,6 +95,47 @@ dist.prob([0.5, 0.8]) dist.sample([3]) ``` +

__init__

+ +``` python +__init__( + loc, + scale, + low, + high, + validate_args=False, + allow_nan_stats=True, + name='TruncatedNormal' +) +``` + +Construct TruncatedNormal. + +All parameters of the distribution will be broadcast to the same shape, +so the resulting distribution will have a batch_shape of the broadcast +shape of all parameters. + +#### Args: + +* `loc`: Floating point tensor; the mean of the normal distribution(s) ( + note that the mean of the resulting distribution will be different + since it is modified by the bounds). +* `scale`: Floating point tensor; the std deviation of the normal + distribution(s). +* `low`: `float` `Tensor` representing lower bound of the distribution's + support. Must be such that `low < high`. +* `high`: `float` `Tensor` representing upper bound of the distribution's + support. Must be such that `low < high`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked at run-time. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -183,45 +225,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - scale, - low, - high, - validate_args=False, - allow_nan_stats=True, - name='TruncatedNormal' -) -``` - -Construct TruncatedNormal. - -All parameters of the distribution will be broadcast to the same shape, -so the resulting distribution will have a batch_shape of the broadcast -shape of all parameters. - -#### Args: - -* `loc`: Floating point tensor; the mean of the normal distribution(s) ( - note that the mean of the resulting distribution will be different - since it is modified by the bounds). -* `scale`: Floating point tensor; the std deviation of the normal - distribution(s). -* `low`: `float` `Tensor` representing lower bound of the distribution's - support. Must be such that `low < high`. -* `high`: `float` `Tensor` representing upper bound of the distribution's - support. Must be such that `low < high`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked at run-time. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -361,7 +364,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -455,7 +458,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Uniform.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Uniform.md index b5cc362d0e..d4a3f3b96f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Uniform.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Uniform.md @@ -1,5 +1,6 @@
+ @@ -83,6 +84,43 @@ u3 = Uniform(low=[[1.0, 2.0], u1 = Uniform(low=3.0, high=[5.0, 6.0, 7.0]) # 3 distributions ``` +

__init__

+ +``` python +__init__( + low=0.0, + high=1.0, + validate_args=False, + allow_nan_stats=True, + name='Uniform' +) +``` + +Initialize a batch of Uniform distributions. + +#### Args: + +* `low`: Floating point tensor, lower boundary of the output interval. Must + have `low < high`. +* `high`: Floating point tensor, upper boundary of the output interval. Must + have `low < high`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `InvalidArgumentError`: if `low >= high` and `validate_args=False`. + + + ## Properties

allow_nan_stats

@@ -164,41 +202,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - low=0.0, - high=1.0, - validate_args=False, - allow_nan_stats=True, - name='Uniform' -) -``` - -Initialize a batch of Uniform distributions. - -#### Args: - -* `low`: Floating point tensor, lower boundary of the output interval. Must - have `low < high`. -* `high`: Floating point tensor, upper boundary of the output interval. Must - have `low < high`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `InvalidArgumentError`: if `low >= high` and `validate_args=False`. -

batch_shape_tensor

``` python @@ -338,7 +341,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -432,7 +435,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDeterministic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDeterministic.md index 469657ede2..7b239f2e05 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDeterministic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDeterministic.md @@ -1,5 +1,6 @@
+ @@ -80,6 +81,55 @@ constant.prob([[0., 1.], [1.9, 3.], [3.99, 5.]]) ==> [1., 0., 0.] ``` +

__init__

+ +``` python +__init__( + loc, + atol=None, + rtol=None, + validate_args=False, + allow_nan_stats=True, + name='VectorDeterministic' +) +``` + +Initialize a `VectorDeterministic` distribution on `R^k`, for `k >= 0`. + +Note that there is only one point in `R^0`, the "point" `[]`. So if `k = 0` +then `self.prob([]) == 1`. + +The `atol` and `rtol` parameters allow for some slack in `pmf` +computations, e.g. due to floating-point error. + +``` +pmf(x; loc) + = 1, if All[Abs(x - loc) <= atol + rtol * Abs(loc)], + = 0, otherwise +``` + +#### Args: + +* `loc`: Numeric `Tensor` of shape `[B1, ..., Bb, k]`, with `b >= 0`, `k >= 0` + The point (or batch of points) on which this distribution is supported. +* `atol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable + shape. The absolute tolerance for comparing closeness to `loc`. + Default is `0`. +* `rtol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable + shape. The relative tolerance for comparing closeness to `loc`. + Default is `0`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

allow_nan_stats

@@ -165,53 +215,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc, - atol=None, - rtol=None, - validate_args=False, - allow_nan_stats=True, - name='VectorDeterministic' -) -``` - -Initialize a `VectorDeterministic` distribution on `R^k`, for `k >= 0`. - -Note that there is only one point in `R^0`, the "point" `[]`. So if `k = 0` -then `self.prob([]) == 1`. - -The `atol` and `rtol` parameters allow for some slack in `pmf` -computations, e.g. due to floating-point error. - -``` -pmf(x; loc) - = 1, if All[Abs(x - loc) <= atol + rtol * Abs(loc)], - = 0, otherwise -``` - -#### Args: - -* `loc`: Numeric `Tensor` of shape `[B1, ..., Bb, k]`, with `b >= 0`, `k >= 0` - The point (or batch of points) on which this distribution is supported. -* `atol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable - shape. The absolute tolerance for comparing closeness to `loc`. - Default is `0`. -* `rtol`: Non-negative `Tensor` of same `dtype` as `loc` and broadcastable - shape. The relative tolerance for comparing closeness to `loc`. - Default is `0`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. -

batch_shape_tensor

``` python @@ -351,7 +354,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -445,7 +448,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDiffeomixture.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDiffeomixture.md index f33a97d76e..851a4ea0cc 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDiffeomixture.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorDiffeomixture.md @@ -1,5 +1,6 @@
+ @@ -156,6 +157,94 @@ vdm = tfd.VectorDiffeomixture( family of distributions. _arXiv preprint arXiv:1801.03080_, 2018. https://arxiv.org/abs/1801.03080 +

__init__

+ +``` python +__init__( + mix_loc, + temperature, + distribution, + loc=None, + scale=None, + quadrature_size=8, + quadrature_fn=tfp.distributions.quadrature_scheme_softmaxnormal_quantiles, + validate_args=False, + allow_nan_stats=True, + name='VectorDiffeomixture' +) +``` + +Constructs the VectorDiffeomixture on `R^d`. + +The vector diffeomixture (VDM) approximates the compound distribution + +```none +p(x) = int p(x | z) p(z) dz, +where z is in the K-simplex, and +p(x | z) := p(x | loc=sum_k z[k] loc[k], scale=sum_k z[k] scale[k]) +``` + +#### Args: + +* `mix_loc`: `float`-like `Tensor` with shape `[b1, ..., bB, K-1]`. + In terms of samples, larger `mix_loc[..., k]` ==> + `Z` is more likely to put more weight on its `kth` component. +* `temperature`: `float`-like `Tensor`. Broadcastable with `mix_loc`. + In terms of samples, smaller `temperature` means one component is more + likely to dominate. I.e., smaller `temperature` makes the VDM look more + like a standard mixture of `K` components. +* `distribution`: `tf.Distribution`-like instance. Distribution from which `d` + iid samples are used as input to the selected affine transformation. + Must be a scalar-batch, scalar-event distribution. Typically + `distribution.reparameterization_type = FULLY_REPARAMETERIZED` or it is + a function of non-trainable parameters. WARNING: If you backprop through + a VectorDiffeomixture sample and the `distribution` is not + `FULLY_REPARAMETERIZED` yet is a function of trainable variables, then + the gradient will be incorrect! +* `loc`: Length-`K` list of `float`-type `Tensor`s. The `k`-th element + represents the `shift` used for the `k`-th affine transformation. If + the `k`-th item is `None`, `loc` is implicitly `0`. When specified, + must have shape `[B1, ..., Bb, d]` where `b >= 0` and `d` is the event + size. +* `scale`: Length-`K` list of `LinearOperator`s. Each should be + positive-definite and operate on a `d`-dimensional vector space. The + `k`-th element represents the `scale` used for the `k`-th affine + transformation. `LinearOperator`s must have shape `[B1, ..., Bb, d, d]`, + `b >= 0`, i.e., characterizes `b`-batches of `d x d` matrices +* `quadrature_size`: Python `int` scalar representing number of + quadrature points. Larger `quadrature_size` means `q_N(x)` better + approximates `p(x)`. +* `quadrature_fn`: Python callable taking `normal_loc`, `normal_scale`, + `quadrature_size`, `validate_args` and returning `tuple(grid, probs)` + representing the SoftmaxNormal grid and corresponding normalized weight. + normalized) weight. + Default value: `quadrature_scheme_softmaxnormal_quantiles`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if `not scale or len(scale) < 2`. +* `ValueError`: if `len(loc) != len(scale)` +* `ValueError`: if `quadrature_grid_and_probs is not None` and + `len(quadrature_grid_and_probs[0]) != len(quadrature_grid_and_probs[1])` +* `ValueError`: if `validate_args` and any not scale.is_positive_definite. +* `TypeError`: if any scale.dtype != scale[0].dtype. +* `TypeError`: if any loc.dtype != scale[0].dtype. +* `NotImplementedError`: if `len(scale) != 2`. +* `ValueError`: if `not distribution.is_scalar_batch`. +* `ValueError`: if `not distribution.is_scalar_event`. + + + ## Properties

allow_nan_stats

@@ -249,92 +338,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - mix_loc, - temperature, - distribution, - loc=None, - scale=None, - quadrature_size=8, - quadrature_fn=tfp.distributions.quadrature_scheme_softmaxnormal_quantiles, - validate_args=False, - allow_nan_stats=True, - name='VectorDiffeomixture' -) -``` - -Constructs the VectorDiffeomixture on `R^d`. - -The vector diffeomixture (VDM) approximates the compound distribution - -```none -p(x) = int p(x | z) p(z) dz, -where z is in the K-simplex, and -p(x | z) := p(x | loc=sum_k z[k] loc[k], scale=sum_k z[k] scale[k]) -``` - -#### Args: - -* `mix_loc`: `float`-like `Tensor` with shape `[b1, ..., bB, K-1]`. - In terms of samples, larger `mix_loc[..., k]` ==> - `Z` is more likely to put more weight on its `kth` component. -* `temperature`: `float`-like `Tensor`. Broadcastable with `mix_loc`. - In terms of samples, smaller `temperature` means one component is more - likely to dominate. I.e., smaller `temperature` makes the VDM look more - like a standard mixture of `K` components. -* `distribution`: `tf.Distribution`-like instance. Distribution from which `d` - iid samples are used as input to the selected affine transformation. - Must be a scalar-batch, scalar-event distribution. Typically - `distribution.reparameterization_type = FULLY_REPARAMETERIZED` or it is - a function of non-trainable parameters. WARNING: If you backprop through - a VectorDiffeomixture sample and the `distribution` is not - `FULLY_REPARAMETERIZED` yet is a function of trainable variables, then - the gradient will be incorrect! -* `loc`: Length-`K` list of `float`-type `Tensor`s. The `k`-th element - represents the `shift` used for the `k`-th affine transformation. If - the `k`-th item is `None`, `loc` is implicitly `0`. When specified, - must have shape `[B1, ..., Bb, d]` where `b >= 0` and `d` is the event - size. -* `scale`: Length-`K` list of `LinearOperator`s. Each should be - positive-definite and operate on a `d`-dimensional vector space. The - `k`-th element represents the `scale` used for the `k`-th affine - transformation. `LinearOperator`s must have shape `[B1, ..., Bb, d, d]`, - `b >= 0`, i.e., characterizes `b`-batches of `d x d` matrices -* `quadrature_size`: Python `int` scalar representing number of - quadrature points. Larger `quadrature_size` means `q_N(x)` better - approximates `p(x)`. -* `quadrature_fn`: Python callable taking `normal_loc`, `normal_scale`, - `quadrature_size`, `validate_args` and returning `tuple(grid, probs)` - representing the SoftmaxNormal grid and corresponding normalized weight. - normalized) weight. - Default value: `quadrature_scheme_softmaxnormal_quantiles`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if `not scale or len(scale) < 2`. -* `ValueError`: if `len(loc) != len(scale)` -* `ValueError`: if `quadrature_grid_and_probs is not None` and - `len(quadrature_grid_and_probs[0]) != len(quadrature_grid_and_probs[1])` -* `ValueError`: if `validate_args` and any not scale.is_positive_definite. -* `TypeError`: if any scale.dtype != scale[0].dtype. -* `TypeError`: if any loc.dtype != scale[0].dtype. -* `NotImplementedError`: if `len(scale) != 2`. -* `ValueError`: if `not distribution.is_scalar_batch`. -* `ValueError`: if `not distribution.is_scalar_event`. -

batch_shape_tensor

``` python @@ -474,7 +477,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -568,7 +571,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorExponentialDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorExponentialDiag.md index 022e0e1e30..e94f7ecc68 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorExponentialDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorExponentialDiag.md @@ -1,5 +1,6 @@
+ @@ -128,6 +129,76 @@ x = [[1.9, 2.2, 3.1], vex.prob(x).eval() # shape: [2] ``` +

__init__

+ +``` python +__init__( + loc=None, + scale_diag=None, + scale_identity_multiplier=None, + validate_args=False, + allow_nan_stats=True, + name='VectorExponentialDiag' +) +``` + +Construct Vector Exponential distribution supported on a subset of `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this. + +Recall that `covariance = scale @ scale.T`. + +```none +scale = diag(scale_diag + scale_identity_multiplier * ones(k)) +``` + +where: + +* `scale_diag.shape = [k]`, and, +* `scale_identity_multiplier.shape = []`. + +Additional leading dimensions (if any) will index batches. + +If both `scale_diag` and `scale_identity_multiplier` are `None`, then +`scale` is the Identity matrix. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal + matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, + and characterizes `b`-batches of `k x k` diagonal matrices added to + `scale`. When both `scale_identity_multiplier` and `scale_diag` are + `None` then `scale` is the `Identity`. +* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing + a scaled-identity-matrix added to `scale`. May have shape + `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled + `k x k` identity matrices added to `scale`. When both + `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is + the `Identity`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if at most `scale_identity_multiplier` is specified. + + + ## Properties

allow_nan_stats

@@ -217,74 +288,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale_diag=None, - scale_identity_multiplier=None, - validate_args=False, - allow_nan_stats=True, - name='VectorExponentialDiag' -) -``` - -Construct Vector Exponential distribution supported on a subset of `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this. - -Recall that `covariance = scale @ scale.T`. - -```none -scale = diag(scale_diag + scale_identity_multiplier * ones(k)) -``` - -where: - -* `scale_diag.shape = [k]`, and, -* `scale_identity_multiplier.shape = []`. - -Additional leading dimensions (if any) will index batches. - -If both `scale_diag` and `scale_identity_multiplier` are `None`, then -`scale` is the Identity matrix. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal - matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, - and characterizes `b`-batches of `k x k` diagonal matrices added to - `scale`. When both `scale_identity_multiplier` and `scale_diag` are - `None` then `scale` is the `Identity`. -* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing - a scaled-identity-matrix added to `scale`. May have shape - `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled - `k x k` identity matrices added to `scale`. When both - `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is - the `Identity`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if at most `scale_identity_multiplier` is specified. -

batch_shape_tensor

``` python @@ -424,7 +427,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -518,7 +521,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorLaplaceDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorLaplaceDiag.md index 972de95b9e..151a30dfc2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorLaplaceDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorLaplaceDiag.md @@ -1,5 +1,6 @@
+ @@ -163,6 +164,76 @@ x = [[-1., 0, 1], vla.prob(x).eval() # shape: [2] ``` +

__init__

+ +``` python +__init__( + loc=None, + scale_diag=None, + scale_identity_multiplier=None, + validate_args=False, + allow_nan_stats=True, + name='VectorLaplaceDiag' +) +``` + +Construct Vector Laplace distribution on `R^k`. + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this. + +Recall that `covariance = 2 * scale @ scale.T`. + +```none +scale = diag(scale_diag + scale_identity_multiplier * ones(k)) +``` + +where: + +* `scale_diag.shape = [k]`, and, +* `scale_identity_multiplier.shape = []`. + +Additional leading dimensions (if any) will index batches. + +If both `scale_diag` and `scale_identity_multiplier` are `None`, then +`scale` is the Identity matrix. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal + matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, + and characterizes `b`-batches of `k x k` diagonal matrices added to + `scale`. When both `scale_identity_multiplier` and `scale_diag` are + `None` then `scale` is the `Identity`. +* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing + a scaled-identity-matrix added to `scale`. May have shape + `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled + `k x k` identity matrices added to `scale`. When both + `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is + the `Identity`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if at most `scale_identity_multiplier` is specified. + + + ## Properties

allow_nan_stats

@@ -252,74 +323,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale_diag=None, - scale_identity_multiplier=None, - validate_args=False, - allow_nan_stats=True, - name='VectorLaplaceDiag' -) -``` - -Construct Vector Laplace distribution on `R^k`. - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this. - -Recall that `covariance = 2 * scale @ scale.T`. - -```none -scale = diag(scale_diag + scale_identity_multiplier * ones(k)) -``` - -where: - -* `scale_diag.shape = [k]`, and, -* `scale_identity_multiplier.shape = []`. - -Additional leading dimensions (if any) will index batches. - -If both `scale_diag` and `scale_identity_multiplier` are `None`, then -`scale` is the Identity matrix. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal - matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, - and characterizes `b`-batches of `k x k` diagonal matrices added to - `scale`. When both `scale_identity_multiplier` and `scale_diag` are - `None` then `scale` is the `Identity`. -* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing - a scaled-identity-matrix added to `scale`. May have shape - `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled - `k x k` identity matrices added to `scale`. When both - `scale_identity_multiplier` and `scale_diag` are `None` then `scale` is - the `Identity`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if at most `scale_identity_multiplier` is specified. -

batch_shape_tensor

``` python @@ -459,7 +462,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -553,7 +556,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorSinhArcsinhDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorSinhArcsinhDiag.md index 9129ad7e62..d4d81fb1de 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorSinhArcsinhDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VectorSinhArcsinhDiag.md @@ -1,5 +1,6 @@
+ @@ -108,6 +109,85 @@ P[(Y - loc) / scale <= 2] = P[F(Z) * (2 / F_0(2)) <= 2] = P[Z <= 2] (if F = F_0). ``` +

__init__

+ +``` python +__init__( + loc=None, + scale_diag=None, + scale_identity_multiplier=None, + skewness=None, + tailweight=None, + distribution=None, + validate_args=False, + allow_nan_stats=True, + name='MultivariateNormalLinearOperator' +) +``` + +Construct VectorSinhArcsinhDiag distribution on `R^k`. + +The arguments `scale_diag` and `scale_identity_multiplier` combine to +define the diagonal `scale` referred to in this class docstring: + +```none +scale = diag(scale_diag + scale_identity_multiplier * ones(k)) +``` + +The `batch_shape` is the broadcast shape between `loc` and `scale` +arguments. + +The `event_shape` is given by last dimension of the matrix implied by +`scale`. The last dimension of `loc` (if provided) must broadcast with this + +Additional leading dimensions (if any) will index batches. + +#### Args: + +* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is + implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where + `b >= 0` and `k` is the event size. +* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal + matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, + and characterizes `b`-batches of `k x k` diagonal matrices added to + `scale`. When both `scale_identity_multiplier` and `scale_diag` are + `None` then `scale` is the `Identity`. +* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing + a scale-identity-matrix added to `scale`. May have shape + `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scale + `k x k` identity matrices added to `scale`. When both + `scale_identity_multiplier` and `scale_diag` are `None` then `scale` + is the `Identity`. +* `skewness`: Skewness parameter. floating-point `Tensor` with shape + broadcastable with `event_shape`. +* `tailweight`: Tailweight parameter. floating-point `Tensor` with shape + broadcastable with `event_shape`. +* `distribution`: `tf.Distribution`-like instance. Distribution from which `k` + iid samples are used as input to transformation `F`. Default is + `tf.distributions.Normal(loc=0., scale=1.)`. + Must be a scalar-batch, scalar-event distribution. Typically + `distribution.reparameterization_type = FULLY_REPARAMETERIZED` or it is + a function of non-trainable parameters. WARNING: If you backprop through + a VectorSinhArcsinhDiag sample and `distribution` is not + `FULLY_REPARAMETERIZED` yet is a function of trainable variables, then + the gradient will be incorrect! +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: if at most `scale_identity_multiplier` is specified. + + + ## Properties

allow_nan_stats

@@ -205,83 +285,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - loc=None, - scale_diag=None, - scale_identity_multiplier=None, - skewness=None, - tailweight=None, - distribution=None, - validate_args=False, - allow_nan_stats=True, - name='MultivariateNormalLinearOperator' -) -``` - -Construct VectorSinhArcsinhDiag distribution on `R^k`. - -The arguments `scale_diag` and `scale_identity_multiplier` combine to -define the diagonal `scale` referred to in this class docstring: - -```none -scale = diag(scale_diag + scale_identity_multiplier * ones(k)) -``` - -The `batch_shape` is the broadcast shape between `loc` and `scale` -arguments. - -The `event_shape` is given by last dimension of the matrix implied by -`scale`. The last dimension of `loc` (if provided) must broadcast with this - -Additional leading dimensions (if any) will index batches. - -#### Args: - -* `loc`: Floating-point `Tensor`. If this is set to `None`, `loc` is - implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where - `b >= 0` and `k` is the event size. -* `scale_diag`: Non-zero, floating-point `Tensor` representing a diagonal - matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`, - and characterizes `b`-batches of `k x k` diagonal matrices added to - `scale`. When both `scale_identity_multiplier` and `scale_diag` are - `None` then `scale` is the `Identity`. -* `scale_identity_multiplier`: Non-zero, floating-point `Tensor` representing - a scale-identity-matrix added to `scale`. May have shape - `[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scale - `k x k` identity matrices added to `scale`. When both - `scale_identity_multiplier` and `scale_diag` are `None` then `scale` - is the `Identity`. -* `skewness`: Skewness parameter. floating-point `Tensor` with shape - broadcastable with `event_shape`. -* `tailweight`: Tailweight parameter. floating-point `Tensor` with shape - broadcastable with `event_shape`. -* `distribution`: `tf.Distribution`-like instance. Distribution from which `k` - iid samples are used as input to transformation `F`. Default is - `tf.distributions.Normal(loc=0., scale=1.)`. - Must be a scalar-batch, scalar-event distribution. Typically - `distribution.reparameterization_type = FULLY_REPARAMETERIZED` or it is - a function of non-trainable parameters. WARNING: If you backprop through - a VectorSinhArcsinhDiag sample and `distribution` is not - `FULLY_REPARAMETERIZED` yet is a function of trainable variables, then - the gradient will be incorrect! -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: if at most `scale_identity_multiplier` is specified. -

batch_shape_tensor

``` python @@ -421,7 +424,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -515,7 +518,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMises.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMises.md new file mode 100644 index 0000000000..df7eb7cae9 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMises.md @@ -0,0 +1,807 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.distributions.VonMises + +## Class `VonMises` + +Inherits From: [`Distribution`](../../tfp/distributions/Distribution.md) + +The von Mises distribution over angles. + +The von Mises distribution is a univariate directional distribution. +Similarly to Normal distribution, it is a maximum entropy distribution. +The samples of this distribution are angles, measured in radians. +They are 2 pi-periodic: x = 0 and x = 2pi are equivalent. +This means that the density is also 2 pi-periodic. +The generated samples, however, are guaranteed to be in [-pi, pi) range. + +When `concentration = 0`, this distribution becomes a Uniform distribuion on +the [-pi, pi) domain. + +The von Mises distribution is a special case of von Mises-Fisher distribution +for n=2. However, the TFP's VonMisesFisher implementation represents the +samples and location as (x, y) points on a circle, while VonMises represents +them as scalar angles. + +#### Mathematical details + +The probability density function (pdf) of this distribution is, + +```none +pdf(x; loc, concentration) = exp(concentration cos(x - loc)) / Z +Z = 2 * pi * I_0 (concentration) +``` + +where: +* `I_0 (concentration)` is the modified Bessel function of order zero; +* `loc` the circular mean of the distribution, a scalar. It can take arbitrary + values, but it is 2pi-periodic: loc and loc + 2pi result in the same + distribution. +* `concentration >= 0` parameter is the concentration parameter. When +`concentration = 0`, + this distribution becomes a Uniform distribution on [-pi, pi). + +#### Examples + +Examples of initialization of one or a batch of distributions. + +```python +# Create a batch of three von Mises distributions. +loc = [1, 2, 3] +concentration = [1, 2, 3] +dist = tfp.distributions.VonMises(loc=[1.0, 2.0], concentration=[0.5, 2.0]) + +dist.sample([3]) # Shape [3, 2] +``` + +Arguments are broadcast when possible. + +```python +dist = tfp.distributions.VonMises(loc=1.0, concentration=[0.5, 2.0]) + +# Evaluate the pdf of both distributions on the same point, 3.0, +# returning a length 2 tensor. +dist.prob(3.0) +``` + +

__init__

+ +``` python +__init__( + loc, + concentration, + validate_args=False, + allow_nan_stats=True, + name='VonMises' +) +``` + +Construct von Mises distributions with given location and concentration. + +The parameters `loc` and `concentration` must be shaped in a way that +supports broadcasting (e.g. `loc + concentration` is a valid operation). + +#### Args: + +* `loc`: Floating point tensor, the circular means of the distribution(s). +* `concentration`: Floating point tensor, the level of concentration of the + distribution(s) around `loc`. Must take non-negative values. + `concentration = 0` defines a Uniform distribution, while + `concentration = +inf` indicates a Deterministic distribution at `loc`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or more + of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `TypeError`: if loc and concentration are different dtypes. + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

concentration

+ +Distribution parameter for the concentration. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

loc

+ +Distribution parameter for the circular mean (loc). + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +Additional documentation from `VonMises`: + +Note: This function computes the circular mean, defined as +atan2(E sin(x), E cos(x)). The values are in the [-pi, pi] range. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + + +Additional documentation from `VonMises`: + +Note: This function computes the circular variance defined as +1 - E cos(x - loc). The values are in the [0, 1] range. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMisesFisher.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMisesFisher.md index 004c2b6f42..2f2f5ecf01 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMisesFisher.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/VonMisesFisher.md @@ -1,5 +1,6 @@
+ @@ -99,6 +100,50 @@ x = [[0., 0, 1], vmf.prob(x) ``` +

__init__

+ +``` python +__init__( + mean_direction, + concentration, + validate_args=False, + allow_nan_stats=True, + name='VonMisesFisher' +) +``` + +Creates a new `VonMisesFisher` instance. + +#### Args: + +* `mean_direction`: Floating-point `Tensor` with shape [B1, ... Bn, D]. + A unit vector indicating the mode of the distribution, or the + unit-normalized direction of the mean. (This is *not* in general the + mean of the distribution; the mean is not generally in the support of + the distribution.) NOTE: `D` is currently restricted to <= 5. +* `concentration`: Floating-point `Tensor` having batch shape [B1, ... Bn] + broadcastable with `mean_direction`. The level of concentration of + samples around the `mean_direction`. `concentration=0` indicates a + uniform distribution over the unit hypersphere, and `concentration=+inf` + indicates a `Deterministic` distribution (delta function) at + `mean_direction`. +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + + +#### Raises: + +* `ValueError`: For known-bad arguments, i.e. unsupported event dimension. + + + ## Properties

allow_nan_stats

@@ -180,48 +225,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - mean_direction, - concentration, - validate_args=False, - allow_nan_stats=True, - name='VonMisesFisher' -) -``` - -Creates a new `VonMisesFisher` instance. - -#### Args: - -* `mean_direction`: Floating-point `Tensor` with shape [B1, ... Bn, D]. - A unit vector indicating the mode of the distribution, or the - unit-normalized direction of the mean. (This is *not* in general the - mean of the distribution; the mean is not generally in the support of - the distribution.) NOTE: `D` is currently restricted to <= 5. -* `concentration`: Floating-point `Tensor` having batch shape [B1, ... Bn] - broadcastable with `mean_direction`. The level of concentration of - samples around the `mean_direction`. `concentration=0` indicates a - uniform distribution over the unit hypersphere, and `concentration=+inf` - indicates a `Deterministic` distribution (delta function) at - `mean_direction`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, - statistics (e.g., mean, mode, variance) use the value "`NaN`" to - indicate the result is undefined. When `False`, an exception is raised - if one or more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - - -#### Raises: - -* `ValueError`: For known-bad arguments, i.e. unsupported event dimension. -

batch_shape_tensor

``` python @@ -361,7 +364,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -455,7 +458,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Wishart.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Wishart.md index 02660cb55a..ea4b341a71 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Wishart.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/Wishart.md @@ -1,5 +1,6 @@
+ @@ -101,6 +102,59 @@ dist.prob(x) # Shape is [2, 2]. # in tfp.distributions.matrix_diag_transform. ``` +

__init__

+ +``` python +__init__( + df, + scale=None, + scale_tril=None, + input_output_cholesky=False, + validate_args=False, + allow_nan_stats=True, + name='Wishart' +) +``` + +Construct Wishart distributions. + +#### Args: + +* `df`: `float` or `double` `Tensor`. Degrees of freedom, must be greater than + or equal to dimension of the scale matrix. +* `scale`: `float` or `double` `Tensor`. The symmetric positive definite + scale matrix of the distribution. Exactly one of `scale` and + 'scale_tril` must be passed. +* `scale_tril`: `float` or `double` `Tensor`. The Cholesky factorization + of the symmetric positive definite scale matrix of the distribution. + Exactly one of `scale` and 'scale_tril` must be passed. +* `input_output_cholesky`: Python `bool`. If `True`, functions whose input or + output have the semantics of samples assume inputs are in Cholesky form + and return outputs in Cholesky form. In particular, if this flag is + `True`, input to `log_prob` is presumed of Cholesky form and output from + `sample`, `mean`, and `mode` are of Cholesky form. Setting this + argument to `True` is purely a computational optimization and does not + change the underlying distribution; for instance, `mean` returns the + Cholesky of the mean, not the mean of Cholesky factors. The `variance` + and `stddev` methods are unaffected by this flag. + Default value: `False` (i.e., input/output does not have Cholesky + semantics). +* `validate_args`: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. +* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. +* `name`: Python `str` name prefixed to Ops created by this class. + +#### Raises: + +* `ValueError`: if zero or both of 'scale' and 'scale_tril' are passed in. + + + ## Properties

allow_nan_stats

@@ -190,57 +244,6 @@ Python `bool` indicating possibly expensive checks are enabled. ## Methods -

__init__

- -``` python -__init__( - df, - scale=None, - scale_tril=None, - input_output_cholesky=False, - validate_args=False, - allow_nan_stats=True, - name='Wishart' -) -``` - -Construct Wishart distributions. - -#### Args: - -* `df`: `float` or `double` `Tensor`. Degrees of freedom, must be greater than - or equal to dimension of the scale matrix. -* `scale`: `float` or `double` `Tensor`. The symmetric positive definite - scale matrix of the distribution. Exactly one of `scale` and - 'scale_tril` must be passed. -* `scale_tril`: `float` or `double` `Tensor`. The Cholesky factorization - of the symmetric positive definite scale matrix of the distribution. - Exactly one of `scale` and 'scale_tril` must be passed. -* `input_output_cholesky`: Python `bool`. If `True`, functions whose input or - output have the semantics of samples assume inputs are in Cholesky form - and return outputs in Cholesky form. In particular, if this flag is - `True`, input to `log_prob` is presumed of Cholesky form and output from - `sample`, `mean`, and `mode` are of Cholesky form. Setting this - argument to `True` is purely a computational optimization and does not - change the underlying distribution; for instance, `mean` returns the - Cholesky of the mean, not the mean of Cholesky factors. The `variance` - and `stddev` methods are unaffected by this flag. - Default value: `False` (i.e., input/output does not have Cholesky - semantics). -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. - -#### Raises: - -* `ValueError`: if zero or both of 'scale' and 'scale_tril' are passed in. -

batch_shape_tensor

``` python @@ -380,7 +383,7 @@ where `F` denotes the support of the random variable `X ~ P`. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. @@ -474,7 +477,7 @@ denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. #### Args: -* `other`: `tf.distributions.Distribution` instance. +* `other`: tfp.distributions.Distribution instance. * `name`: Python `str` prepended to names of ops created by this function. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_log_moving_mean_exp.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_log_moving_mean_exp.md index f801861ddb..d4b427e564 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_log_moving_mean_exp.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_log_moving_mean_exp.md @@ -1,5 +1,6 @@
+
# tfp.distributions.assign_log_moving_mean_exp diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_moving_mean_variance.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_moving_mean_variance.md index a43ed06278..cc8afc1537 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_moving_mean_variance.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/assign_moving_mean_variance.md @@ -1,5 +1,6 @@
+
# tfp.distributions.assign_moving_mean_variance diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/auto_correlation.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/auto_correlation.md index faef7813fb..17283f28e4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/auto_correlation.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/auto_correlation.md @@ -1,5 +1,6 @@
+
# tfp.distributions.auto_correlation diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular.md index cfe82b7d8c..1bf2b8f956 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular.md @@ -1,5 +1,6 @@
+
# tfp.distributions.fill_triangular diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular_inverse.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular_inverse.md index 1f1d7284dd..0a09d5b852 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular_inverse.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/fill_triangular_inverse.md @@ -1,5 +1,6 @@
+
# tfp.distributions.fill_triangular_inverse diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/kl_divergence.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/kl_divergence.md index 85bd478379..268de2e13f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/kl_divergence.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/kl_divergence.md @@ -1,5 +1,6 @@
+
# tfp.distributions.kl_divergence diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/matrix_diag_transform.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/matrix_diag_transform.md index 6e8e5a1915..a21c8756fd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/matrix_diag_transform.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/matrix_diag_transform.md @@ -1,5 +1,6 @@
+
# tfp.distributions.matrix_diag_transform @@ -43,7 +44,7 @@ chol = matrix_diag_transform(matrix, transform=tf.nn.softplus) mu = tf.contrib.layers.fully_connected(activations, 2) # This is a fully trainable multivariate normal! -dist = tfd.MVNCholesky(mu, chol) +dist = tfd.MultivariateNormalTriL(mu, chol) # Standard log loss. Minimizing this will "train" mu and chol, and then dist # will be a distribution predicting labels as multivariate Gaussians. @@ -63,4 +64,4 @@ loss = -1 * tf.reduce_mean(dist.log_prob(labels)) #### Returns: -A `Tensor` with same shape and `dtype` as `matrix`. +A `Tensor` with same shape and `dtype` as `matrix`. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/moving_mean_variance.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/moving_mean_variance.md index 5052345690..73917e5413 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/moving_mean_variance.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/moving_mean_variance.md @@ -1,5 +1,6 @@
+
# tfp.distributions.moving_mean_variance diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_posterior.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_posterior.md index fb81ad5076..ee5e1dffe8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_posterior.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_posterior.md @@ -1,5 +1,6 @@
+
# tfp.distributions.normal_conjugates_known_scale_posterior diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_predictive.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_predictive.md index f9583bff45..ca5c4d8e52 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_predictive.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/normal_conjugates_known_scale_predictive.md @@ -1,5 +1,6 @@
+
# tfp.distributions.normal_conjugates_known_scale_predictive diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/percentile.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/percentile.md index c9798e6cf2..f1f3c47b92 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/percentile.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/percentile.md @@ -1,5 +1,6 @@
+
# tfp.distributions.percentile diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_gauss_hermite.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_gauss_hermite.md index cd65863700..e0e3cafee0 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_gauss_hermite.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_gauss_hermite.md @@ -1,5 +1,6 @@
+
# tfp.distributions.quadrature_scheme_lognormal_gauss_hermite diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_quantiles.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_quantiles.md index 738b5841bf..96cc79bfc1 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_quantiles.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_lognormal_quantiles.md @@ -1,5 +1,6 @@
+
# tfp.distributions.quadrature_scheme_lognormal_quantiles diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_gauss_hermite.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_gauss_hermite.md index 499854d97a..0d70cbefab 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_gauss_hermite.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_gauss_hermite.md @@ -1,5 +1,6 @@
+
# tfp.distributions.quadrature_scheme_softmaxnormal_gauss_hermite diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_quantiles.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_quantiles.md index 72fa49f976..7b64b30cf8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_quantiles.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/quadrature_scheme_softmaxnormal_quantiles.md @@ -1,5 +1,6 @@
+
# tfp.distributions.quadrature_scheme_softmaxnormal_quantiles diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/reduce_weighted_logsumexp.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/reduce_weighted_logsumexp.md index da7508c420..b465f9691c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/reduce_weighted_logsumexp.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/reduce_weighted_logsumexp.md @@ -1,5 +1,6 @@
+
# tfp.distributions.reduce_weighted_logsumexp diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/softplus_inverse.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/softplus_inverse.md index dd0cc0d075..351f0549b4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/softplus_inverse.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/softplus_inverse.md @@ -1,5 +1,6 @@
+
# tfp.distributions.softplus_inverse diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/tridiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/tridiag.md index ff85aaf9bb..dfff152d2c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/tridiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/distributions/tridiag.md @@ -1,5 +1,6 @@
+
# tfp.distributions.tridiag diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2.md index 1035e3d918..e7bbcb64c8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2.md @@ -1,11 +1,19 @@
+
# Module: tfp.edward2 Edward2 probabilistic programming language. +For user guides, see: + ++ [Overview]( + https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/edward2/README.md) ++ [Upgrading from Edward to Edward2]( + https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/edward2/Upgrading_From_Edward_To_Edward2.md) + ## Classes [`class RandomVariable`](../tfp/edward2/RandomVariable.md): Class for random variables. @@ -104,9 +112,13 @@ Edward2 probabilistic programming language. [`as_random_variable(...)`](../tfp/edward2/as_random_variable.md): Wrap an existing distribution as a traceable random variable. -[`get_interceptor(...)`](../tfp/edward2/get_interceptor.md): Returns the top-most (last) interceptor on the thread's stack. +[`get_next_interceptor(...)`](../tfp/edward2/get_next_interceptor.md): Yields the top-most interceptor on the thread-local interceptor stack. + +[`interceptable(...)`](../tfp/edward2/interceptable.md): Decorator that wraps `func` so that its execution is intercepted. [`interception(...)`](../tfp/edward2/interception.md): Python context manager for interception. [`make_log_joint_fn(...)`](../tfp/edward2/make_log_joint_fn.md): Takes Edward probabilistic program and returns its log joint function. +[`tape(...)`](../tfp/edward2/tape.md): Context manager for recording interceptable executions onto a tape. + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Autoregressive.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Autoregressive.md index 8d2b157681..39d25d48d7 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Autoregressive.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Autoregressive.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Autoregressive diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Bernoulli.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Bernoulli.md index e5e9ec77c5..338fe89b00 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Bernoulli.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Bernoulli.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Bernoulli diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Beta.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Beta.md index ae634987a1..0d2526aa0f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Beta.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Beta.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Beta diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Binomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Binomial.md index 386a58c589..40b80e9ad9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Binomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Binomial.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Binomial diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Categorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Categorical.md index f668622a9e..682ed5f22d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Categorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Categorical.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Categorical diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Cauchy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Cauchy.md index 388a5eee01..af79283b18 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Cauchy.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Cauchy.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Cauchy diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Chi2.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Chi2.md index a947f1810e..c0738c442a 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Chi2.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Chi2.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Chi2 diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ConditionalTransformedDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ConditionalTransformedDistribution.md index 4880e0a92e..f7c97ecc3e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ConditionalTransformedDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ConditionalTransformedDistribution.md @@ -1,5 +1,6 @@
+
# tfp.edward2.ConditionalTransformedDistribution diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Deterministic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Deterministic.md index 8dbcfae201..0dc7bbd2e2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Deterministic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Deterministic.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Deterministic diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Dirichlet.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Dirichlet.md index aebf3d74ae..fc72ef6e17 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Dirichlet.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Dirichlet.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Dirichlet diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/DirichletMultinomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/DirichletMultinomial.md index b20822958c..1cfb5f7ed8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/DirichletMultinomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/DirichletMultinomial.md @@ -1,5 +1,6 @@
+
# tfp.edward2.DirichletMultinomial diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ExpRelaxedOneHotCategorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ExpRelaxedOneHotCategorical.md index d365258c02..dd20c650b3 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ExpRelaxedOneHotCategorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/ExpRelaxedOneHotCategorical.md @@ -1,5 +1,6 @@
+
# tfp.edward2.ExpRelaxedOneHotCategorical diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Exponential.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Exponential.md index 915716362d..07f25b6b48 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Exponential.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Exponential.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Exponential diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Gamma.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Gamma.md index 88a6c87d08..79ca2524be 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Gamma.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Gamma.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Gamma diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Geometric.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Geometric.md index 0f17eaf8e8..fe200f9c69 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Geometric.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Geometric.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Geometric diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/HalfNormal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/HalfNormal.md index dcbb45bcf6..2356bca6bf 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/HalfNormal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/HalfNormal.md @@ -1,5 +1,6 @@
+
# tfp.edward2.HalfNormal diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Independent.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Independent.md index 3eb7009118..9f8affa97d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Independent.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Independent.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Independent diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/InverseGamma.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/InverseGamma.md index 9b413496c4..959b34c15f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/InverseGamma.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/InverseGamma.md @@ -1,5 +1,6 @@
+
# tfp.edward2.InverseGamma diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Kumaraswamy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Kumaraswamy.md index da6e5102cf..ce2b51fbf9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Kumaraswamy.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Kumaraswamy.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Kumaraswamy diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Laplace.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Laplace.md index c7222cf7ca..160d133cf2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Laplace.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Laplace.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Laplace diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Logistic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Logistic.md index 917cced988..0f270e4c47 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Logistic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Logistic.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Logistic diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Mixture.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Mixture.md index aabadc4090..f40f8e04d2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Mixture.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Mixture.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Mixture diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MixtureSameFamily.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MixtureSameFamily.md index 4ce1e42766..71d0f7f564 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MixtureSameFamily.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MixtureSameFamily.md @@ -1,5 +1,6 @@
+
# tfp.edward2.MixtureSameFamily diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Multinomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Multinomial.md index ca9944a26a..0d2b4bbdef 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Multinomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Multinomial.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Multinomial diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalDiag.md index 65546d74b4..d6da2cc143 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalDiag.md @@ -1,5 +1,6 @@
+
# tfp.edward2.MultivariateNormalDiag diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalFullCovariance.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalFullCovariance.md index 0f454d2cea..089b0616ef 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalFullCovariance.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalFullCovariance.md @@ -1,5 +1,6 @@
+
# tfp.edward2.MultivariateNormalFullCovariance diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalTriL.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalTriL.md index eda3d1de0f..f497c01d3f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalTriL.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/MultivariateNormalTriL.md @@ -1,5 +1,6 @@
+
# tfp.edward2.MultivariateNormalTriL diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/NegativeBinomial.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/NegativeBinomial.md index 757ec408ba..846f6eb275 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/NegativeBinomial.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/NegativeBinomial.md @@ -1,5 +1,6 @@
+
# tfp.edward2.NegativeBinomial diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Normal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Normal.md index e5cf8892c4..6006387a36 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Normal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Normal.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Normal diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/OneHotCategorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/OneHotCategorical.md index c81360b92c..37e0707130 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/OneHotCategorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/OneHotCategorical.md @@ -1,5 +1,6 @@
+
# tfp.edward2.OneHotCategorical diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Poisson.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Poisson.md index 350e117b3c..0cc7e8bdc5 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Poisson.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Poisson.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Poisson diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/PoissonLogNormalQuadratureCompound.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/PoissonLogNormalQuadratureCompound.md index e96ebe70be..db3920c9c6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/PoissonLogNormalQuadratureCompound.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/PoissonLogNormalQuadratureCompound.md @@ -1,5 +1,6 @@
+
# tfp.edward2.PoissonLogNormalQuadratureCompound diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/QuantizedDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/QuantizedDistribution.md index 0cdea0d8c7..b3e813b337 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/QuantizedDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/QuantizedDistribution.md @@ -1,5 +1,6 @@
+
# tfp.edward2.QuantizedDistribution diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RandomVariable.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RandomVariable.md index 2d6fdedcc9..7e6c6c6f2c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RandomVariable.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RandomVariable.md @@ -1,5 +1,6 @@
+ @@ -96,33 +97,7 @@ assert x.distribution.batch_shape.as_list() == [] assert x.distribution.event_shape.as_list() == [] ``` -## Properties - -

distribution

- -Distribution of random variable. - -

dtype

- -`Dtype` of elements in this random variable. - -

sample_shape

- -Sample shape of random variable as a `TensorShape`. - -

shape

- -Shape of random variable. - -

value

- -Get tensor that the random variable corresponds to. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -149,7 +124,34 @@ Create a new random variable. * `ValueError`: `value` has incompatible shape with `sample_shape + distribution.batch_shape + distribution.event_shape`. -* `NotImplementedError`: `distribution` does not have a `sample` method. + + + +## Properties + +

distribution

+ +Distribution of random variable. + +

dtype

+ +`Dtype` of elements in this random variable. + +

sample_shape

+ +Sample shape of random variable as a `TensorShape`. + +

shape

+ +Shape of random variable. + +

value

+ +Get tensor that the random variable corresponds to. + + + +## Methods

__abs__

@@ -311,9 +313,6 @@ possibly an integer represented as floating point). This op is generated by `x // y` floor division in Python 3 and in Python 2.7 with `from __future__ import division`. -Note that for efficiency, `floordiv` uses C semantics for negative numbers -(unlike Python and Numpy). - `x` and `y` must have the same type, and the result will have the same type as well. @@ -326,7 +325,7 @@ as well. #### Returns: -`x / y` rounded down (except possibly towards zero for negative integers). +`x / y` rounded down. #### Raises: @@ -880,9 +879,6 @@ possibly an integer represented as floating point). This op is generated by `x // y` floor division in Python 3 and in Python 2.7 with `from __future__ import division`. -Note that for efficiency, `floordiv` uses C semantics for negative numbers -(unlike Python and Numpy). - `x` and `y` must have the same type, and the result will have the same type as well. @@ -895,7 +891,7 @@ as well. #### Returns: -`x / y` rounded down (except possibly towards zero for negative integers). +`x / y` rounded down. #### Raises: diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedBernoulli.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedBernoulli.md index 9db303a048..8db2fac91d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedBernoulli.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedBernoulli.md @@ -1,5 +1,6 @@
+
# tfp.edward2.RelaxedBernoulli diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedOneHotCategorical.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedOneHotCategorical.md index c7f40b3210..f187bb6a82 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedOneHotCategorical.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/RelaxedOneHotCategorical.md @@ -1,5 +1,6 @@
+
# tfp.edward2.RelaxedOneHotCategorical diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/SinhArcsinh.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/SinhArcsinh.md index f26b2be91c..6acf68764b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/SinhArcsinh.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/SinhArcsinh.md @@ -1,5 +1,6 @@
+
# tfp.edward2.SinhArcsinh diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/StudentT.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/StudentT.md index 95d171e7b2..f286105f3c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/StudentT.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/StudentT.md @@ -1,5 +1,6 @@
+
# tfp.edward2.StudentT diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/TransformedDistribution.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/TransformedDistribution.md index 13171608ef..9220d6c775 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/TransformedDistribution.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/TransformedDistribution.md @@ -1,5 +1,6 @@
+
# tfp.edward2.TransformedDistribution diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Uniform.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Uniform.md index feb0014181..fe9f16a39b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Uniform.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Uniform.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Uniform diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDeterministic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDeterministic.md index 315044dfa8..bf11077bfe 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDeterministic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDeterministic.md @@ -1,5 +1,6 @@
+
# tfp.edward2.VectorDeterministic diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDiffeomixture.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDiffeomixture.md index 00b982a168..8c2dfb45bd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDiffeomixture.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorDiffeomixture.md @@ -1,5 +1,6 @@
+
# tfp.edward2.VectorDiffeomixture diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorExponentialDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorExponentialDiag.md index f780454eb8..b065b2e813 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorExponentialDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorExponentialDiag.md @@ -1,5 +1,6 @@
+
# tfp.edward2.VectorExponentialDiag diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorLaplaceDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorLaplaceDiag.md index 5cd558af06..3498189c68 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorLaplaceDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorLaplaceDiag.md @@ -1,5 +1,6 @@
+
# tfp.edward2.VectorLaplaceDiag diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorSinhArcsinhDiag.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorSinhArcsinhDiag.md index 7a5fd59de1..b1ec533b35 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorSinhArcsinhDiag.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/VectorSinhArcsinhDiag.md @@ -1,5 +1,6 @@
+
# tfp.edward2.VectorSinhArcsinhDiag diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Wishart.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Wishart.md index 8060c34d2e..a5bf849c25 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Wishart.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/Wishart.md @@ -1,5 +1,6 @@
+
# tfp.edward2.Wishart diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/WishartCholesky.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/WishartCholesky.md deleted file mode 100644 index 42c5509d69..0000000000 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/WishartCholesky.md +++ /dev/null @@ -1,52 +0,0 @@ -Project: /probability/_project.yaml -Book: /probability/_book.yaml -page_type: reference -Project: /probability/_project.yaml -Book: /probability/_book.yaml -page_type: reference -
- -
- -# tfp.edward2.WishartCholesky - -``` python -tfp.edward2.WishartCholesky( - *args, - **kwargs -) -``` - -Create a random variable for WishartCholesky. - -See WishartCholesky for more details. - -#### Returns: - - RandomVariable. - -#### Original Docstring for Distribution - -Construct Wishart distributions. - - -#### Args: - -* `df`: `float` or `double` `Tensor`. Degrees of freedom, must be greater than - or equal to dimension of the scale matrix. -* `scale`: `float` or `double` `Tensor`. The Cholesky factorization of - the symmetric positive definite scale matrix of the distribution. -* `cholesky_input_output_matrices`: Python `bool`. Any function which whose - input or output is a matrix assumes the input is Cholesky and returns a - Cholesky factored matrix. Example `log_prob` input takes a Cholesky and - `sample_n` returns a Cholesky when - `cholesky_input_output_matrices=True`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/WishartFull.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/WishartFull.md deleted file mode 100644 index 7def8d90cc..0000000000 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/WishartFull.md +++ /dev/null @@ -1,52 +0,0 @@ -Project: /probability/_project.yaml -Book: /probability/_book.yaml -page_type: reference -Project: /probability/_project.yaml -Book: /probability/_book.yaml -page_type: reference -
- -
- -# tfp.edward2.WishartFull - -``` python -tfp.edward2.WishartFull( - *args, - **kwargs -) -``` - -Create a random variable for WishartFull. - -See WishartFull for more details. - -#### Returns: - - RandomVariable. - -#### Original Docstring for Distribution - -Construct Wishart distributions. - - -#### Args: - -* `df`: `float` or `double` `Tensor`. Degrees of freedom, must be greater than - or equal to dimension of the scale matrix. -* `scale`: `float` or `double` `Tensor`. The symmetric positive definite - scale matrix of the distribution. -* `cholesky_input_output_matrices`: Python `bool`. Any function which whose - input or output is a matrix assumes the input is Cholesky and returns a - Cholesky factored matrix. Example `log_prob` input takes a Cholesky and - `sample_n` returns a Cholesky when - `cholesky_input_output_matrices=True`. -* `validate_args`: Python `bool`, default `False`. When `True` distribution - parameters are checked for validity despite possibly degrading runtime - performance. When `False` invalid inputs may silently render incorrect - outputs. -* `allow_nan_stats`: Python `bool`, default `True`. When `True`, statistics - (e.g., mean, mode, variance) use the value "`NaN`" to indicate the - result is undefined. When `False`, an exception is raised if one or - more of the statistic's batch members are undefined. -* `name`: Python `str` name prefixed to Ops created by this class. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/as_random_variable.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/as_random_variable.md index 6368971734..bf4fc3f148 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/as_random_variable.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/as_random_variable.md @@ -1,5 +1,6 @@
+
# tfp.edward2.as_random_variable diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/get_interceptor.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/get_interceptor.md deleted file mode 100644 index f1d51c8b04..0000000000 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/get_interceptor.md +++ /dev/null @@ -1,15 +0,0 @@ -
- -
- -# tfp.edward2.get_interceptor - -``` python -tfp.edward2.get_interceptor() -``` - -Returns the top-most (last) interceptor on the thread's stack. - -The bottom-most (first) interceptor in the stack is a function which takes -`f, *args, **kwargs` as input and returns `f(*args, **kwargs)`. It is the -default if no `interception` contexts have been entered. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/get_next_interceptor.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/get_next_interceptor.md new file mode 100644 index 0000000000..f59d2ef2e2 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/get_next_interceptor.md @@ -0,0 +1,84 @@ +
+ + +
+ +# tfp.edward2.get_next_interceptor + +``` python +tfp.edward2.get_next_interceptor( + *args, + **kwds +) +``` + +Yields the top-most interceptor on the thread-local interceptor stack. + +Operations may be intercepted by multiple nested interceptors. Once reached, +an operation can be forwarded through nested interceptors until resolved. +To allow for nesting, implement interceptors by re-wrapping their first +argument (`f`) as an `interceptable`. To avoid nesting, manipulate the +computation without using `interceptable`. + +This function allows for nesting by manipulating the thread-local interceptor +stack, so that operations are intercepted in the order of interceptor nesting. + +#### Examples + +```python +from tensorflow_probability import edward2 as ed + +def model(): + x = ed.Normal(loc=0., scale=1., name="x") + y = ed.Normal(loc=x, scale=1., name="y") + return x + y + +def double(f, *args, **kwargs): + return 2. * interceptable(f)(*args, **kwargs) + +def set_y(f, *args, **kwargs): + if kwargs.get("name") == "y": + kwargs["value"] = 0.42 + return interceptable(f)(*args, **kwargs) + +with interception(double): + with interception(set_y): + z = model() +``` + +This will firstly put `double` on the stack, and then `set_y`, +resulting in the stack: +(TOP) set_y -> double -> apply (BOTTOM) + +The execution of `model` is then (top lines are current stack state): +1) (TOP) set_y -> double -> apply (BOTTOM); +`ed.Normal(0., 1., "x")` is intercepted by `set_y`, and as the name is not "y" +the operation is simply forwarded to the next interceptor on the stack. + +2) (TOP) double -> apply (BOTTOM); +`ed.Normal(0., 1., "x")` is intercepted by `double`, to produce +`2*ed.Normal(0., 1., "x")`, with the operation being forwarded down the stack. + +3) (TOP) apply (BOTTOM); +`ed.Normal(0., 1., "x")` is intercepted by `apply`, which simply calls the +constructor. + +(At this point, the nested calls to `get_next_interceptor()`, produced by +forwarding operations, exit, and the current stack is again: +(TOP) set_y -> double -> apply (BOTTOM)) + +4) (TOP) set_y -> double -> apply (BOTTOM); +`ed.Normal(0., 1., "y")` is intercepted by `set_y`, +the value of `y` is set to 0.42 and the operation is forwarded down the stack. + +5) (TOP) double -> apply (BOTTOM); +`ed.Normal(0., 1., "y")` is intercepted by `double`, to produce +`2*ed.Normal(0., 1., "y")`, with the operation being forwarded down the stack. + +6) (TOP) apply (BOTTOM); +`ed.Normal(0., 1., "y")` is intercepted by `apply`, which simply calls the +constructor. + +The final values for `x` and `y` inside of `model()` are tensors where `x` is +a random draw from Normal(0., 1.) doubled, and `y` is a constant 0.84, thus +z = 2 * Normal(0., 1.) + 0.84. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interceptable.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interceptable.md new file mode 100644 index 0000000000..893144c977 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interceptable.md @@ -0,0 +1,27 @@ +
+ + +
+ +# tfp.edward2.interceptable + +``` python +tfp.edward2.interceptable(func) +``` + +Decorator that wraps `func` so that its execution is intercepted. + +The wrapper passes `func` to the interceptor for the current thread. + +If there is no next interceptor, we perform an "immediate" call to `func`. +That is, `func` terminates without forwarding its execution to another +interceptor. + +#### Args: + +* `func`: Function to wrap. + + +#### Returns: + +The decorated function. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interception.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interception.md index 57d0c29499..ec9e9f6236 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interception.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/interception.md @@ -1,5 +1,6 @@
+
# tfp.edward2.interception @@ -40,11 +41,16 @@ def model(): def interceptor(f, *args, **kwargs): if kwargs.get("name") == "y": kwargs["value"] = 42 - return f(*args, **kwargs) + return interceptable(f)(*args, **kwargs) with ed.interception(interceptor): y = model() with tf.Session() as sess: assert sess.run(y.value) == 42 -``` \ No newline at end of file +``` + +Wrapping `f` as `interceptable` allows interceptors down the stack to +additionally modify this operation. Since the operation `f()` is not wrapped +by default, we could have called it directly. Refer also to the example in +`get_next_interceptor()` for more details on nested interceptors. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/make_log_joint_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/make_log_joint_fn.md index c794244249..325d481789 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/make_log_joint_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/make_log_joint_fn.md @@ -1,5 +1,6 @@
+
# tfp.edward2.make_log_joint_fn @@ -13,7 +14,7 @@ Takes Edward probabilistic program and returns its log joint function. #### Args: * `model`: Python callable which executes the generative process of a - computable probability distribution using Edward `RandomVariable`s. + computable probability distribution using `ed.RandomVariable`s. #### Returns: @@ -24,23 +25,24 @@ Takes Edward probabilistic program and returns its log joint function. #### Examples -Below we define Bayesian logistic regression as an Edward program, which -represents the model's generative process. We apply `make_log_joint_fn` in -order to alternatively represent the model in terms of its joint probability -function. +Below we define Bayesian logistic regression as an Edward program, +representing the model's generative process. We apply `make_log_joint_fn` in +order to represent the model in terms of its joint probability function. ```python from tensorflow_probability import edward2 as ed -def model(X): - w = ed.Normal(loc=0., scale=1., sample_shape=X.shape[1], name="w") - y = ed.Normal(loc=tf.tensordot(X, w, [[1], [0]]), scale=0.1, name="y") - return y +def logistic_regression(features): + coeffs = ed.Normal(loc=0., scale=1., + sample_shape=features.shape[1], name="coeffs") + outcomes = ed.Bernoulli(logits=tf.tensordot(features, coeffs, [[1], [0]]), + name="outcomes") + return outcomes -log_joint = ed.make_log_joint_fn(model) +log_joint = ed.make_log_joint_fn(logistic_regression) -X = tf.random_normal([3, 2]) -w_value = tf.random_normal([2]) -y_value = tf.random_normal([3]) -output = log_joint(X, w=w_value, y=y_value) +features = tf.random_normal([3, 2]) +coeffs_value = tf.random_normal([2]) +outcomes_value = tf.round(tf.random_uniform([3])) +output = log_joint(features, coeffs=coeffs_value, outcomes=outcomes_value) ``` \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/tape.md b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/tape.md new file mode 100644 index 0000000000..6eb2f44011 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/edward2/tape.md @@ -0,0 +1,47 @@ +
+ + +
+ +# tfp.edward2.tape + +``` python +tfp.edward2.tape( + *args, + **kwds +) +``` + +Context manager for recording interceptable executions onto a tape. + +Similar to `tf.GradientTape`, operations are recorded if they are executed +within this context manager. In addition, the operation must be registered +(wrapped) as `ed.interceptable`. + +#### Yields: + +* `tape`: OrderedDict where operations are recorded in sequence. Keys are + the `name` keyword argument to the operation (typically, a random + variable's `name`) and values are the corresponding output of the + operation. If the operation has no name, it is not recorded. + +#### Examples + +```python +from tensorflow_probability import edward2 as ed + +def probabilistic_matrix_factorization(): + users = ed.Normal(0., 1., sample_shape=[5000, 128], name="users") + items = ed.Normal(0., 1., sample_shape=[7500, 128], name="items") + ratings = ed.Normal(loc=tf.matmul(users, items, transpose_b=True), + scale=0.1, + name="ratings") + return ratings + +with ed.tape() as model_tape: + ratings = probabilistic_matrix_factorization() + +assert model_tape["users"].shape == (5000, 128) +assert model_tape["items"].shape == (7500, 128) +assert model_tape["ratings"] == ratings +``` \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm.md index 3e78db8df8..1eb705ee99 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm.md @@ -1,5 +1,6 @@
+
# Module: tfp.glm @@ -40,3 +41,9 @@ TensorFlow Probability GLM python package. [`fit_one_step(...)`](../tfp/glm/fit_one_step.md): Runs one step of Fisher scoring. +[`fit_sparse(...)`](../tfp/glm/fit_sparse.md): Fits a GLM using coordinate-wise FIM-informed proximal gradient descent. + +[`fit_sparse_one_step(...)`](../tfp/glm/fit_sparse_one_step.md): One step of (the outer loop of) the GLM fitting algorithm. + +[`soft_threshold(...)`](../tfp/glm/soft_threshold.md): Soft Thresholding operator. + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Bernoulli.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Bernoulli.md index 009f6829f6..e4879f4d0d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Bernoulli.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Bernoulli.md @@ -1,5 +1,6 @@
+ @@ -15,6 +16,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Bernoulli(probs=mean)` where `mean = sigmoid(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -29,19 +45,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/BernoulliNormalCDF.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/BernoulliNormalCDF.md index 11f8bcce5c..b19dd958ee 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/BernoulliNormalCDF.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/BernoulliNormalCDF.md @@ -1,5 +1,6 @@
+ @@ -16,6 +17,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Bernoulli(probs=mean)` where `mean = Normal(0, 1).cdf(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -30,19 +46,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/CustomExponentialFamily.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/CustomExponentialFamily.md index d060c8772a..5367206752 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/CustomExponentialFamily.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/CustomExponentialFamily.md @@ -1,5 +1,6 @@
+ @@ -17,29 +18,7 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) Constucts GLM from arbitrary distribution and inverse link function. -## Properties - -

distribution_fn

- - - -

is_canonical

- -Returns `True` when `variance(r) == grad_mean(r)` for all `r`. - -

linear_model_to_mean_fn

- - - -

name

- -Returns TF namescope prefixed to ops created by member functions. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -68,6 +47,30 @@ Creates the `CustomExponentialFamily`. * `name`: Python `str` used as TF namescope for ops created by member functions. Default value: `None` (i.e., the subclass name). + + +## Properties + +

distribution_fn

+ + + +

is_canonical

+ +Returns `True` when `variance(r) == grad_mean(r)` for all `r`. + +

linear_model_to_mean_fn

+ + + +

name

+ +Returns TF namescope prefixed to ops created by member functions. + + + +## Methods +

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/ExponentialFamily.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/ExponentialFamily.md index ede8ea0c1d..3541410833 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/ExponentialFamily.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/ExponentialFamily.md @@ -1,5 +1,6 @@
+ @@ -33,6 +34,21 @@ Subclasses must implement `_call`, `_log_prob`, and `_is_canonical`. In context of tfp.glm.fit, these functions are used to find the best fitting weights for given model matrix ("X") and responses ("Y"). +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -47,19 +63,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaExp.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaExp.md index 1513890afc..d80d5da002 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaExp.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaExp.md @@ -1,5 +1,6 @@
+ @@ -16,6 +17,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Gamma(concentration=1, rate=1 / mean)` where `mean = exp(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -30,19 +46,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaSoftplus.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaSoftplus.md index e9ccfe98a6..8d51179d87 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaSoftplus.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/GammaSoftplus.md @@ -1,5 +1,6 @@
+ @@ -16,6 +17,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Gamma(concentration=1, rate=1 / mean)` where `mean = softplus(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -30,19 +46,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormal.md index a8bcb28fb9..6a71388f0f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormal.md @@ -1,5 +1,6 @@
+ @@ -16,6 +17,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `LogNormal(loc=log(mean) - log(2) / 2, scale=sqrt(log(2)))` where `mean = exp(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -30,19 +46,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormalSoftplus.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormalSoftplus.md index 7cc5f5562b..5b0413f266 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormalSoftplus.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/LogNormalSoftplus.md @@ -1,5 +1,6 @@
+ @@ -16,6 +17,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `LogNormal(loc=log(mean) - log(2) / 2, scale=sqrt(log(2)))` `mean = softplus(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -30,19 +46,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Normal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Normal.md index 7cf4dbef7c..1be4d55c66 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Normal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Normal.md @@ -1,5 +1,6 @@
+ @@ -15,6 +16,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Normal(loc=mean, scale=1)` where `mean = matmul(X, weights)`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -29,19 +45,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/NormalReciprocal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/NormalReciprocal.md index 8d51cfc77d..ec03c23b96 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/NormalReciprocal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/NormalReciprocal.md @@ -1,5 +1,6 @@
+ @@ -15,6 +16,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Normal(loc=mean, scale=1)` where `mean = 1 / matmul(X, weights)`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -29,19 +45,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Poisson.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Poisson.md index 360f342d1b..a2c75f7846 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Poisson.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/Poisson.md @@ -1,5 +1,6 @@
+ @@ -15,6 +16,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Poisson(rate=mean)` where `mean = exp(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -29,19 +45,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/PoissonSoftplus.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/PoissonSoftplus.md index 9115762467..efecc736c2 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/PoissonSoftplus.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/PoissonSoftplus.md @@ -1,5 +1,6 @@
+ @@ -15,6 +16,21 @@ Inherits From: [`ExponentialFamily`](../../tfp/glm/ExponentialFamily.md) `Poisson(rate=mean)` where `mean = softplus(matmul(X, weights))`. +

__init__

+ +``` python +__init__(name=None) +``` + +Creates the ExponentialFamily. + +#### Args: + +* `name`: Python `str` used as TF namescope for ops created by member + functions. Default value: `None` (i.e., the subclass name). + + + ## Properties

is_canonical

@@ -29,19 +45,6 @@ Returns TF namescope prefixed to ops created by member functions. ## Methods -

__init__

- -``` python -__init__(name=None) -``` - -Creates the ExponentialFamily. - -#### Args: - -* `name`: Python `str` used as TF namescope for ops created by member - functions. Default value: `None` (i.e., the subclass name). -

__call__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/convergence_criteria_small_relative_norm_weights_change.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/convergence_criteria_small_relative_norm_weights_change.md index ac3d1a7607..acc184cd83 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/convergence_criteria_small_relative_norm_weights_change.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/convergence_criteria_small_relative_norm_weights_change.md @@ -1,5 +1,6 @@
+
# tfp.glm.convergence_criteria_small_relative_norm_weights_change diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit.md index fabd7c552e..4759adb959 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit.md @@ -1,5 +1,6 @@
+
# tfp.glm.fit @@ -135,7 +136,7 @@ with tf.Session() as sess: [w_, linear_response_, is_converged_, num_iter_, Y_, w_true_, log_likelihood_] = sess.run([ w, linear_response, is_converged, num_iter, Y, w_true, - log_likelihood_]) + log_likelihood]) print('is_converged: ', is_converged_) print(' num_iter: ', num_iter_) diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_one_step.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_one_step.md index c2db303d20..841400b08c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_one_step.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_one_step.md @@ -1,5 +1,6 @@
+
# tfp.glm.fit_one_step diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_sparse.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_sparse.md new file mode 100644 index 0000000000..93f1555916 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_sparse.md @@ -0,0 +1,245 @@ +
+ + +
+ +# tfp.glm.fit_sparse + +``` python +tfp.glm.fit_sparse( + model_matrix, + response, + model, + model_coefficients_start, + tolerance, + l1_regularizer, + l2_regularizer=None, + maximum_iterations=None, + maximum_full_sweeps_per_iteration=1, + learning_rate=None, + model_coefficients_update_var=None, + name=None +) +``` + +Fits a GLM using coordinate-wise FIM-informed proximal gradient descent. + +This function uses a L1- and L2-regularized, second-order quasi-Newton method +to find maximum-likelihood parameters for the given model and observed data. +The second-order approximations use negative Fisher information in place of +the Hessian, that is, + +```none +FisherInfo = E_Y[Hessian with respect to model_coefficients of -LogLikelihood( + Y | model_matrix, current value of model_coefficients)] +``` + +For large, sparse data sets, `model_matrix` should be supplied as a +`SparseTensor`. + +#### Args: + +* `model_matrix`: matrix-shaped, `float` `Tensor` or `SparseTensor` where each + row represents a sample's features. Has shape `[N, n]` where `N` is the + number of data samples and `n` is the number of features per sample. +* `response`: vector-shaped `Tensor` with the same dtype as `model_matrix` where + each element represents a sample's observed response (to the corresponding + row of features). +* `model`: tfp.glm.ExponentialFamily-like instance, which specifies the link + function and distribution of the GLM, and thus characterizes the negative + log-likelihood which will be minimized. Must have sufficient statistic + equal to the response, that is, `T(y) = y`. +* `model_coefficients_start`: vector-shaped, `float` `Tensor` with the same + dtype as `model_matrix`, representing the initial values of the + coefficients for the GLM regression. Has shape `[n]` where `model_matrix` + has shape `[N, n]`. +* `tolerance`: scalar, `float` `Tensor` representing the tolerance for each + optiization step; see the `tolerance` argument of `fit_sparse_one_step`. +* `l1_regularizer`: scalar, `float` `Tensor` representing the weight of the L1 + regularization term. +* `l2_regularizer`: scalar, `float` `Tensor` representing the weight of the L2 + regularization term. + Default value: `None` (i.e., no L2 regularization). +* `maximum_iterations`: Python integer specifying maximum number of iterations + of the outer loop of the optimizer (i.e., maximum number of calls to + `fit_sparse_one_step`). After this many iterations of the outer loop, the + algorithm will terminate even if the return value `model_coefficients` has + not converged. + Default value: `1`. +* `maximum_full_sweeps_per_iteration`: Python integer specifying the maximum + number of coordinate descent sweeps allowed in each iteration. + Default value: `1`. +* `learning_rate`: scalar, `float` `Tensor` representing a multiplicative factor + used to dampen the proximal gradient descent steps. + Default value: `None` (i.e., factor is conceptually `1`). +* `model_coefficients_update_var`: `Variable` with the same shape and dtype as + `model_coefficients_start`. Used to store the current value of + `model_coefficients_update`. + Default value: `None` (i.e., a new `Variable` will be created). +* `name`: Python string representing the name of the TensorFlow operation. + The default name is `"fit_sparse"`. + +Note that this function does not support batched inputs. + + +#### Returns: + +* `model_coefficients`: `Tensor` of the same shape and dtype as + `model_coefficients_start`, representing the computed model coefficients + which minimize the regularized negative log-likelihood. +* `is_converged`: scalar, `bool` `Tensor` indicating whether the minimization + procedure converged within the specified number of iterations. Here + convergence means that an iteration of the inner loop + (`fit_sparse_one_step`) returns `True` for its `is_converged` output + value. +* `iter`: scalar, `int` `Tensor` indicating the actual number of iterations of + the outer loop of the optimizer completed (i.e., number of calls to + `fit_sparse_one_step` before achieving convergence). + +#### Example + +```python +from __future__ import print_function +import numpy as np +import tensorflow as tf +import tensorflow_probability as tfp +tfd = tfp.distributions + +def make_dataset(n, d, link, scale=1., dtype=np.float32): + model_coefficients = tfd.Uniform( + low=np.array(-1, dtype), high=np.array(1, dtype)).sample( + d, seed=42) + radius = np.sqrt(2.) + model_coefficients *= radius / tf.linalg.norm(model_coefficients) + mask = tf.random_shuffle(tf.range(d)) < tf.to_int32(0.5 * tf.to_float(d)) + model_coefficients = tf.where(mask, model_coefficients, + tf.zeros_like(model_coefficients)) + model_matrix = tfd.Normal( + loc=np.array(0, dtype), scale=np.array(1, dtype)).sample( + [n, d], seed=43) + scale = tf.convert_to_tensor(scale, dtype) + linear_response = tf.matmul(model_matrix, + model_coefficients[..., tf.newaxis])[..., 0] + if link == 'linear': + response = tfd.Normal(loc=linear_response, scale=scale).sample(seed=44) + elif link == 'probit': + response = tf.cast( + tfd.Normal(loc=linear_response, scale=scale).sample(seed=44) > 0, + dtype) + elif link == 'logit': + response = tfd.Bernoulli(logits=linear_response).sample(seed=44) +* `else`: raise ValueError('unrecognized true link: {}'.format(link)) + return model_matrix, response, model_coefficients, mask + +with tf.Session() as sess: + x_, y_, model_coefficients_true_, _ = sess.run(make_dataset( + n=int(1e5), d=100, link='probit')) + + model = tfp.glm.Bernoulli() + model_coefficients_start = tf.zeros(x_.shape[-1], np.float32) + + with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): + model_coefficients, is_converged, num_iter = tfp.glm.fit_sparse( + model_matrix=tf.convert_to_tensor(x_), + response=tf.convert_to_tensor(y_), + model=model, + model_coefficients_start=model_coefficients_start, + l1_regularizer=800., + l2_regularizer=None, + maximum_iterations=10, + maximum_full_sweeps_per_iteration=10, + tolerance=1e-6, + learning_rate=None) + + init_op = tf.global_variables_initializer() + sess.run([init_op]) + model_coefficients_, is_converged_, num_iter_ = sess.run([ + model_coefficients, is_converged, num_iter]) + + print("is_converged:", is_converged_) + print(" num_iter:", num_iter_) + print("\nLearned / True") + print(np.concatenate( + [[model_coefficients_], [model_coefficients_true_]], axis=0).T) + +# ==> +# is_converged: True +# num_iter: 1 +# +# Learned / True +# [[ 0. 0. ] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0.11195257 0.12484948] +# [ 0. 0. ] +# [ 0.05191106 0.06394956] +# [-0.15090358 -0.15325639] +# [-0.18187316 -0.18825999] +# [-0.06140942 -0.07994166] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0.14474444 0.15810856] +# [ 0. 0. ] +# [-0.25249591 -0.24260855] +# [ 0. 0. ] +# [ 0. 0. ] +# [-0.03888761 -0.06755984] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0. 0. ] +# [-0.0192222 -0.04169233] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0.01434913 0.03568212] +# [-0.11336883 -0.12873614] +# [ 0. 0. ] +# [-0.24496339 -0.24048163] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0.04088281 0.06565224] +# [-0.12784363 -0.13359821] +# [ 0.05618424 0.07396613] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0. 0. ] +# [ 0. -0.01719233] +# [ 0. 0. ] +# [ 0. 0. ] +# [-0.00076072 -0.03607186] +# [ 0.21801499 0.21146794] +# [-0.02161094 -0.04031265] +# [ 0.0918689 0.10487888] +# [ 0.0106154 0.03233612] +# [-0.07817317 -0.09725142] +# [ 0. 0. ] +# [ 0. 0. ] +# [-0.23725343 -0.24194022] +# [ 0. 0. ] +# [-0.08725718 -0.1048776 ] +# [ 0. 0. ] +# [ 0. 0. ] +# [-0.02114314 -0.04145789] +# [ 0. 0. ] +# [ 0. 0. ] +# [-0.02710908 -0.04590397] +# [ 0.15293184 0.15415154] +# [ 0.2114463 0.2088728 ] +# [-0.10969634 -0.12368613] +# [ 0. -0.01505797] +# [-0.01140458 -0.03234904] +# [ 0.16051085 0.1680062 ] +# [ 0.09816848 0.11094204] +``` + +#### References + +[1]: Jerome Friedman, Trevor Hastie and Rob Tibshirani. Regularization Paths + for Generalized Linear Models via Coordinate Descent. _Journal of + Statistical Software_, 33(1), 2010. + https://www.jstatsoft.org/article/view/v033i01/v33i01.pdf + +[2]: Guo-Xun Yuan, Chia-Hua Ho and Chih-Jen Lin. An Improved GLMNET for + L1-regularized Logistic Regression. _Journal of Machine Learning + Research_, 13, 2012. + http://www.jmlr.org/papers/volume13/yuan12a/yuan12a.pdf \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_sparse_one_step.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_sparse_one_step.md new file mode 100644 index 0000000000..5c631ad9c2 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/fit_sparse_one_step.md @@ -0,0 +1,116 @@ +
+ + +
+ +# tfp.glm.fit_sparse_one_step + +``` python +tfp.glm.fit_sparse_one_step( + model_matrix, + response, + model, + model_coefficients_start, + tolerance, + l1_regularizer, + l2_regularizer=None, + maximum_full_sweeps=None, + learning_rate=None, + model_coefficients_update_var=None, + name=None +) +``` + +One step of (the outer loop of) the GLM fitting algorithm. + +This function returns a new value of `model_coefficients`, equal to +`model_coefficients_start + model_coefficients_update`. The increment +`model_coefficients_update in R^n` is computed by a coordinate descent method, +that is, by a loop in which each iteration updates exactly one coordinate of +`model_coefficients_update`. (Some updates may leave the value of the +coordinate unchanged.) + +The particular update method used is to apply an L1-based proximity operator, +"soft threshold", whose fixed point `model_coefficients_update^*` is the +desired minimum + +```none +model_coefficients_update^* = argmin{ + -LogLikelihood(model_coefficients_start + model_coefficients_update') + + l1_regularizer * + ||model_coefficients_start + model_coefficients_update'||_1 + + l2_regularizer * + ||model_coefficients_start + model_coefficients_update'||_2**2 + : model_coefficients_update' } +``` + +where in each iteration `model_coefficients_update'` has at most one nonzero +coordinate. + +This update method preserves sparsity, i.e., tends to find sparse solutions if +`model_coefficients_start` is sparse. Additionally, the choice of step size +is based on curvature (Fisher information matrix), which significantly speeds +up convergence. + +Note that this function does not support batched inputs. + +#### Args: + +* `model_matrix`: matrix-shaped, `float` `Tensor` or `SparseTensor` where each + row represents a sample's features. Has shape `[N, n]` where `N` is the + number of data samples and `n` is the number of features per sample. +* `response`: vector-shaped `Tensor` with the same dtype as `model_matrix` where + each element represents a sample's observed response (to the corresponding + row of features). +* `model`: tfp.glm.ExponentialFamily-like instance, which specifies the link + function and distribution of the GLM, and thus characterizes the negative + log-likelihood which will be minimized. Must have sufficient statistic + equal to the response, that is, `T(y) = y`. +* `model_coefficients_start`: vector-shaped, `float` `Tensor` with the same + dtype as `model_matrix`, representing the initial values of the + coefficients for the GLM regression. Has shape `[n]` where `model_matrix` + has shape `[N, n]`. +* `tolerance`: scalar, `float` `Tensor` representing the convergence threshold. + The optimization step will terminate early, returning its current value of + `model_coefficients_start + model_coefficients_update`, once the following + condition is met: + `||model_coefficients_update_end - model_coefficients_update_start||_2 + / (1 + ||model_coefficients_start||_2) + < sqrt(tolerance)`, + where `model_coefficients_update_end` is the value of + `model_coefficients_update` at the end of a sweep and + `model_coefficients_update_start` is the value of + `model_coefficients_update` at the beginning of that sweep. +* `l1_regularizer`: scalar, `float` `Tensor` representing the weight of the L1 + regularization term (see equation above). +* `l2_regularizer`: scalar, `float` `Tensor` representing the weight of the L2 + regularization term (see equation above). + Default value: `None` (i.e., no L2 regularization). +* `maximum_full_sweeps`: Python integer specifying maximum number of sweeps to + run. A "sweep" consists of an iteration of coordinate descent on each + coordinate. After this many sweeps, the algorithm will terminate even if + convergence has not been reached. + Default value: `1`. +* `learning_rate`: scalar, `float` `Tensor` representing a multiplicative factor + used to dampen the proximal gradient descent steps. + Default value: `None` (i.e., factor is conceptually `1`). +* `model_coefficients_update_var`: `Variable` with the same shape and dtype as + `model_coefficients_start`. Used to store the current value of + `model_coefficients_update`. + Default value: `None` (i.e., a new `Variable` will be created). +* `name`: Python string representing the name of the TensorFlow operation. + The default name is `"fit_sparse_one_step"`. + + +#### Returns: + +* `model_coefficients`: `Tensor` having the same shape and dtype as + `model_coefficients_start`, representing the updated value of + `model_coefficients`, that is, `model_coefficients_start + + model_coefficients_update`. +* `is_converged`: scalar, `bool` `Tensor` indicating whether convergence + occurred within the specified number of sweeps. +* `iter`: scalar, `int` `Tensor` representing the actual number of coordinate + updates made (before achieving convergence). Since each sweep consists of + `tf.size(model_coefficients_start)` iterations, the maximum number of + updates is `maximum_full_sweeps * tf.size(model_coefficients_start)`. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/glm/soft_threshold.md b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/soft_threshold.md new file mode 100644 index 0000000000..2596c994e0 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/glm/soft_threshold.md @@ -0,0 +1,100 @@ +
+ + +
+ +# tfp.glm.soft_threshold + +``` python +tfp.glm.soft_threshold( + x, + threshold, + name=None +) +``` + +Soft Thresholding operator. + +This operator is defined by the equations + +```none + { x[i] - gamma, x[i] > gamma +SoftThreshold(x, gamma)[i] = { 0, x[i] == gamma + { x[i] + gamma, x[i] < -gamma +``` + +In the context of proximal gradient methods, we have + +```none +SoftThreshold(x, gamma) = prox_{gamma L1}(x) +``` + +where `prox` is the proximity operator. Thus the soft thresholding operator +is used in proximal gradient descent for optimizing a smooth function with +(non-smooth) L1 regularization, as outlined below. + +The proximity operator is defined as: + +```none +prox_r(x) = argmin{ r(z) + 0.5 ||x - z||_2**2 : z }, +``` + +where `r` is a (weakly) convex function, not necessarily differentiable. +Because the L2 norm is strictly convex, the above argmin is unique. + +One important application of the proximity operator is as follows. Let `L` be +a convex and differentiable function with Lipschitz-continuous gradient. Let +`R` be a convex lower semicontinuous function which is possibly +nondifferentiable. Let `gamma` be an arbitrary positive real. Then + +```none +x_star = argmin{ L(x) + R(x) : x } +``` + +if and only if the fixed-point equation is satisfied: + +```none +x_star = prox_{gamma R}(x_star - gamma grad L(x_star)) +``` + +Proximal gradient descent thus typically consists of choosing an initial value +`x^{(0)}` and repeatedly applying the update + +```none +x^{(k+1)} = prox_{gamma^{(k)} R}(x^{(k)} - gamma^{(k)} grad L(x^{(k)})) +``` + +where `gamma` is allowed to vary from iteration to iteration. Specializing to +the case where `R(x) = ||x||_1`, we minimize `L(x) + ||x||_1` by repeatedly +applying the update + +``` +x^{(k+1)} = SoftThreshold(x - gamma grad L(x^{(k)}), gamma) +``` + +(This idea can also be extended to second-order approximations, although the +multivariate case does not have a known closed form like above.) + +#### Args: + +* `x`: `float` `Tensor` representing the input to the SoftThreshold function. +* `threshold`: nonnegative scalar, `float` `Tensor` representing the radius of + the interval on which each coordinate of SoftThreshold takes the value + zero. Denoted `gamma` above. +* `name`: Python string indicating the name of the TensorFlow operation. + Default name is `"soft_threshold"`. + + +#### Returns: + +* `softthreshold`: `float` `Tensor` with the same shape and dtype as `x`, + representing the value of the SoftThreshold function. + +#### References + +[1]: Yu, Yao-Liang. The Proximity Operator. + https://www.cs.cmu.edu/~suvrit/teach/yaoliang_proximity.pdf + +[2]: Wikipedia Contributors. Proximal gradient methods for learning. + _Wikipedia, The Free Encyclopedia_, 2018. + https://en.wikipedia.org/wiki/Proximal_gradient_methods_for_learning \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers.md index 6acc9f311e..eb28e60c00 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers.md @@ -1,5 +1,6 @@
+
# Module: tfp.layers diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DFlipout.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DFlipout.md index ac9e2e81c4..c4b9b5361c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DFlipout.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DFlipout.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -74,25 +68,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - filters: Python integer, dimensionality of the output space. - kernel_size: Size of the convolution window. - strides: Stride length of convolution. - padding: Python string describing padding approach. - data_format: Python string describing input data's dimensions. - dilation_rate: Dilation rate for an atrous convolution. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - seed: Python integer, used to create random seeds. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -133,6 +108,93 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2018. https://arxiv.org/abs/1803.04386 +

__init__

+ +``` python +__init__( + filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + activation=None, + activity_regularizer=None, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + seed=None, + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `filters`: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). +* `kernel_size`: An integer or tuple/list of a single integer, specifying the + length of the 1D convolution window. +* `strides`: An integer or tuple/list of a single integer, + specifying the stride length of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. +* `padding`: One of `"valid"` or `"same"` (case-insensitive). +* `data_format`: A string, one of `channels_last` (default) or + `channels_first`. The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape `(batch, length, + channels)` while `channels_first` corresponds to inputs with shape + `(batch, channels, length)`. +* `dilation_rate`: An integer or tuple/list of a single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. +* `activation`: Activation function. Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `seed`: Python scalar `int` which initializes the random number + generator. Default value: `None` (i.e., use global seed). + + + ## Properties

activity_regularizer

@@ -143,10 +205,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -231,10 +289,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -321,91 +375,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - filters, - kernel_size, - strides=1, - padding='valid', - data_format='channels_last', - dilation_rate=1, - activation=None, - activity_regularizer=None, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - seed=None, - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `filters`: Integer, the dimensionality of the output space (i.e. the number - of filters in the convolution). -* `kernel_size`: An integer or tuple/list of a single integer, specifying the - length of the 1D convolution window. -* `strides`: An integer or tuple/list of a single integer, - specifying the stride length of the convolution. - Specifying any stride value != 1 is incompatible with specifying - any `dilation_rate` value != 1. -* `padding`: One of `"valid"` or `"same"` (case-insensitive). -* `data_format`: A string, one of `channels_last` (default) or - `channels_first`. The ordering of the dimensions in the inputs. - `channels_last` corresponds to inputs with shape `(batch, length, - channels)` while `channels_first` corresponds to inputs with shape - `(batch, channels, length)`. -* `dilation_rate`: An integer or tuple/list of a single integer, specifying - the dilation rate to use for dilated convolution. - Currently, specifying any `dilation_rate` value != 1 is - incompatible with specifying any `strides` value != 1. -* `activation`: Activation function. Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `seed`: Python scalar `int` which initializes the random number - generator. Default value: `None` (i.e., use global seed). -

__call__

``` python @@ -445,159 +414,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -631,14 +447,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DReparameterization.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DReparameterization.md index 0b3c273f62..9ed2973ab9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DReparameterization.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution1DReparameterization.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -72,24 +66,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - filters: Python integer, dimensionality of the output space. - kernel_size: Size of the convolution window. - strides: Stride length of convolution. - padding: Python string describing padding approach. - data_format: Python string describing input data's dimensions. - dilation_rate: Dilation rate for an atrous convolution. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -129,6 +105,90 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2014. https://arxiv.org/abs/1312.6114 +

__init__

+ +``` python +__init__( + filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + activation=None, + activity_regularizer=None, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `filters`: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). +* `kernel_size`: An integer or tuple/list of a single integer, specifying the + length of the 1D convolution window. +* `strides`: An integer or tuple/list of a single integer, + specifying the stride length of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. +* `padding`: One of `"valid"` or `"same"` (case-insensitive). +* `data_format`: A string, one of `channels_last` (default) or + `channels_first`. The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape `(batch, length, + channels)` while `channels_first` corresponds to inputs with shape + `(batch, channels, length)`. +* `dilation_rate`: An integer or tuple/list of a single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. +* `activation`: Activation function. Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. + + + ## Properties

activity_regularizer

@@ -139,10 +199,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -227,10 +283,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -317,88 +369,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - filters, - kernel_size, - strides=1, - padding='valid', - data_format='channels_last', - dilation_rate=1, - activation=None, - activity_regularizer=None, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `filters`: Integer, the dimensionality of the output space (i.e. the number - of filters in the convolution). -* `kernel_size`: An integer or tuple/list of a single integer, specifying the - length of the 1D convolution window. -* `strides`: An integer or tuple/list of a single integer, - specifying the stride length of the convolution. - Specifying any stride value != 1 is incompatible with specifying - any `dilation_rate` value != 1. -* `padding`: One of `"valid"` or `"same"` (case-insensitive). -* `data_format`: A string, one of `channels_last` (default) or - `channels_first`. The ordering of the dimensions in the inputs. - `channels_last` corresponds to inputs with shape `(batch, length, - channels)` while `channels_first` corresponds to inputs with shape - `(batch, channels, length)`. -* `dilation_rate`: An integer or tuple/list of a single integer, specifying - the dilation rate to use for dilated convolution. - Currently, specifying any `dilation_rate` value != 1 is - incompatible with specifying any `strides` value != 1. -* `activation`: Activation function. Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -

__call__

``` python @@ -438,159 +408,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -624,14 +441,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DFlipout.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DFlipout.md index 5eba12db4e..6839784612 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DFlipout.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DFlipout.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -74,25 +68,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - filters: Python integer, dimensionality of the output space. - kernel_size: Size of the convolution window. - strides: Stride length of convolution. - padding: Python string describing padding approach. - data_format: Python string describing input data's dimensions. - dilation_rate: Dilation rate for an atrous convolution. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - seed: Python integer, used to create random seeds. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -136,6 +111,99 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2018. https://arxiv.org/abs/1803.04386 +

__init__

+ +``` python +__init__( + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1), + activation=None, + activity_regularizer=None, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + seed=None, + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `filters`: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). +* `kernel_size`: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. +* `strides`: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. +* `padding`: One of `"valid"` or `"same"` (case-insensitive). +* `data_format`: A string, one of `channels_last` (default) or + `channels_first`. The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape `(batch, height, + width, channels)` while `channels_first` corresponds to inputs with + shape `(batch, channels, height, width)`. +* `dilation_rate`: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. +* `activation`: Activation function. Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `seed`: Python scalar `int` which initializes the random number + generator. Default value: `None` (i.e., use global seed). + + + ## Properties

activity_regularizer

@@ -146,10 +214,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -234,10 +298,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -324,97 +384,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - filters, - kernel_size, - strides=(1, 1), - padding='valid', - data_format='channels_last', - dilation_rate=(1, 1), - activation=None, - activity_regularizer=None, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - seed=None, - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `filters`: Integer, the dimensionality of the output space (i.e. the number - of filters in the convolution). -* `kernel_size`: An integer or tuple/list of 2 integers, specifying the - height and width of the 2D convolution window. - Can be a single integer to specify the same value for - all spatial dimensions. -* `strides`: An integer or tuple/list of 2 integers, - specifying the strides of the convolution along the height and width. - Can be a single integer to specify the same value for - all spatial dimensions. - Specifying any stride value != 1 is incompatible with specifying - any `dilation_rate` value != 1. -* `padding`: One of `"valid"` or `"same"` (case-insensitive). -* `data_format`: A string, one of `channels_last` (default) or - `channels_first`. The ordering of the dimensions in the inputs. - `channels_last` corresponds to inputs with shape `(batch, height, - width, channels)` while `channels_first` corresponds to inputs with - shape `(batch, channels, height, width)`. -* `dilation_rate`: An integer or tuple/list of 2 integers, specifying - the dilation rate to use for dilated convolution. - Can be a single integer to specify the same value for - all spatial dimensions. - Currently, specifying any `dilation_rate` value != 1 is - incompatible with specifying any stride value != 1. -* `activation`: Activation function. Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `seed`: Python scalar `int` which initializes the random number - generator. Default value: `None` (i.e., use global seed). -

__call__

``` python @@ -454,159 +423,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -640,14 +456,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DReparameterization.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DReparameterization.md index af1d182a6f..5bd79be73b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DReparameterization.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution2DReparameterization.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -72,24 +66,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - filters: Python integer, dimensionality of the output space. - kernel_size: Size of the convolution window. - strides: Stride length of convolution. - padding: Python string describing padding approach. - data_format: Python string describing input data's dimensions. - dilation_rate: Dilation rate for an atrous convolution. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -132,6 +108,96 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2014. https://arxiv.org/abs/1312.6114 +

__init__

+ +``` python +__init__( + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1), + activation=None, + activity_regularizer=None, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `filters`: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). +* `kernel_size`: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. +* `strides`: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. +* `padding`: One of `"valid"` or `"same"` (case-insensitive). +* `data_format`: A string, one of `channels_last` (default) or + `channels_first`. The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape `(batch, height, + width, channels)` while `channels_first` corresponds to inputs with + shape `(batch, channels, height, width)`. +* `dilation_rate`: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. +* `activation`: Activation function. Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. + + + ## Properties

activity_regularizer

@@ -142,10 +208,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -230,10 +292,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -320,94 +378,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - filters, - kernel_size, - strides=(1, 1), - padding='valid', - data_format='channels_last', - dilation_rate=(1, 1), - activation=None, - activity_regularizer=None, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `filters`: Integer, the dimensionality of the output space (i.e. the number - of filters in the convolution). -* `kernel_size`: An integer or tuple/list of 2 integers, specifying the - height and width of the 2D convolution window. - Can be a single integer to specify the same value for - all spatial dimensions. -* `strides`: An integer or tuple/list of 2 integers, - specifying the strides of the convolution along the height and width. - Can be a single integer to specify the same value for - all spatial dimensions. - Specifying any stride value != 1 is incompatible with specifying - any `dilation_rate` value != 1. -* `padding`: One of `"valid"` or `"same"` (case-insensitive). -* `data_format`: A string, one of `channels_last` (default) or - `channels_first`. The ordering of the dimensions in the inputs. - `channels_last` corresponds to inputs with shape `(batch, height, - width, channels)` while `channels_first` corresponds to inputs with - shape `(batch, channels, height, width)`. -* `dilation_rate`: An integer or tuple/list of 2 integers, specifying - the dilation rate to use for dilated convolution. - Can be a single integer to specify the same value for - all spatial dimensions. - Currently, specifying any `dilation_rate` value != 1 is - incompatible with specifying any stride value != 1. -* `activation`: Activation function. Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -

__call__

``` python @@ -447,159 +417,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -633,14 +450,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DFlipout.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DFlipout.md index 90445ccc61..b96481e473 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DFlipout.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DFlipout.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -74,25 +68,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - filters: Python integer, dimensionality of the output space. - kernel_size: Size of the convolution window. - strides: Stride length of convolution. - padding: Python string describing padding approach. - data_format: Python string describing input data's dimensions. - dilation_rate: Dilation rate for an atrous convolution. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - seed: Python integer, used to create random seeds. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -136,6 +111,100 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2018. https://arxiv.org/abs/1803.04386 +

__init__

+ +``` python +__init__( + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1, 1), + activation=None, + activity_regularizer=None, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + seed=None, + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `filters`: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). +* `kernel_size`: An integer or tuple/list of 3 integers, specifying the + depth, height and width of the 3D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. +* `strides`: An integer or tuple/list of 3 integers, + specifying the strides of the convolution along the depth, + height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. +* `padding`: One of `"valid"` or `"same"` (case-insensitive). +* `data_format`: A string, one of `channels_last` (default) or + `channels_first`. The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape `(batch, depth, + height, width, channels)` while `channels_first` corresponds to inputs + with shape `(batch, channels, depth, height, width)`. +* `dilation_rate`: An integer or tuple/list of 3 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. +* `activation`: Activation function. Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `seed`: Python scalar `int` which initializes the random number + generator. Default value: `None` (i.e., use global seed). + + + ## Properties

activity_regularizer

@@ -146,10 +215,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -234,10 +299,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -324,98 +385,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - filters, - kernel_size, - strides=(1, 1, 1), - padding='valid', - data_format='channels_last', - dilation_rate=(1, 1, 1), - activation=None, - activity_regularizer=None, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - seed=None, - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `filters`: Integer, the dimensionality of the output space (i.e. the number - of filters in the convolution). -* `kernel_size`: An integer or tuple/list of 3 integers, specifying the - depth, height and width of the 3D convolution window. - Can be a single integer to specify the same value for - all spatial dimensions. -* `strides`: An integer or tuple/list of 3 integers, - specifying the strides of the convolution along the depth, - height and width. - Can be a single integer to specify the same value for - all spatial dimensions. - Specifying any stride value != 1 is incompatible with specifying - any `dilation_rate` value != 1. -* `padding`: One of `"valid"` or `"same"` (case-insensitive). -* `data_format`: A string, one of `channels_last` (default) or - `channels_first`. The ordering of the dimensions in the inputs. - `channels_last` corresponds to inputs with shape `(batch, depth, - height, width, channels)` while `channels_first` corresponds to inputs - with shape `(batch, channels, depth, height, width)`. -* `dilation_rate`: An integer or tuple/list of 3 integers, specifying - the dilation rate to use for dilated convolution. - Can be a single integer to specify the same value for - all spatial dimensions. - Currently, specifying any `dilation_rate` value != 1 is - incompatible with specifying any stride value != 1. -* `activation`: Activation function. Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `seed`: Python scalar `int` which initializes the random number - generator. Default value: `None` (i.e., use global seed). -

__call__

``` python @@ -455,159 +424,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -641,14 +457,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DReparameterization.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DReparameterization.md index c2b900cbc7..de4b535e97 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DReparameterization.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/Convolution3DReparameterization.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -72,24 +66,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - filters: Python integer, dimensionality of the output space. - kernel_size: Size of the convolution window. - strides: Stride length of convolution. - padding: Python string describing padding approach. - data_format: Python string describing input data's dimensions. - dilation_rate: Dilation rate for an atrous convolution. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -132,6 +108,97 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2014. https://arxiv.org/abs/1312.6114 +

__init__

+ +``` python +__init__( + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1, 1), + activation=None, + activity_regularizer=None, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `filters`: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). +* `kernel_size`: An integer or tuple/list of 3 integers, specifying the + depth, height and width of the 3D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. +* `strides`: An integer or tuple/list of 3 integers, + specifying the strides of the convolution along the depth, + height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. +* `padding`: One of `"valid"` or `"same"` (case-insensitive). +* `data_format`: A string, one of `channels_last` (default) or + `channels_first`. The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape `(batch, depth, + height, width, channels)` while `channels_first` corresponds to inputs + with shape `(batch, channels, depth, height, width)`. +* `dilation_rate`: An integer or tuple/list of 3 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. +* `activation`: Activation function. Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. + + + ## Properties

activity_regularizer

@@ -142,10 +209,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -230,10 +293,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -320,95 +379,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - filters, - kernel_size, - strides=(1, 1, 1), - padding='valid', - data_format='channels_last', - dilation_rate=(1, 1, 1), - activation=None, - activity_regularizer=None, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `filters`: Integer, the dimensionality of the output space (i.e. the number - of filters in the convolution). -* `kernel_size`: An integer or tuple/list of 3 integers, specifying the - depth, height and width of the 3D convolution window. - Can be a single integer to specify the same value for - all spatial dimensions. -* `strides`: An integer or tuple/list of 3 integers, - specifying the strides of the convolution along the depth, - height and width. - Can be a single integer to specify the same value for - all spatial dimensions. - Specifying any stride value != 1 is incompatible with specifying - any `dilation_rate` value != 1. -* `padding`: One of `"valid"` or `"same"` (case-insensitive). -* `data_format`: A string, one of `channels_last` (default) or - `channels_first`. The ordering of the dimensions in the inputs. - `channels_last` corresponds to inputs with shape `(batch, depth, - height, width, channels)` while `channels_first` corresponds to inputs - with shape `(batch, channels, depth, height, width)`. -* `dilation_rate`: An integer or tuple/list of 3 integers, specifying - the dilation rate to use for dilated convolution. - Can be a single integer to specify the same value for - all spatial dimensions. - Currently, specifying any `dilation_rate` value != 1 is - incompatible with specifying any stride value != 1. -* `activation`: Activation function. Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -

__call__

``` python @@ -448,159 +418,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -634,14 +451,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseFlipout.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseFlipout.md index d5d1d437a4..348632674d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseFlipout.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseFlipout.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -73,20 +67,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - units: Python integer, dimensionality of the output space. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - seed: Python integer, used to create random seeds. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -123,6 +103,72 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2018. https://arxiv.org/abs/1803.04386 +

__init__

+ +``` python +__init__( + units, + activation=None, + activity_regularizer=None, + trainable=True, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + seed=None, + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `units`: Integer or Long, dimensionality of the output space. +* `activation`: Activation function (`callable`). Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `seed`: Python scalar `int` which initializes the random number + generator. Default value: `None` (i.e., use global seed). + + + ## Properties

activity_regularizer

@@ -133,10 +179,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -221,10 +263,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -311,70 +349,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - units, - activation=None, - activity_regularizer=None, - trainable=True, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - seed=None, - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `units`: Integer or Long, dimensionality of the output space. -* `activation`: Activation function (`callable`). Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `seed`: Python scalar `int` which initializes the random number - generator. Default value: `None` (i.e., use global seed). -

__call__

``` python @@ -414,159 +388,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -600,14 +421,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseLocalReparameterization.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseLocalReparameterization.md index d8218ad1b2..3a5b889fa5 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseLocalReparameterization.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseLocalReparameterization.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -65,25 +59,16 @@ outputs = activation(matmul(inputs, kernel) + bias) It uses the local reparameterization estimator [(Kingma et al., 2015)][1], which performs a Monte Carlo approximation of the distribution on the hidden -units induced by the `kernel` and `bias`. +units induced by the `kernel` and `bias`. The default `kernel_posterior_fn` +is a normal distribution which factorizes across all elements of the weight +matrix and bias vector. Unlike [1]'s multiplicative parameterization, this +distribution has trainable location and scale parameters which is known as +an additive noise parameterization [(Molchanov et al., 2017)][2]. The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - units: Python integer, dimensionality of the output space. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -118,6 +103,72 @@ terms which are arguments to the layer. [1]: Diederik Kingma, Tim Salimans, and Max Welling. Variational Dropout and the Local Reparameterization Trick. In _Neural Information Processing Systems_, 2015. https://arxiv.org/abs/1506.02557 +[2]: Dmitry Molchanov, Arsenii Ashukha, Dmitry Vetrov. Variational Dropout + Sparsifies Deep Neural Networks. In _International Conference on Machine + Learning_, 2017. https://arxiv.org/abs/1701.05369 + +

__init__

+ +``` python +__init__( + units, + activation=None, + activity_regularizer=None, + trainable=True, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `units`: Integer or Long, dimensionality of the output space. +* `activation`: Activation function (`callable`). Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. + + ## Properties @@ -129,10 +180,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -217,10 +264,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -307,67 +350,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - units, - activation=None, - activity_regularizer=None, - trainable=True, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `units`: Integer or Long, dimensionality of the output space. -* `activation`: Activation function (`callable`). Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -

__call__

``` python @@ -407,159 +389,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -593,14 +422,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseReparameterization.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseReparameterization.md index be39d0a937..bcb24f068d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseReparameterization.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/DenseReparameterization.md @@ -1,8 +1,8 @@
+ - @@ -10,7 +10,6 @@ - @@ -21,13 +20,8 @@ - - - - - @@ -71,19 +65,6 @@ The arguments permit separate specification of the surrogate posterior (`q(W|x)`), prior (`p(W)`), and divergence for both the `kernel` and `bias` distributions. -Properties: - units: Python integer, dimensionality of the output space. - activation: Activation function (`callable`). - activity_regularizer: Regularizer function for the output. - kernel_posterior_fn: `callable` returning posterior. - kernel_posterior_tensor_fn: `callable` operating on posterior. - kernel_prior_fn: `callable` returning prior. - kernel_divergence_fn: `callable` returning divergence. - bias_posterior_fn: `callable` returning posterior. - bias_posterior_tensor_fn: `callable` operating on posterior. - bias_prior_fn: `callable` returning prior. - bias_divergence_fn: `callable` returning divergence. - #### Examples We illustrate a Bayesian neural network with [variational inference]( @@ -120,6 +101,69 @@ terms which are arguments to the layer. _International Conference on Learning Representations_, 2014. https://arxiv.org/abs/1312.6114 +

__init__

+ +``` python +__init__( + units, + activation=None, + activity_regularizer=None, + trainable=True, + kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), + kernel_posterior_tensor_fn=(lambda d: d.sample()), + kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, + kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), + bias_posterior_tensor_fn=(lambda d: d.sample()), + bias_prior_fn=None, + bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), + **kwargs +) +``` + +Construct layer. + +#### Args: + +* `units`: Integer or Long, dimensionality of the output space. +* `activation`: Activation function (`callable`). Set it to None to maintain a + linear activation. +* `activity_regularizer`: Regularizer function for the output. +* `kernel_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `kernel` parameter. Default value: + `default_mean_field_normal_fn()`. +* `kernel_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` + instance. See `default_mean_field_normal_fn` docstring for required + parameter signature. + Default value: `tf.distributions.Normal(loc=0., scale=1.)`. +* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. +* `bias_posterior_fn`: Python `callable` which creates + `tf.distributions.Distribution` instance representing the surrogate + posterior of the `bias` parameter. Default value: + `default_mean_field_normal_fn(is_singular=True)` (which creates an + instance of `tf.distributions.Deterministic`). +* `bias_posterior_tensor_fn`: Python `callable` which takes a + `tf.distributions.Distribution` instance and returns a representative + value. Default value: `lambda d: d.sample()`. +* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. + See `default_mean_field_normal_fn` docstring for required parameter + signature. Default value: `None` (no prior, no variational inference) +* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior + distribution, prior distribution and random variate sample(s) from the + surrogate posterior and computes or approximates the KL divergence. The + distributions are `tf.distributions.Distribution`-like instances and the + sample is a `Tensor`. + + + ## Properties

activity_regularizer

@@ -130,10 +174,6 @@ Optional regularizer function for the output of this layer. -

inbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

input

Retrieves the input tensor(s) of a layer. @@ -218,10 +258,6 @@ A list of tensors. -

outbound_nodes

- -Deprecated, do NOT use! Only for compatibility with external Keras. -

output

Retrieves the output tensor(s) of a layer. @@ -308,67 +344,6 @@ A list of variables. ## Methods -

__init__

- -``` python -__init__( - units, - activation=None, - activity_regularizer=None, - trainable=True, - kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(), - kernel_posterior_tensor_fn=(lambda d: d.sample()), - kernel_prior_fn=tfp.layers.default_multivariate_normal_fn, - kernel_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - bias_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(is_singular=True), - bias_posterior_tensor_fn=(lambda d: d.sample()), - bias_prior_fn=None, - bias_divergence_fn=(lambda q, p, ignore: tfd.kl_divergence(q, p)), - **kwargs -) -``` - -Construct layer. - -#### Args: - -* `units`: Integer or Long, dimensionality of the output space. -* `activation`: Activation function (`callable`). Set it to None to maintain a - linear activation. -* `activity_regularizer`: Regularizer function for the output. -* `kernel_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `kernel` parameter. Default value: - `default_mean_field_normal_fn()`. -* `kernel_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `kernel_prior_fn`: Python `callable` which creates `tf.distributions` - instance. See `default_mean_field_normal_fn` docstring for required - parameter signature. - Default value: `tf.distributions.Normal(loc=0., scale=1.)`. -* `kernel_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -* `bias_posterior_fn`: Python `callable` which creates - `tf.distributions.Distribution` instance representing the surrogate - posterior of the `bias` parameter. Default value: - `default_mean_field_normal_fn(is_singular=True)` (which creates an - instance of `tf.distributions.Deterministic`). -* `bias_posterior_tensor_fn`: Python `callable` which takes a - `tf.distributions.Distribution` instance and returns a representative - value. Default value: `lambda d: d.sample()`. -* `bias_prior_fn`: Python `callable` which creates `tf.distributions` instance. - See `default_mean_field_normal_fn` docstring for required parameter - signature. Default value: `None` (no prior, no variational inference) -* `bias_divergence_fn`: Python `callable` which takes the surrogate posterior - distribution, prior distribution and random variate sample(s) from the - surrogate posterior and computes or approximates the KL divergence. The - distributions are `tf.distributions.Distribution`-like instances and the - sample is a `Tensor`. -

__call__

``` python @@ -408,159 +383,6 @@ Note: * `ValueError`: if the layer's `call` method returns None (an invalid value). -

add_loss

- -``` python -add_loss( - losses, - inputs=None -) -``` - -Add loss tensor(s), potentially dependent on layer inputs. - -Some losses (for instance, activity regularization losses) may be dependent -on the inputs passed when calling a layer. Hence, when reusing the same -layer on different inputs `a` and `b`, some entries in `layer.losses` may -be dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_losses_for` method allows to retrieve the losses relevant to a -specific set of inputs. - -Note that `add_loss` is not supported when executing eagerly. Instead, -variable regularizers may be added through `add_variable`. Activity -regularization is not supported directly (but such losses may be returned -from `Layer.call()`). - -#### Arguments: - -* `losses`: Loss tensor, or list/tuple of tensors. -* `inputs`: If anything other than None is passed, it signals the losses - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for activity regularization losses, for instance. - If `None` is passed, the losses are assumed - to be unconditional, and will apply across all dataflows of the layer - (e.g. weight regularization losses). - - -#### Raises: - -* `RuntimeError`: If called in Eager mode. - -

add_update

- -``` python -add_update( - updates, - inputs=None -) -``` - -Add update op(s), potentially dependent on layer inputs. - -Weight updates (for instance, the updates of the moving mean and variance -in a BatchNormalization layer) may be dependent on the inputs passed -when calling a layer. Hence, when reusing the same layer on -different inputs `a` and `b`, some entries in `layer.updates` may be -dependent on `a` and some on `b`. This method automatically keeps track -of dependencies. - -The `get_updates_for` method allows to retrieve the updates relevant to a -specific set of inputs. - -This call is ignored when eager execution is enabled (in that case, variable -updates are run on the fly and thus do not need to be tracked for later -execution). - -#### Arguments: - -* `updates`: Update op, or list/tuple of update ops. -* `inputs`: If anything other than None is passed, it signals the updates - are conditional on some of the layer's inputs, - and thus they should only be run where these inputs are available. - This is the case for BatchNormalization updates, for instance. - If None, the updates will be taken into account unconditionally, - and you are responsible for making sure that any dependency they might - have is available at runtime. - A step counter might fall into this category. - -

add_variable

- -``` python -add_variable( - *args, - **kwargs -) -``` - -Alias for `add_weight`. - -

add_weight

- -``` python -add_weight( - name, - shape, - dtype=None, - initializer=None, - regularizer=None, - trainable=None, - constraint=None, - partitioner=None, - use_resource=None, - synchronization=vs.VariableSynchronization.AUTO, - aggregation=vs.VariableAggregation.NONE, - getter=None -) -``` - -Adds a new variable to the layer, or gets an existing one; returns it. - -#### Arguments: - -* `name`: variable name. -* `shape`: variable shape. -* `dtype`: The type of the variable. Defaults to `self.dtype` or `float32`. -* `initializer`: initializer instance (callable). -* `regularizer`: regularizer instance (callable). -* `trainable`: whether the variable should be part of the layer's - "trainable_variables" (e.g. variables, biases) - or "non_trainable_variables" (e.g. BatchNorm mean, stddev). - Note, if the current variable scope is marked as non-trainable - then this parameter is ignored and any added variables are also - marked as non-trainable. `trainable` defaults to `True` unless - `synchronization` is set to `ON_READ`. -* `constraint`: constraint instance (callable). -* `partitioner`: Partitioner to be passed to the `Checkpointable` API. -* `use_resource`: Whether to use `ResourceVariable`. -* `synchronization`: Indicates when a distributed a variable will be - aggregated. Accepted values are constants defined in the class - `tf.VariableSynchronization`. By default the synchronization is set to - `AUTO` and the current `DistributionStrategy` chooses - when to synchronize. If `synchronization` is set to `ON_READ`, - `trainable` must not be set to `True`. -* `aggregation`: Indicates how a distributed variable will be aggregated. - Accepted values are constants defined in the class - `tf.VariableAggregation`. -* `getter`: Variable getter argument to be passed to the `Checkpointable` API. - - -#### Returns: - -The created variable. Usually either a `Variable` or `ResourceVariable` -instance. If `partitioner` is not `None`, a `PartitionedVariable` -instance is returned. - - -#### Raises: - -* `RuntimeError`: If called with partioned variable regularization and - eager execution is enabled. -* `ValueError`: When giving unsupported dtype and no initializer or when - trainable has been set to True with synchronization set as `ON_READ`. -

apply

``` python @@ -594,14 +416,6 @@ build(input_shape) -

call

- -``` python -call(inputs) -``` - - -

compute_mask

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_loc_scale_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_loc_scale_fn.md index a1b3a171e8..29ca290866 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_loc_scale_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_loc_scale_fn.md @@ -1,5 +1,6 @@
+
# tfp.layers.default_loc_scale_fn diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_mean_field_normal_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_mean_field_normal_fn.md index e01ad0bef7..5c25ea43ed 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_mean_field_normal_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_mean_field_normal_fn.md @@ -1,5 +1,6 @@
+
# tfp.layers.default_mean_field_normal_fn diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_multivariate_normal_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_multivariate_normal_fn.md index 36b0ee25aa..37ef519fbd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_multivariate_normal_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/layers/default_multivariate_normal_fn.md @@ -1,5 +1,6 @@
+
# tfp.layers.default_multivariate_normal_fn diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math.md index 4d122b3d46..9a55d04cda 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/math.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math.md @@ -1,5 +1,6 @@
+
# Module: tfp.math @@ -8,6 +9,8 @@ TensorFlow Probability math functions. ## Functions +[`custom_gradient(...)`](../tfp/math/custom_gradient.md): Embeds a custom gradient into a `Tensor`. + [`diag_jacobian(...)`](../tfp/math/diag_jacobian.md): Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`. [`matvecmul(...)`](../tfp/math/matvecmul.md): Multiply a matrix by a vector. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math/custom_gradient.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math/custom_gradient.md new file mode 100644 index 0000000000..9a0b9c2948 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math/custom_gradient.md @@ -0,0 +1,54 @@ +
+ + +
+ +# tfp.math.custom_gradient + +``` python +tfp.math.custom_gradient( + fx, + gx, + x, + fx_gx_manually_stopped=False, + name=None +) +``` + +Embeds a custom gradient into a `Tensor`. + +This function works by clever application of `stop_gradient`. I.e., observe +that: + +```none +h(x) = stop_gradient(f(x)) + stop_gradient(g(x)) * (x - stop_gradient(x)) +``` + +is such that `h(x) == stop_gradient(f(x))` and +`grad[h(x), x] == stop_gradient(g(x)).` + +In addition to scalar-domain/scalar-range functions, this function also +supports tensor-domain/scalar-range functions. + +Partial Custom Gradient: + +Suppose `h(x) = htilde(x, y)`. Note that `dh/dx = stop(g(x))` but `dh/dy = +None`. This is because a `Tensor` cannot have only a portion of its gradient +stopped. To circumvent this issue, one must manually `stop_gradient` the +relevant portions of `f`, `g`. For example see the unit-test, +`test_works_correctly_fx_gx_manually_stopped`. + +#### Args: + +* `fx`: `Tensor`. Output of function evaluated at `x`. +* `gx`: `Tensor` or list of `Tensor`s. Gradient of function at (each) `x`. +* `x`: `Tensor` or list of `Tensor`s. Args of evaluation for `f`. +* `fx_gx_manually_stopped`: Python `bool` indicating that `fx`, `gx` manually + have `stop_gradient` applied. +* `name`: Python `str` name prefixed to Ops created by this function. + + +#### Returns: + +* `fx`: Floating-type `Tensor` equal to `f(x)` but which has gradient + `stop_gradient(g(x))`. \ No newline at end of file diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math/diag_jacobian.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math/diag_jacobian.md index 42cf33b637..cc1aa59887 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/math/diag_jacobian.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math/diag_jacobian.md @@ -1,5 +1,6 @@
+
# tfp.math.diag_jacobian diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math/matvecmul.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math/matvecmul.md index bd62f06fa9..bc12187334 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/math/matvecmul.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math/matvecmul.md @@ -1,5 +1,6 @@
+
# tfp.math.matvecmul diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math/pinv.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math/pinv.md index 08604f9ebb..ff06836d6e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/math/pinv.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math/pinv.md @@ -1,5 +1,6 @@
+
# tfp.math.pinv diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rademacher.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rademacher.md index 11dfec0a1c..701ed283dd 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rademacher.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rademacher.md @@ -1,5 +1,6 @@
+
# tfp.math.random_rademacher diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rayleigh.md b/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rayleigh.md index 5a5ea0c78a..c39685f040 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rayleigh.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/math/random_rayleigh.md @@ -1,5 +1,6 @@
+
# tfp.math.random_rayleigh diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc.md index f60029ef07..6cb8a1e835 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc.md @@ -1,5 +1,6 @@
+
# Module: tfp.mcmc diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/HamiltonianMonteCarlo.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/HamiltonianMonteCarlo.md index 90eade2859..ba0933d607 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/HamiltonianMonteCarlo.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/HamiltonianMonteCarlo.md @@ -1,5 +1,6 @@
+ @@ -246,49 +247,7 @@ plt.xlabel('iteration') stochastic approximation version of the EM algorithm_, Ann. Statist. 27 (1999), no. 1, 94--128. https://projecteuclid.org/euclid.aos/1018031103 -## Properties - -

is_calibrated

- - - -

name

- - - -

num_leapfrog_steps

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

state_gradients_are_stopped

- - - -

step_size

- - - -

step_size_update_fn

- - - -

target_log_prob_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -331,19 +290,48 @@ Initializes this transition kernel. Default value: `None` (i.e., 'hmc_kernel'). -#### Returns: -* `next_state`: Tensor or Python list of `Tensor`s representing the state(s) - of the Markov chain(s) at each result step. Has same shape as - `current_state`. -* `kernel_results`: `collections.namedtuple` of internal calculations used to - advance the chain. +## Properties +

is_calibrated

-#### Raises: -* `ValueError`: if there isn't one `step_size` or a list with same length as - `current_state`. + +

name

+ + + +

num_leapfrog_steps

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

state_gradients_are_stopped

+ + + +

step_size

+ + + +

step_size_update_fn

+ + + +

target_log_prob_fn

+ + + + + +## Methods

bootstrap_results

diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisAdjustedLangevinAlgorithm.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisAdjustedLangevinAlgorithm.md index d15e84ea80..5ba293a162 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisAdjustedLangevinAlgorithm.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisAdjustedLangevinAlgorithm.md @@ -1,5 +1,6 @@
+ @@ -208,45 +209,7 @@ print('sample covariance matrix', sample_cov_) Langevin algorithm. _arXiv preprint arXiv:1309.2983_, 2013. https://arxiv.org/abs/1309.2983 -## Properties - -

is_calibrated

- - - -

name

- - - -

parallel_iterations

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

step_size

- - - -

target_log_prob_fn

- - - -

volatility_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -300,6 +263,46 @@ Initializes MALA transition kernel. `current_state`. * `TypeError`: if `volatility_fn` is not callable. + + +## Properties + +

is_calibrated

+ + + +

name

+ + + +

parallel_iterations

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

step_size

+ + + +

target_log_prob_fn

+ + + +

volatility_fn

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisHastings.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisHastings.md index 40dbf3fb72..6ba91a01f8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisHastings.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/MetropolisHastings.md @@ -1,5 +1,6 @@
+ @@ -76,33 +77,7 @@ hmc = tfp.mcmc.MetropolisHastings( # num_leapfrog_steps=3) ``` -## Properties - -

inner_kernel

- - - -

is_calibrated

- - - -

name

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -130,6 +105,34 @@ Instantiates this object. * `metropolis_hastings_kernel`: Instance of `TransitionKernel` which wraps the input transition kernel with the Metropolis-Hastings algorithm. + + +## Properties + +

inner_kernel

+ + + +

is_calibrated

+ + + +

name

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/RandomWalkMetropolis.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/RandomWalkMetropolis.md index 0e3ba5bed9..98fdaef61a 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/RandomWalkMetropolis.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/RandomWalkMetropolis.md @@ -1,5 +1,6 @@
+ @@ -150,7 +151,6 @@ print('Estimated covariance of covariance: {}'.format(cov_sample_cov_)) import numpy as np import tensorflow as tf import tensorflow_probability as tfp -from tensorflow.python.ops.distributions import util as distributions_util tfd = tfp.distributions @@ -162,12 +162,10 @@ def cauchy_new_state_fn(scale, dtype): cauchy = tfd.Cauchy(loc=dtype(0), scale=dtype(scale)) def _fn(state_parts, seed): next_state_parts = [] + seed_stream = tfd.SeedStream(seed, salt='RandomCauchy') for sp in state_parts: - # Mutate seed with each use. - seed = distributions_util.gen_new_seed( - seed, salt='random_walk_cauchy_new_state_fn') next_state_parts.append(sp + cauchy.sample( - sample_shape=sp.shape, seed=seed)) + sample_shape=sp.shape, seed=seed_stream())) return next_state_parts return _fn @@ -194,37 +192,7 @@ print('Estimated mean: {}'.format(sample_mean_)) print('Estimated standard deviation: {}'.format(sample_std_)) ``` -## Properties - -

is_calibrated

- - - -

name

- - - -

new_state_fn

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

target_log_prob_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -266,6 +234,38 @@ Initializes this transition kernel. * `ValueError`: if there isn't one `scale` or a list with same length as `current_state`. + + +## Properties + +

is_calibrated

+ + + +

name

+ + + +

new_state_fn

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

target_log_prob_fn

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/ReplicaExchangeMC.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/ReplicaExchangeMC.md index ab1d8c3e94..be67e3c3ea 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/ReplicaExchangeMC.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/ReplicaExchangeMC.md @@ -1,5 +1,6 @@
+ @@ -134,45 +135,7 @@ plt.plot(samples_[:, 0], samples_[:, 1], '.') plt.show() ``` -## Properties - -

exchange_proposed_fn

- - - -

inverse_temperatures

- - - -

is_calibrated

- - - -

name

- - - -

num_replica

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

target_log_prob_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -212,6 +175,46 @@ Instantiates this object. * `ValueError`: `inverse_temperatures` doesn't have statically known 1D shape. + + +## Properties + +

exchange_proposed_fn

+ + + +

inverse_temperatures

+ + + +

is_calibrated

+ + + +

name

+ + + +

num_replica

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

target_log_prob_fn

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/SliceSampler.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/SliceSampler.md index f667b20114..b8d6d05967 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/SliceSampler.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/SliceSampler.md @@ -1,5 +1,6 @@
+ @@ -21,13 +22,13 @@ Inherits From: [`TransitionKernel`](../../tfp/mcmc/TransitionKernel.md) Runs one step of the slice sampler using a hit and run approach. Slice Sampling is a Markov Chain Monte Carlo (MCMC) algorithm based, as stated -by [Neal (2003)][1], on the observation that `...one can sample from a +by [Neal (2003)][1], on the observation that "...one can sample from a distribution by sampling uniformly from the region under the plot of its density function. A Markov chain that converges to this uniform distribution can be constructed by alternately uniform sampling in the vertical direction with uniform sampling from the horizontal `slice` defined by the current vertical position, or more generally, with some update that leaves the uniform -distribution over this slice invariant`. Mathematical details and derivations +distribution over this slice invariant". Mathematical details and derivations can be found in [Neal (2003)][1]. The one dimensional slice sampler is extended to n-dimensions through use of a hit-and-run approach: choose a random direction in n-dimensional space and take a step, as determined by the @@ -47,141 +48,120 @@ chains is `tf.size(target_log_prob_fn(*current_state))`.) Note that the sampler only supports states where all components have a common dtype. -#### Examples: +### Examples: -##### Simple chain with warm-up. +#### Simple chain with warm-up. In this example we sample from a standard univariate normal distribution using slice sampling. ```python -import tensorflow as tf -import tensorflow_probability as tfp -import numpy as np - -tfd = tfp.distributions - -dtype = np.float32 - -target = tfd.Normal(loc=dtype(0), scale=dtype(1)) - -samples, _ = tfp.mcmc.sample_chain( - num_results=1000, - current_state=dtype(1), - kernel=tfp.mcmc.SliceSampler( - target.log_prob, - step_size=1.0, - max_doublings=5, - seed=1234), - num_burnin_steps=500, - parallel_iterations=1) # For determinism. - -sample_mean = tf.reduce_mean(samples, axis=0) -sample_std = tf.sqrt( - tf.reduce_mean(tf.squared_difference(samples, sample_mean), - axis=0)) - -with tf.Session() as sess: - [sample_mean, sample_std] = sess.run([sample_mean, sample_std]) - -print "Sample mean: ", sample_mean -print "Sample Std: ", sample_std - -##### Sample from a Two Dimensional Normal. - -dtype = np.float32 -true_mean = dtype([0, 0]) -true_cov = dtype([[1, 0.5], [0.5, 1]]) -num_results = 500 -num_chains = 50 - -# Target distribution is defined through the Cholesky decomposition -chol = tf.linalg.cholesky(true_cov) -target = tfd.MultivariateNormalTriL(loc=true_mean, scale_tril=chol) - -# Assume that the state is passed as a list of 1-d tensors `x` and `y`. -# Then the target log-density is defined as follows: -def target_log_prob(x, y): - # Stack the input tensors together - z = tf.stack([x, y], axis=-1) - true_mean - return target.log_prob(z) - -# Initial state of the chain -init_state = [np.ones([num_chains, 1], dtype=dtype), - np.ones([num_chains, 1], dtype=dtype)] - -# Run Slice Samper for `num_results` iterations for `num_chains` -# independent chains: -[x, y], _ = tfp.mcmc.sample_chain( - num_results=num_results, - current_state=init_state, - kernel=tfp.mcmc.SliceSampler( - target_log_prob_fn=target_log_prob, - step_size=1.0, - max_doublings=5, - seed=47), - num_burnin_steps=200, - num_steps_between_results=1, - parallel_iterations=1) - -states = tf.stack([x, y], axis=-1) -sample_mean = tf.reduce_mean(states, axis=[0, 1]) -z = states - sample_mean -sample_cov = tf.reduce_mean(tf.matmul(z, z, transpose_a=True), - axis=[0, 1]) - -with tf.Session() as sess: - [sample_mean, sample_cov] = sess.run([ - sample_mean, sample_cov]) - -print "sample_mean: ", sample_mean -print "sample_cov: ", sample_cov - -#### References + import tensorflow as tf + import tensorflow_probability as tfp + import numpy as np -[1]: Radford M. Neal. Slice Sampling. The Annals of Statistics. 2003, Vol 31, - No. 3 , 705-767. - https://projecteuclid.org/download/pdf_1/euclid.aos/1056562461 -[2]: C.J.P. Belisle, H.E. Romeijn, R.L. Smith. Hit-and-run algorithms for - generating multivariate distributions. Math. Oper. Res., 18(1993), - 225-266. - https://www.jstor.org/stable/3690278?seq=1#page_scan_tab_contents - -## Properties - -

is_calibrated

- - - -

max_doublings

- - - -

name

+ tfd = tfp.distributions + dtype = np.float32 + target = tfd.Normal(loc=dtype(0), scale=dtype(1)) -

parameters

- -Returns `dict` of ``__init__`` arguments and their values. - -

seed

+ samples, _ = tfp.mcmc.sample_chain( + num_results=1000, + current_state=dtype(1), + kernel=tfp.mcmc.SliceSampler( + target.log_prob, + step_size=1.0, + max_doublings=5, + seed=1234), + num_burnin_steps=500, + parallel_iterations=1) # For determinism. + sample_mean = tf.reduce_mean(samples, axis=0) + sample_std = tf.sqrt( + tf.reduce_mean(tf.squared_difference(samples, sample_mean), + axis=0)) + with tf.Session() as sess: + [sample_mean, sample_std] = sess.run([sample_mean, sample_std]) -

step_size

- - + print "Sample mean: ", sample_mean + print "Sample Std: ", sample_std +``` -

target_log_prob_fn

+#### Sample from a Two Dimensional Normal. +In the following example we sample from a two dimensional Normal +distribution using slice sampling. +```python + import tensorflow as tf + import tensorflow_probability as tfp + import numpy as np + + tfd = tfp.distributions + + dtype = np.float32 + true_mean = dtype([0, 0]) + true_cov = dtype([[1, 0.5], [0.5, 1]]) + num_results = 500 + num_chains = 50 + + # Target distribution is defined through the Cholesky decomposition + chol = tf.linalg.cholesky(true_cov) + target = tfd.MultivariateNormalTriL(loc=true_mean, scale_tril=chol) + + # Assume that the state is passed as a list of 1-d tensors `x` and `y`. + # Then the target log-density is defined as follows: + def target_log_prob(x, y): + # Stack the input tensors together + z = tf.stack([x, y], axis=-1) - true_mean + return target.log_prob(z) + + # Initial state of the chain + init_state = [np.ones([num_chains, 1], dtype=dtype), + np.ones([num_chains, 1], dtype=dtype)] + + # Run Slice Samper for `num_results` iterations for `num_chains` + # independent chains: + [x, y], _ = tfp.mcmc.sample_chain( + num_results=num_results, + current_state=init_state, + kernel=tfp.mcmc.SliceSampler( + target_log_prob_fn=target_log_prob, + step_size=1.0, + max_doublings=5, + seed=47), + num_burnin_steps=200, + num_steps_between_results=1, + parallel_iterations=1) + + states = tf.stack([x, y], axis=-1) + sample_mean = tf.reduce_mean(states, axis=[0, 1]) + z = states - sample_mean + sample_cov = tf.reduce_mean(tf.matmul(z, z, transpose_a=True), + axis=[0, 1]) + + with tf.Session() as sess: + [sample_mean, sample_cov] = sess.run([ + sample_mean, sample_cov]) + + print "sample_mean: ", sample_mean + print "sample_cov: ", sample_cov +``` +### References +[1]: Radford M. Neal. Slice Sampling. The Annals of Statistics. 2003, Vol 31, + No. 3 , 705-767. + https://projecteuclid.org/download/pdf_1/euclid.aos/1056562461 -## Methods +[2]: C.J.P. Belisle, H.E. Romeijn, R.L. Smith. Hit-and-run algorithms for + generating multivariate distributions. Math. Oper. Res., 18(1993), + 225-266. + https://www.jstor.org/stable/3690278?seq=1#page_scan_tab_contents -

__init__

+

__init__

``` python __init__( @@ -198,7 +178,7 @@ Initializes this transition kernel. #### Args: * `target_log_prob_fn`: Python callable which takes an argument like - `current_state` (or `*current_state` if it's a list) and returns its + `current_state` (or `*current_state` if it is a list) and returns its (possibly unnormalized) log-density under the target distribution. * `step_size`: Scalar or `tf.Tensor` with same dtype as and shape compatible with `x_initial`. The size of the initial interval. @@ -217,6 +197,42 @@ Initializes this transition kernel. * `kernel_results`: `collections.namedtuple` of internal calculations used to advance the chain. + + +## Properties + +

is_calibrated

+ + + +

max_doublings

+ + + +

name

+ + + +

parameters

+ +Returns `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

step_size

+ + + +

target_log_prob_fn

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransformedTransitionKernel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransformedTransitionKernel.md index 607b28f1b9..f484313084 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransformedTransitionKernel.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransformedTransitionKernel.md @@ -1,5 +1,6 @@
+ @@ -98,33 +99,7 @@ sample_var = tf.reduce_mean( hamiltonian monte carlo methods. In _Journal of the Royal Statistical Society_, 2011. https://doi.org/10.1111/j.1467-9868.2010.00765.x -## Properties - -

bijector

- - - -

inner_kernel

- - - -

is_calibrated

- - - -

name

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -145,7 +120,7 @@ Instantiates this object. `inner_kernel` state space to the state expected by `inner_kernel.target_log_prob_fn`. * `name`: Python `str` name prefixed to Ops created by this function. - Default value: `None` (i.e., "hmc_kernel"). + Default value: `None` (i.e., "transformed_kernel"). #### Returns: @@ -154,6 +129,34 @@ Instantiates this object. transition kernel then modifies its `target_log_prob_fn` by applying the provided bijector(s). + + +## Properties + +

bijector

+ + + +

inner_kernel

+ + + +

is_calibrated

+ + + +

name

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransitionKernel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransitionKernel.md index c8f0dfeb7e..5109c4a4b4 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransitionKernel.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/TransitionKernel.md @@ -1,5 +1,6 @@
+ diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedHamiltonianMonteCarlo.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedHamiltonianMonteCarlo.md index dfdd5293fa..662d39cb17 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedHamiltonianMonteCarlo.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedHamiltonianMonteCarlo.md @@ -1,5 +1,6 @@
+ @@ -28,45 +29,7 @@ or `MetropolisHastings(UncalibratedHamiltonianMonteCarlo(...))`. For more details on `UncalibratedHamiltonianMonteCarlo`, see `HamiltonianMonteCarlo`. -## Properties - -

is_calibrated

- - - -

name

- - - -

num_leapfrog_steps

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

state_gradients_are_stopped

- - - -

step_size

- - - -

target_log_prob_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -108,19 +71,44 @@ Initializes this transition kernel. Default value: `None` (i.e., 'hmc_kernel'). -#### Returns: -* `next_state`: Tensor or Python list of `Tensor`s representing the state(s) - of the Markov chain(s) at each result step. Has same shape as - `current_state`. -* `kernel_results`: `collections.namedtuple` of internal calculations used to - advance the chain. +## Properties + +

is_calibrated

-#### Raises: -* `ValueError`: if there isn't one `step_size` or a list with same length as - `current_state`. +

name

+ + + +

num_leapfrog_steps

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

state_gradients_are_stopped

+ + + +

step_size

+ + + +

target_log_prob_fn

+ + + + + +## Methods

bootstrap_results

diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedLangevin.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedLangevin.md index c1f15f302c..6ba01294e1 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedLangevin.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedLangevin.md @@ -1,5 +1,6 @@
+ @@ -34,49 +35,7 @@ Warning: this kernel will not result in a chain which converges to the For more details on `UncalibratedLangevin`, see `MetropolisAdjustedLangevinAlgorithm`. -## Properties - -

compute_acceptance

- - - -

is_calibrated

- - - -

name

- - - -

parallel_iterations

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

step_size

- - - -

target_log_prob_fn

- - - -

volatility_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -134,6 +93,50 @@ Initializes Langevin diffusion transition kernel. `current_state`. * `TypeError`: if `volatility_fn` is not callable. + + +## Properties + +

compute_acceptance

+ + + +

is_calibrated

+ + + +

name

+ + + +

parallel_iterations

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

step_size

+ + + +

target_log_prob_fn

+ + + +

volatility_fn

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedRandomWalk.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedRandomWalk.md index c719be20f9..fc174bdb4f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedRandomWalk.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/UncalibratedRandomWalk.md @@ -1,5 +1,6 @@
+ @@ -27,37 +28,7 @@ Warning: this kernel will not result in a chain which converges to the For more details on `UncalibratedRandomWalk`, see `RandomWalkMetropolis`. -## Properties - -

is_calibrated

- - - -

name

- - - -

new_state_fn

- - - -

parameters

- -Return `dict` of ``__init__`` arguments and their values. - -

seed

- - - -

target_log_prob_fn

- - - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -99,6 +70,38 @@ Initializes this transition kernel. * `ValueError`: if there isn't one `scale` or a list with same length as `current_state`. + + +## Properties + +

is_calibrated

+ + + +

name

+ + + +

new_state_fn

+ + + +

parameters

+ +Return `dict` of ``__init__`` arguments and their values. + +

seed

+ + + +

target_log_prob_fn

+ + + + + +## Methods +

bootstrap_results

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/default_exchange_proposed_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/default_exchange_proposed_fn.md index a8054a0396..083153d9ee 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/default_exchange_proposed_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/default_exchange_proposed_fn.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.default_exchange_proposed_fn diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/effective_sample_size.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/effective_sample_size.md index 669b6fe8e6..b64960b6c3 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/effective_sample_size.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/effective_sample_size.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.effective_sample_size diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/make_simple_step_size_update_policy.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/make_simple_step_size_update_policy.md index b7c23f5a24..300a18a2bc 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/make_simple_step_size_update_policy.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/make_simple_step_size_update_policy.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.make_simple_step_size_update_policy diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/potential_scale_reduction.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/potential_scale_reduction.md index 599c7dc014..9acc018364 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/potential_scale_reduction.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/potential_scale_reduction.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.potential_scale_reduction diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_normal_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_normal_fn.md index cdddc3591e..925ca20da9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_normal_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_normal_fn.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.random_walk_normal_fn diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_uniform_fn.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_uniform_fn.md index e5c550bbe8..8169dfab5e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_uniform_fn.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/random_walk_uniform_fn.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.random_walk_uniform_fn diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_annealed_importance_chain.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_annealed_importance_chain.md index 6d8f4e3d21..6c263cb6cf 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_annealed_importance_chain.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_annealed_importance_chain.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.sample_annealed_importance_chain diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_chain.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_chain.md index c1afe2acae..1639983a13 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_chain.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_chain.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.sample_chain diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_halton_sequence.md b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_halton_sequence.md index c41a53640f..f0c3173f25 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_halton_sequence.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/mcmc/sample_halton_sequence.md @@ -1,5 +1,6 @@
+
# tfp.mcmc.sample_halton_sequence @@ -98,10 +99,10 @@ print ("Leaped Estimated: %f, True Value: %f" % values) * `dim`: Positive Python `int` representing each sample's `event_size.` Must not be greater than 1000. -* `num_results`: (Optional) positive Python `int`. The number of samples to - generate. Either this parameter or sequence_indices must be specified but - not both. If this parameter is None, then the behaviour is determined by - the `sequence_indices`. +* `num_results`: (Optional) Positive scalar `Tensor` of dtype int32. The number + of samples to generate. Either this parameter or sequence_indices must + be specified but not both. If this parameter is None, then the behaviour + is determined by the `sequence_indices`. Default value: `None`. * `sequence_indices`: (Optional) `Tensor` of dtype int32 and rank 1. The elements of the sequence to compute specified by their position in the diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo.md b/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo.md index b4e015a711..36080ec3f5 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo.md @@ -1,5 +1,6 @@
+ @@ -16,11 +17,11 @@ Monte Carlo integration and helpers. ## Other Members -`__all__` +

__all__

-`absolute_import` +

absolute_import

-`division` +

division

-`print_function` + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo/expectation.md b/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo/expectation.md index 59c6c57775..70f3e9b130 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo/expectation.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/monte_carlo/expectation.md @@ -1,5 +1,6 @@
+
# tfp.monte_carlo.expectation diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer.md index 248f6a184c..463be259c5 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer.md @@ -1,5 +1,6 @@
+
# Module: tfp.optimizer diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/StochasticGradientLangevinDynamics.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/StochasticGradientLangevinDynamics.md index c61bd56e22..0af314971c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/StochasticGradientLangevinDynamics.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/StochasticGradientLangevinDynamics.md @@ -1,5 +1,6 @@
+ @@ -139,17 +140,7 @@ with tf.Session(graph=tf.Graph()) as sess: Networks. In _Association for the Advancement of Artificial Intelligence_, 2016. https://arxiv.org/abs/1512.07666 -## Properties - -

variable_scope

- -Variable scope of all calls to `tf.get_variable`. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -166,6 +157,18 @@ __init__( + + +## Properties + +

variable_scope

+ +Variable scope of all calls to `tf.get_variable`. + + + +## Methods +

apply_gradients

``` python @@ -366,13 +369,12 @@ was not `None`, that operation also increments `global_step`. #### Eager Compatibility When eager execution is enabled, `loss` should be a Python function that -takes elements of `var_list` as arguments and computes the value to be -minimized. If `var_list` is None, `loss` should take no arguments. -Minimization (and gradient computation) is done with respect to the -elements of `var_list` if not None, else with respect to any trainable -variables created during the execution of the `loss` function. -`gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and -`grad_loss` are ignored when eager execution is enabled. +takes no arguments and computes the value to be minimized. Minimization (and +gradient computation) is done with respect to the elements of `var_list` if +not None, else with respect to any trainable variables created during the +execution of the `loss` function. `gate_gradients`, `aggregation_method`, +`colocate_gradients_with_ops` and `grad_loss` are ignored when eager +execution is enabled. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/VariationalSGD.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/VariationalSGD.md index c1b583d371..7c10c413f8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/VariationalSGD.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/VariationalSGD.md @@ -1,5 +1,6 @@
+ @@ -73,17 +74,7 @@ described below. Gradient Descent as Approximate Bayesian Inference. _arXiv preprint arXiv:1704.04289_, 2017. https://arxiv.org/abs/1704.04289 -## Properties - -

variable_scope

- -Variable scope of all calls to `tf.get_variable`. - - - -## Methods - -

__init__

+

__init__

``` python __init__( @@ -101,6 +92,18 @@ __init__( + + +## Properties + +

variable_scope

+ +Variable scope of all calls to `tf.get_variable`. + + + +## Methods +

apply_gradients

``` python @@ -301,13 +304,12 @@ was not `None`, that operation also increments `global_step`. #### Eager Compatibility When eager execution is enabled, `loss` should be a Python function that -takes elements of `var_list` as arguments and computes the value to be -minimized. If `var_list` is None, `loss` should take no arguments. -Minimization (and gradient computation) is done with respect to the -elements of `var_list` if not None, else with respect to any trainable -variables created during the execution of the `loss` function. -`gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and -`grad_loss` are ignored when eager execution is enabled. +takes no arguments and computes the value to be minimized. Minimization (and +gradient computation) is done with respect to the elements of `var_list` if +not None, else with respect to any trainable variables created during the +execution of the `loss` function. `gate_gradients`, `aggregation_method`, +`colocate_gradients_with_ops` and `grad_loss` are ignored when eager +execution is enabled. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/bfgs_minimize.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/bfgs_minimize.md index c1e9d53251..8f01d04115 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/bfgs_minimize.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/bfgs_minimize.md @@ -1,5 +1,6 @@
+
# tfp.optimizer.bfgs_minimize diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch.md index dd39635e6b..557cda3aff 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch.md @@ -1,5 +1,6 @@
+
# Module: tfp.optimizer.linesearch diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch/hager_zhang.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch/hager_zhang.md index 767475cf82..1ed50eb96d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch/hager_zhang.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/linesearch/hager_zhang.md @@ -1,5 +1,6 @@
+
# tfp.optimizer.linesearch.hager_zhang @@ -90,10 +91,12 @@ usage of the line search. guaranteed descent and an efficient line search. SIAM J. Optim., Vol 16. 1, pp. 170-172. 2005. https://www.math.lsu.edu/~hozhang/papers/cg_descent.pdf + [2]: William Hager, Hongchao Zhang. Algorithm 851: CG_DESCENT, a conjugate gradient method with guaranteed descent. ACM Transactions on Mathematical Software, Vol 32., 1, pp. 113-137. 2006. http://users.clas.ufl.edu/hager/papers/CG/cg_compare.pdf + [3]: Jorge Nocedal, Stephen Wright. Numerical Optimization. Springer Series in Operations Research. pp 33-36. 2006 diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_minimize.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_minimize.md index b9ff74253b..f9b710af7c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_minimize.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_minimize.md @@ -1,5 +1,6 @@
+
# tfp.optimizer.nelder_mead_minimize @@ -72,7 +73,8 @@ point. # Check that the search converged assert(results.converged) # Check that the argmin is close to the actual value. - np.testing.assert_allclose(results.position, np.array([0.0, 0.0])) + np.testing.assert_allclose(results.position, np.array([0.0, 0.0]), + atol=1e-7) # Print out the total number of function evaluations it took. print ("Function evaluations: %d" % results.num_objective_evaluations) ``` @@ -81,10 +83,12 @@ point. [1]: William Press, Saul Teukolsky, William Vetterling and Brian Flannery. Numerical Recipes in C++, third edition. pp. 502-507. (2007). http://numerical.recipes/cpppages/chap0sel.pdf + [2]: Jeffrey Lagarias, James Reeds, Margaret Wright and Paul Wright. Convergence properties of the Nelder-Mead simplex method in low dimensions, Siam J. Optim., Vol 9, No. 1, pp. 112-147. (1998). http://www.math.kent.edu/~reichel/courses/Opt/reading.material.2/nelder.mead.pdf + [3]: Fuchang Gao and Lixing Han. Implementing the Nelder-Mead simplex algorithm with adaptive parameters. Computational Optimization and Applications, Vol 51, Issue 1, pp 259-277. (2012). @@ -127,20 +131,20 @@ point. * `objective_at_initial_vertex`: (Optional) Scalar `Tensor` of real dtype. The value of the objective function at the initial vertex. May be supplied only if the `initial_vertex` is also supplied. -* `batch_evaluate_objective`: Python `bool`. If True, the objective function - will be evaluated on all the vertices of the simplex packed into a - single tensor. If False, the objective will be mapped across each +* `batch_evaluate_objective`: (Optional) Python `bool`. If True, the objective + function will be evaluated on all the vertices of the simplex packed + into a single tensor. If False, the objective will be mapped across each vertex separately. Evaluating the objective function in a batch allows use of vectorization and should be preferred if the objective function allows it. -* `func_tolerance`: Scalar `Tensor` of real dtype. The algorithm stops - if the absolute difference between the largest and the smallest +* `func_tolerance`: (Optional) Scalar `Tensor` of real dtype. The algorithm + stops if the absolute difference between the largest and the smallest function value on the vertices of the simplex is below this number. -* `position_tolerance`: Scalar `Tensor` of real dtype. The algorithm stops - if the largest absolute difference between the coordinates of the - vertices is below this threshold. -* `parallel_iterations`: Positive integer. The number of iterations allowed to - run in parallel. +* `position_tolerance`: (Optional) Scalar `Tensor` of real dtype. The + algorithm stops if the largest absolute difference between the + coordinates of the vertices is below this threshold. +* `parallel_iterations`: (Optional) Positive integer. The number of iterations + allowed to run in parallel. * `max_iterations`: (Optional) Scalar positive `Tensor` of dtype `int32`. The maximum number of iterations allowed. If `None` then no limit is applied. diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_one_step.md b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_one_step.md index 3ded6fec5c..0b51a895a6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_one_step.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/optimizer/nelder_mead_one_step.md @@ -1,5 +1,6 @@
+
# tfp.optimizer.nelder_mead_one_step diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels.md index 96c04104dd..ead98e294a 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels.md @@ -1,5 +1,6 @@
+
# Module: tfp.positive_semidefinite_kernels diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExpSinSquared.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExpSinSquared.md index 1553617625..9306c4f68f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExpSinSquared.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExpSinSquared.md @@ -1,7 +1,9 @@
+ + @@ -35,6 +37,44 @@ k(x, y) = amplitude**2 * exp( This kernel acts over the space `S = R^(D1 x D2 x D3 ... Dd)`. +

__init__

+ +``` python +__init__( + amplitude=None, + length_scale=None, + period=None, + feature_ndims=1, + validate_args=False, + name='ExpSinSquared' +) +``` + +Construct a ExpSinSquared kernel instance. + +#### Args: + +* `amplitude`: Positive floating point `Tensor` that controls the maximum + value of the kernel. Must be broadcastable with `period`, `length_scale` + and inputs to `apply` and `matrix` methods. A value of `None` is treated + like 1. +* `length_scale`: Positive floating point `Tensor` that controls how sharp or + wide the kernel shape is. This provides a characteristic "unit" of + length against which `|x - y|` can be compared for scale. Must be + broadcastable with `amplitude`, `period` and inputs to `apply` and + `matrix` methods. A value of `None` is treated like 1. +* `period`: Positive floating point `Tensor` that controls the period of the + kernel. Must be broadcastable with `amplitude`, `length_scale` and + inputs to `apply` and `matrix` methods. A value of `None` is treated + like 1. +* `feature_ndims`: Python `int` number of rightmost dims to include in kernel + computation. +* `validate_args`: If `True`, parameters are checked for validity despite + possibly degrading runtime performance +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

amplitude

@@ -71,6 +111,10 @@ concrete implementation sub-classes are obliged to provide. `TensorShape` instance describing the fully broadcast shape of all kernel parameters. +

dtype

+ +DType over which the kernel operates. +

feature_ndims

The number of feature dimensions. @@ -106,42 +150,6 @@ Period parameter. ## Methods -

__init__

- -``` python -__init__( - amplitude=None, - length_scale=None, - period=None, - feature_ndims=1, - validate_args=False, - name='ExpSinSquared' -) -``` - -Construct a ExpSinSquared kernel instance. - -#### Args: - -* `amplitude`: Positive floating point `Tensor` that controls the maximum - value of the kernel. Must be broadcastable with `period`, `length_scale` - and inputs to `apply` and `matrix` methods. A value of `None` is treated - like 1. -* `length_scale`: Positive floating point `Tensor` that controls how sharp or - wide the kernel shape is. This provides a characteristic "unit" of - length against which `|x - y|` can be compared for scale. Must be - broadcastable with `amplitude`, `period` and inputs to `apply` and - `matrix` methods. A value of `None` is treated like 1. -* `period`: Positive floating point `Tensor` that controls the period of the - kernel. Must be broadcastable with `amplitude`, `length_scale` and - inputs to `apply` and `matrix` methods. A value of `None` is - treated like 1. -* `feature_ndims`: Python `int` number of rightmost dims to include in kernel - computation. -* `validate_args`: If `True`, parameters are checked for validity despite - possibly degrading runtime performance -* `name`: Python `str` name prefixed to Ops created by this class. -

__add__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExponentiatedQuadratic.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExponentiatedQuadratic.md index 16fb090c2b..882be7e27e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExponentiatedQuadratic.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/ExponentiatedQuadratic.md @@ -1,7 +1,9 @@
+ + @@ -32,6 +34,37 @@ function", this kernel function has the form where the double-bars represent vector length (ie, Euclidean, or L2 norm). +

__init__

+ +``` python +__init__( + amplitude=None, + length_scale=None, + feature_ndims=1, + validate_args=False, + name='ExponentiatedQuadratic' +) +``` + +Construct an ExponentiatedQuadratic kernel instance. + +#### Args: + +* `amplitude`: floating point `Tensor` that controls the maximum value + of the kernel. Must be broadcastable with `length_scale` and inputs to + `apply` and `matrix` methods. Must be greater than zero. +* `length_scale`: floating point `Tensor` that controls how sharp or wide the + kernel shape is. This provides a characteristic "unit" of length against + which `||x - y||` can be compared for scale. Must be broadcastable with + `amplitude` and inputs to `apply` and `matrix` methods. +* `feature_ndims`: Python `int` number of rightmost dims to include in the + squared difference norm in the exponential. +* `validate_args`: If `True`, parameters are checked for validity despite + possibly degrading runtime performance +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

amplitude

@@ -68,6 +101,10 @@ concrete implementation sub-classes are obliged to provide. `TensorShape` instance describing the fully broadcast shape of all kernel parameters. +

dtype

+ +DType over which the kernel operates. +

feature_ndims

The number of feature dimensions. @@ -99,35 +136,6 @@ Name prepended to all ops created by this class. ## Methods -

__init__

- -``` python -__init__( - amplitude=None, - length_scale=None, - feature_ndims=1, - validate_args=False, - name='ExponentiatedQuadratic' -) -``` - -Construct an ExponentiatedQuadratic kernel instance. - -#### Args: - -* `amplitude`: floating point `Tensor` that controls the maximum value - of the kernel. Must be broadcastable with `length_scale` and inputs to - `apply` and `matrix` methods. Must be greater than zero. -* `length_scale`: floating point `Tensor` that controls how sharp or wide the - kernel shape is. This provides a characteristic "unit" of length against - which `||x - y||` can be compared for scale. Must be broadcastable with - `amplitude` and inputs to `apply` and `matrix` methods. -* `feature_ndims`: Python `int` number of rightmost dims to include in the - squared difference norm in the exponential. -* `validate_args`: If `True`, parameters are checked for validity despite - possibly degrading runtime performance -* `name`: Python `str` name prefixed to Ops created by this class. -

__add__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternFiveHalves.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternFiveHalves.md index 6b80ef2dbc..c740923a45 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternFiveHalves.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternFiveHalves.md @@ -1,7 +1,9 @@
+ + @@ -33,6 +35,39 @@ This kernel is part of the Matern family of kernels, with parameter 5/2. where the double-bars represent vector length (i.e. Euclidean, or L2 Norm). This kernel, acts over the space `S = R^(D1 x D2 .. x Dd)`. +

__init__

+ +``` python +__init__( + amplitude=None, + length_scale=None, + feature_ndims=1, + validate_args=False, + name='MaternFiveHalves' +) +``` + +Construct a MaternFiveHalves kernel instance. + +#### Args: + +* `amplitude`: Positive floating point `Tensor` that controls the maximum + value of the kernel. Must be broadcastable with `length_scale` and + inputs to `apply` and `matrix` methods. A value of `None` is treated + like 1. +* `length_scale`: Positive floating point `Tensor` that controls how sharp or + wide the kernel shape is. This provides a characteristic "unit" of + length against which `||x - y||` can be compared for scale. Must be + broadcastable with `amplitude`, and inputs to `apply` and `matrix` + methods. A value of `None` is treated like 1. +* `feature_ndims`: Python `int` number of rightmost dims to include in the + squared difference norm in the exponential. +* `validate_args`: If `True`, parameters are checked for validity despite + possibly degrading runtime performance +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

amplitude

@@ -69,6 +104,10 @@ concrete implementation sub-classes are obliged to provide. `TensorShape` instance describing the fully broadcast shape of all kernel parameters. +

dtype

+ +DType over which the kernel operates. +

feature_ndims

The number of feature dimensions. @@ -100,37 +139,6 @@ Name prepended to all ops created by this class. ## Methods -

__init__

- -``` python -__init__( - amplitude=None, - length_scale=None, - feature_ndims=1, - validate_args=False, - name='MaternFiveHalves' -) -``` - -Construct a MaternFiveHalves kernel instance. - -#### Args: - -* `amplitude`: Positive floating point `Tensor` that controls the maximum - value of the kernel. Must be broadcastable with `length_scale` and - inputs to `apply` and `matrix` methods. A value of `None` is treated - like 1. -* `length_scale`: Positive floating point `Tensor` that controls how sharp - or wide the kernel shape is. This provides a characteristic "unit" of - length against which `||x - y||` can be compared for scale. Must be - broadcastable with `amplitude`, and inputs to `apply` and `matrix` - methods. A value of `None` is treated like 1. -* `feature_ndims`: Python `int` number of rightmost dims to include in the - squared difference norm in the exponential. -* `validate_args`: If `True`, parameters are checked for validity despite - possibly degrading runtime performance -* `name`: Python `str` name prefixed to Ops created by this class. -

__add__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternOneHalf.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternOneHalf.md index 32e57e8d78..3f90659c5d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternOneHalf.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternOneHalf.md @@ -1,7 +1,9 @@
+ + @@ -37,6 +39,39 @@ The kernel has the following form: where the double-bars represent vector length (i.e. Euclidean, or L2 Norm). This kernel, acts over the space `S = R^(D1 x D2 .. x Dd)`. +

__init__

+ +``` python +__init__( + amplitude=None, + length_scale=None, + feature_ndims=1, + validate_args=False, + name='MaternOneHalf' +) +``` + +Construct a MaternOneHalf kernel instance. + +#### Args: + +* `amplitude`: Positive floating point `Tensor` that controls the maximum + value of the kernel. Must be broadcastable with `length_scale` and + inputs to `apply` and `matrix` methods. A value of `None` is treated + like 1. +* `length_scale`: Positive floating point `Tensor` that controls how sharp or + wide the kernel shape is. This provides a characteristic "unit" of + length against which `||x - y||` can be compared for scale. Must be + broadcastable with `amplitude` and inputs to `apply` and `matrix` + methods. A value of `None` is treated like 1. +* `feature_ndims`: Python `int` number of rightmost dims to include in the + squared difference norm in the exponential. +* `validate_args`: If `True`, parameters are checked for validity despite + possibly degrading runtime performance +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

amplitude

@@ -73,6 +108,10 @@ concrete implementation sub-classes are obliged to provide. `TensorShape` instance describing the fully broadcast shape of all kernel parameters. +

dtype

+ +DType over which the kernel operates. +

feature_ndims

The number of feature dimensions. @@ -104,37 +143,6 @@ Name prepended to all ops created by this class. ## Methods -

__init__

- -``` python -__init__( - amplitude=None, - length_scale=None, - feature_ndims=1, - validate_args=False, - name='MaternOneHalf' -) -``` - -Construct a MaternOneHalf kernel instance. - -#### Args: - -* `amplitude`: Positive floating point `Tensor` that controls the maximum - value of the kernel. Must be broadcastable with `length_scale` and - inputs to `apply` and `matrix` methods. A value of `None` is treated - like 1. -* `length_scale`: Positive floating point `Tensor` that controls how sharp - or wide the kernel shape is. This provides a characteristic "unit" of - length against which `||x - y||` can be compared for scale. Must be - broadcastable with `amplitude` and inputs to `apply` and `matrix` - methods. A value of `None` is treated like 1. -* `feature_ndims`: Python `int` number of rightmost dims to include in the - squared difference norm in the exponential. -* `validate_args`: If `True`, parameters are checked for validity despite - possibly degrading runtime performance -* `name`: Python `str` name prefixed to Ops created by this class. -

__add__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternThreeHalves.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternThreeHalves.md index 8e205c20fb..f204d836b8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternThreeHalves.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/MaternThreeHalves.md @@ -1,7 +1,9 @@
+ + @@ -33,6 +35,39 @@ This kernel is part of the Matern family of kernels, with parameter 3/2. where the double-bars represent vector length (i.e. Euclidean, or L2 Norm). This kernel, acts over the space `S = R^(D1 x D2 .. x Dd)`. +

__init__

+ +``` python +__init__( + amplitude=None, + length_scale=None, + feature_ndims=1, + validate_args=False, + name='MaternThreeHalves' +) +``` + +Construct a MaternThreeHalves kernel instance. + +#### Args: + +* `amplitude`: Positive floating point `Tensor` that controls the maximum + value of the kernel. Must be broadcastable with `length_scale` and + inputs to `apply` and `matrix` methods. A value of `None` is treated + like 1. +* `length_scale`: Positive floating point `Tensor` that controls how sharp or + wide the kernel shape is. This provides a characteristic "unit" of + length against which `||x - y||` can be compared for scale. Must be + broadcastable with `amplitude` and inputs to `apply` and `matrix` + methods. A value of `None` is treated like 1. +* `feature_ndims`: Python `int` number of rightmost dims to include in the + squared difference norm in the exponential. +* `validate_args`: If `True`, parameters are checked for validity despite + possibly degrading runtime performance +* `name`: Python `str` name prefixed to Ops created by this class. + + + ## Properties

amplitude

@@ -69,6 +104,10 @@ concrete implementation sub-classes are obliged to provide. `TensorShape` instance describing the fully broadcast shape of all kernel parameters. +

dtype

+ +DType over which the kernel operates. +

feature_ndims

The number of feature dimensions. @@ -100,37 +139,6 @@ Name prepended to all ops created by this class. ## Methods -

__init__

- -``` python -__init__( - amplitude=None, - length_scale=None, - feature_ndims=1, - validate_args=False, - name='MaternThreeHalves' -) -``` - -Construct a MaternThreeHalves kernel instance. - -#### Args: - -* `amplitude`: Positive floating point `Tensor` that controls the maximum - value of the kernel. Must be broadcastable with `length_scale` and - inputs to `apply` and `matrix` methods. A value of `None` is treated - like 1. -* `length_scale`: Positive floating point `Tensor` that controls how sharp - or wide the kernel shape is. This provides a characteristic "unit" of - length against which `||x - y||` can be compared for scale. Must be - broadcastable with `amplitude` and inputs to `apply` and `matrix` - methods. A value of `None` is treated like 1. -* `feature_ndims`: Python `int` number of rightmost dims to include in the - squared difference norm in the exponential. -* `validate_args`: If `True`, parameters are checked for validity despite - possibly degrading runtime performance -* `name`: Python `str` name prefixed to Ops created by this class. -

__add__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/PositiveSemidefiniteKernel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/PositiveSemidefiniteKernel.md index 2adb29af9c..54a58d51de 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/PositiveSemidefiniteKernel.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/positive_semidefinite_kernels/PositiveSemidefiniteKernel.md @@ -1,6 +1,8 @@
+ + @@ -101,6 +103,46 @@ partition into 3 pieces: requirement is that batch dimensions of inputs `x` and `y` be broadcastable with each other and with the kernel's parameter batch shapes (see above). +

__init__

+ +``` python +__init__( + feature_ndims, + dtype=None, + name=None +) +``` + +Construct a PositiveSemidefiniteKernel (subclass) instance. + +#### Args: + +* `feature_ndims`: Python `integer` indicating the number of dims (the rank) + of the feature space this kernel acts on. +* `dtype`: `DType` on which this kernel operates. +* `name`: Python `str` name prefixed to Ops created by this class. Default: + subclass name. + + +#### Raises: + +* `ValueError`: if `feature_ndims` is not an integer greater than 0 +Inputs to PositiveSemidefiniteKernel methods partition into 3 pieces: + +```none +[b1, ..., bB, e, f1, ..., fF] +'----------' | '---------' + | | '-- Feature dimensions + | '-- Example dimension (`matrix`-only) + '-- Batch dimensions +``` + +The `feature_ndims` argument declares how many of the right-most shape +dimensions belong to the feature dimensions. This enables us to predict +which shape dimensions will be 'reduced' away during kernel computation. + + + ## Properties

batch_shape

@@ -133,6 +175,10 @@ concrete implementation sub-classes are obliged to provide. `TensorShape` instance describing the fully broadcast shape of all kernel parameters. +

dtype

+ +DType over which the kernel operates. +

feature_ndims

The number of feature dimensions. @@ -160,42 +206,6 @@ Name prepended to all ops created by this class. ## Methods -

__init__

- -``` python -__init__( - feature_ndims, - name=None -) -``` - -Construct a PositiveSemidefiniteKernel (subclass) instance. - -#### Args: - -* `feature_ndims`: Python `integer` indicating the number of dims (the rank) - of the feature space this kernel acts on. -* `name`: Python `str` name prefixed to Ops created by this class. Default: - subclass name. - - -#### Raises: - -* `ValueError`: if `feature_ndims` is not an integer greater than 0 -Inputs to PositiveSemidefiniteKernel methods partition into 3 pieces: - -```none -[b1, ..., bB, e, f1, ..., fF] -'----------' | '---------' - | | '-- Feature dimensions - | '-- Example dimension (`matrix`-only) - '-- Batch dimensions -``` - -The `feature_ndims` argument declares how many of the right-most shape -dimensions belong to the feature dimensions. This enables us to predict -which shape dimensions will be 'reduced' away during kernel computation. -

__add__

``` python diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts.md new file mode 100644 index 0000000000..ecdd1c1e49 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts.md @@ -0,0 +1,25 @@ +
+ + +
+ +# Module: tfp.sts + +Framework for Bayesian structural time series models. + +## Classes + +[`class AdditiveStateSpaceModel`](../tfp/sts/AdditiveStateSpaceModel.md): A state space model representing a sum of component state space models. + +[`class LocalLinearTrend`](../tfp/sts/LocalLinearTrend.md): Formal representation of a local linear trend model. + +[`class LocalLinearTrendStateSpaceModel`](../tfp/sts/LocalLinearTrendStateSpaceModel.md): State space model for a local linear trend. + +[`class Seasonal`](../tfp/sts/Seasonal.md): Formal representation of a seasonal effect model. + +[`class SeasonalStateSpaceModel`](../tfp/sts/SeasonalStateSpaceModel.md): State space model for a seasonal effect. + +[`class StructuralTimeSeries`](../tfp/sts/StructuralTimeSeries.md): Base class for structural time series models. + +[`class Sum`](../tfp/sts/Sum.md): Sum of structural time series components. + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/AdditiveStateSpaceModel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/AdditiveStateSpaceModel.md new file mode 100644 index 0000000000..df7ff25a04 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/AdditiveStateSpaceModel.md @@ -0,0 +1,920 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.sts.AdditiveStateSpaceModel + +## Class `AdditiveStateSpaceModel` + +Inherits From: [`LinearGaussianStateSpaceModel`](../../tfp/distributions/LinearGaussianStateSpaceModel.md) + +A state space model representing a sum of component state space models. + +A state space model (SSM) posits a set of latent (unobserved) variables that +evolve over time with dynamics specified by a probabilistic transition model +`p(z[t+1] | z[t])`. At each timestep, we observe a value sampled from an +observation model conditioned on the current state, `p(x[t] | z[t])`. The +special case where both the transition and observation models are Gaussians +with mean specified as a linear function of the inputs, is known as a linear +Gaussian state space model and supports tractable exact probabilistic +calculations; see tfp.distributions.LinearGaussianStateSpaceModel for +details. + +The `AdditiveStateSpaceModel` represents a sum of component state space +models. Each of the `N` components describes a random process +generating a distribution on observed time series `x1[t], x2[t], ..., xN[t]`. +The additive model represents the sum of these +processes, `y[t] = x1[t] + x2[t] + ... + xN[t] + eps[t]`, where +`eps[t] ~ N(0, observation_noise_scale)` is an observation noise term. + +#### Mathematical Details + +The additive model concatenates the latent states of its component models. +The generative process runs each component's dynamics in its own subspace of +latent space, and then observes the sum of the observation models from the +components. + +Formally, the transition model is linear Gaussian: + +``` +p(z[t+1] | z[t]) ~ Normal(loc = transition_matrix.matmul(z[t]), + cov = transition_cov) +``` + +where each `z[t]` is a latent state vector concatenating the component +state vectors, `z[t] = [z1[t], z2[t], ..., zN[t]]`, so it has size +`latent_size = sum([c.latent_size for c in components])`. + +The transition matrix is the block-diagonal composition of transition +matrices from the component processes: + +``` +transition_matrix = + [[ c0.transition_matrix, 0., ..., 0. ], + [ 0., c1.transition_matrix, ..., 0. ], + [ ... ... ... ], + [ 0., 0., ..., cN.transition_matrix ]] +``` + +and the noise covariance is similarly the block-diagonal composition of +component noise covariances: + +``` +transition_cov = + [[ c0.transition_cov, 0., ..., 0. ], + [ 0., c1.transition_cov, ..., 0. ], + [ ... ... ... ], + [ 0., 0., ..., cN.transition_cov ]] +``` + +The observation model is also linear Gaussian, + +``` +p(y[t] | z[t]) ~ Normal(loc = observation_matrix.matmul(z[t]), + stddev = observation_noise_scale) +``` + +This implementation assumes scalar observations, so +`observation_matrix` has shape `[1, latent_size]`. The additive +observation matrix simply concatenates the observation matrices from each +component: + +``` +observation_matrix = + concat([c0.obs_matrix, c1.obs_matrix, ..., cN.obs_matrix], axis=-1) +``` + +The effect is that each component observation matrix acts on the dimensions +of latent state corresponding to that component, and the overall expected +observation is the sum of the expected observations from each component. + +If `observation_noise_scale` is not explicitly specified, it is also computed +by summing the noise variances of the component processes: + +``` +observation_noise_scale = sqrt(sum([ + c.observation_noise_scale**2 for c in components])) +``` + +#### Examples + +To construct an additive state space model combining a local linear trend +and day-of-week seasonality component (note, the `StructuralTimeSeries` +classes, e.g., `Sum`, provide a higher-level interface for this +construction, which will likely be preferred by most users): + +``` + num_timesteps = 30 + local_ssm = tfp.sts.LocalLinearTrendStateSpaceModel( + num_timesteps=num_timesteps, + level_scale=0.5, + slope_scale=0.1, + initial_state_prior=tfd.MultivariateNormalDiag( + loc=[0., 0.], scale_diag=[1., 1.])) + day_of_week_ssm = tfp.sts.SeasonalStateSpaceModel( + num_timesteps=num_timesteps, + num_seasons=7, + initial_state_prior=tfd.MultivariateNormalDiag( + loc=tf.zeros([7]), scale_diag=tf.ones([7]))) + additive_ssm = tfp.sts.AdditiveStateSpaceModel( + component_ssms=[local_ssm, day_of_week_ssm], + observation_noise_scale=0.1) + + y = additive_ssm.sample() + print(y.shape) + # => [] +``` + +

__init__

+ +``` python +__init__( + component_ssms, + observation_noise_scale=None, + initial_state_prior=None, + initial_step=0, + validate_args=False, + allow_nan_stats=True, + name=None +) +``` + +Build a state space model representing the sum of component models. + +#### Args: + +* `component_ssms`: Python `list` containing one or more + `tfd.LinearGaussianStateSpaceModel` instances. The components + will in general implement different time-series models, with possibly + different `latent_size`, but they must have the same `dtype`, event + shape (`num_timesteps` and `observation_size`), and their batch shapes + must broadcast to a compatible batch shape. +* `observation_noise_scale`: Optional scalar `float` `Tensor` indicating the + standard deviation of the observation noise. May contain additional + batch dimensions, which must broadcast with the batch shape of elements + in `component_ssms`. If `observation_noise_scale` is specified for the + `AdditiveStateSpaceModel`, the observation noise scales of component + models are ignored. If `None`, the observation noise scale is derived + by summing the noise variances of the component models, i.e., + `observation_noise_scale = sqrt(sum( + [ssm.observation_noise_scale**2 for ssm in component_ssms]))`. +* `initial_state_prior`: Optional instance of `tfd.MultivariateNormal` + representing a prior distribution on the latent state at time + `initial_step`. If `None`, defaults to the independent priors from + component models, i.e., + `[component.initial_state_prior for component in component_ssms]`. + Default value: `None`. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `validate_args`: Python `bool`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are + invalid, correct behavior is not guaranteed. + Default value: `False`. +* `allow_nan_stats`: Python `bool`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member. If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. + Default value: `True`. +* `name`: Python `str` name prefixed to ops created by this class. + Default value: "AdditiveStateSpaceModel". + + +#### Raises: + +* `ValueError`: if components have different `num_timesteps`. + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

forward_filter

+ +``` python +forward_filter(x) +``` + +Run a Kalman filter over a provided sequence of outputs. + +Note that the returned values `filtered_means`, `predicted_means`, and +`observation_means` depend on the observed time series `x`, while the +corresponding covariances are independent of the observed series; i.e., they +depend only on the model itself. This means that the mean values have shape +`concat([sample_shape(x), batch_shape, [num_timesteps, +{latent/observation}_size]])`, while the covariances have shape +`concat[(batch_shape, [num_timesteps, {latent/observation}_size, +{latent/observation}_size]])`, which does not depend on the sample shape. + +#### Args: + +* `x`: a float-type `Tensor` with rightmost dimensions + `[num_timesteps, observation_size]` matching + `self.event_shape`. Additional dimensions must match or be + broadcastable to `self.batch_shape`; any further dimensions + are interpreted as a sample shape. + + +#### Returns: + +* `log_likelihoods`: Per-timestep log marginal likelihoods `log + p(x_t | x_{:t-1})` evaluated at the input `x`, as a `Tensor` + of shape `sample_shape(x) + batch_shape + [num_timesteps].` +* `filtered_means`: Means of the per-timestep filtered marginal + distributions p(z_t | x_{:t}), as a Tensor of shape + `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`. +* `filtered_covs`: Covariances of the per-timestep filtered marginal + distributions p(z_t | x_{:t}), as a Tensor of shape + `batch_shape + [num_timesteps, latent_size, latent_size]`. +* `predicted_means`: Means of the per-timestep predictive + distributions over latent states, p(z_{t+1} | x_{:t}), as a + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, latent_size]`. +* `predicted_covs`: Covariances of the per-timestep predictive + distributions over latent states, p(z_{t+1} | x_{:t}), as a + Tensor of shape `batch_shape + [num_timesteps, latent_size, + latent_size]`. +* `observation_means`: Means of the per-timestep predictive + distributions over observations, p(x_{t} | x_{:t-1}), as a + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, observation_size]`. +* `observation_covs`: Covariances of the per-timestep predictive + distributions over observations, p(x_{t} | x_{:t-1}), as a + Tensor of shape `batch_shape + [num_timesteps, + observation_size, observation_size]`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/LocalLinearTrend.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/LocalLinearTrend.md new file mode 100644 index 0000000000..809a37f264 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/LocalLinearTrend.md @@ -0,0 +1,238 @@ +
+ + + + + + + + + + + + +
+ +# tfp.sts.LocalLinearTrend + +## Class `LocalLinearTrend` + +Inherits From: [`StructuralTimeSeries`](../../tfp/sts/StructuralTimeSeries.md) + +Formal representation of a local linear trend model. + +The local linear trend model posits a `level` and `slope`, each +evolving via a Gaussian random walk: + +``` +level[t] = level[t-1] + slope[t-1] + Normal(0., level_scale) +slope[t] = slope[t-1] + Normal(0., slope_scale) +``` + +The latent state is the two-dimensional tuple `[level, slope]`. At each +timestep we observe a noisy realization of the current level: +`f[t] = level[t] + Normal(0., observation_noise_scale)`. This model +is appropriate for data where the trend direction and magnitude (latent +`slope`) is consistent within short periods but may evolve over time. + +Note that this model can produce very high uncertainty forecasts, as +uncertainty over the slope compounds quickly. If you expect your data to +have nonzero long-term trend, i.e. that slopes tend to revert to some mean, +then the `SemiLocalLinearTrend` model may produce sharper forecasts. + +

__init__

+ +``` python +__init__( + level_scale_prior=None, + slope_scale_prior=None, + initial_level_prior=None, + initial_slope_prior=None, + observed_time_series=None, + name=None +) +``` + +Specify a local linear trend model. + +#### Args: + +* `level_scale_prior`: optional `tfd.Distribution` instance specifying a prior + on the `level_scale` parameter. If `None`, a heuristic default prior is + constructed based on the provided `observed_time_series`. + Default value: `None`. +* `slope_scale_prior`: optional `tfd.Distribution` instance specifying a prior + on the `slope_scale` parameter. If `None`, a heuristic default prior is + constructed based on the provided `observed_time_series`. + Default value: `None`. +* `initial_level_prior`: optional `tfd.Distribution` instance specifying a + prior on the initial level. If `None`, a heuristic default prior is + constructed based on the provided `observed_time_series`. + Default value: `None`. +* `initial_slope_prior`: optional `tfd.Distribution` instance specifying a + prior on the initial slope. If `None`, a heuristic default prior is + constructed based on the provided `observed_time_series`. + Default value: `None`. +* `observed_time_series`: optional `float` `Tensor` of shape + `batch_shape + [T, 1]` (omitting the trailing unit dimension is also + supported when `T > 1`), specifying an observed time series. + Any priors not explicitly set will be given default values according to + the scale of the observed time series (or batch of time series). + Default value: `None`. +* `name`: the name of this model component. + Default value: 'LocalLinearTrend'. + + + +## Properties + +

batch_shape

+ +Static batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: A `tf.TensorShape` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape`. It may be partially + defined or unknown. + +

initial_state_prior

+ +Prior distribution on the initial latent state (level and scale). + +

latent_size

+ +Python `int` dimensionality of the latent space in this model. + +

name

+ +Name of this model component. + +

parameters

+ +List of Parameter(name, prior, bijector) namedtuples for this model. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor() +``` + +Runtime batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: `int` `Tensor` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape_tensor()`. + +

joint_log_prob

+ +``` python +joint_log_prob(observed_time_series) +``` + +Build the joint density `log p(params) + log p(y|params)` as a callable. + +#### Args: + +* `observed_time_series`: Observed `Tensor` trajectories of shape + `sample_shape + batch_shape + [num_timesteps, 1]` (the trailing + `1` dimension is optional if `num_timesteps > 1`), where + `batch_shape` should match `self.batch_shape` (the broadcast batch + shape of all priors on parameters for this structural time series + model). + + +#### Returns: + +log_joint_fn: A function taking a `Tensor` argument for each model + parameter, in canonical order, and returning a `Tensor` log probability + of shape `batch_shape`. Note that, *unlike* `tfp.Distributions` + `log_prob` methods, the `log_joint` sums over the `sample_shape` from y, + so that `sample_shape` does not appear in the output log_prob. This + corresponds to viewing multiple samples in `y` as iid observations from a + single model, which is typically the desired behavior for parameter + inference. + +

make_state_space_model

+ +``` python +make_state_space_model( + num_timesteps, + param_vals=None, + initial_state_prior=None, + initial_step=0 +) +``` + +Instantiate this model as a Distribution over specified `num_timesteps`. + +#### Args: + +* `num_timesteps`: Python `int` number of timesteps to model. +* `param_vals`: a list of `Tensor` parameter values in order corresponding to + `self.parameters`, or a dict mapping from parameter names to values. +* `initial_state_prior`: an optional `Distribution` instance overriding the + default prior on the model's initial state. This is used in forecasting + ("today's prior is yesterday's posterior"). +* `initial_step`: optional `int` specifying the initial timestep to model. + This is relevant when the model contains time-varying components, + e.g., holidays or seasonality. + + +#### Returns: + +* `dist`: a `LinearGaussianStateSpaceModel` Distribution object. + +

prior_sample

+ +``` python +prior_sample( + num_timesteps, + initial_step=0, + params_sample_shape=(), + trajectories_sample_shape=(), + seed=None +) +``` + +Sample from the joint prior over model parameters and trajectories. + +#### Args: + +* `num_timesteps`: Scalar `int` `Tensor` number of timesteps to model. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `params_sample_shape`: Number of possible worlds to sample iid from the + parameter prior, or more generally, `Tensor` `int` shape to fill with + iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `trajectories_sample_shape`: For each sampled set of parameters, number + of trajectories to sample, or more generally, `Tensor` `int` shape to + fill with iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `seed`: Python `int` random seed. + + +#### Returns: + +* `trajectories`: `float` `Tensor` of shape + `trajectories_sample_shape + params_sample_shape + [num_timesteps, 1]` + containing all sampled trajectories. +* `param_samples`: list of sampled parameter value `Tensor`s, in order + corresponding to `self.parameters`, each of shape + `params_sample_shape + prior.batch_shape + prior.event_shape`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/LocalLinearTrendStateSpaceModel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/LocalLinearTrendStateSpaceModel.md new file mode 100644 index 0000000000..3391dbc548 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/LocalLinearTrendStateSpaceModel.md @@ -0,0 +1,889 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.sts.LocalLinearTrendStateSpaceModel + +## Class `LocalLinearTrendStateSpaceModel` + +Inherits From: [`LinearGaussianStateSpaceModel`](../../tfp/distributions/LinearGaussianStateSpaceModel.md) + +State space model for a local linear trend. + +A state space model (SSM) posits a set of latent (unobserved) variables that +evolve over time with dynamics specified by a probabilistic transition model +`p(z[t+1] | z[t])`. At each timestep, we observe a value sampled from an +observation model conditioned on the current state, `p(x[t] | z[t])`. The +special case where both the transition and observation models are Gaussians +with mean specified as a linear function of the inputs, is known as a linear +Gaussian state space model and supports tractable exact probabilistic +calculations; see tfp.distributions.LinearGaussianStateSpaceModel for +details. + +The local linear trend model is a special case of a linear Gaussian SSM, in +which the latent state posits a `level` and `slope`, each evolving via a +Gaussian random walk: + +```python +level[t] = level[t-1] + slope[t-1] + Normal(0., level_scale) +slope[t] = slope[t-1] + Normal(0., slope_scale) +``` + +The latent state is the two-dimensional tuple `[level, slope]`. The +`level` is observed at each timestep. + +The parameters `level_scale`, `slope_scale`, and `observation_noise_scale` +are each (a batch of) scalars. The batch shape of this `Distribution` is the +broadcast batch shape of these parameters and of the `initial_state_prior`. + +#### Mathematical Details + +The linear trend model implements a +tfp.distributions.LinearGaussianStateSpaceModel with `latent_size = 2` +and `observation_size = 1`, following the transition model: + +``` +transition_matrix = [[1., 1.] + [0., 1.]] +transition_noise ~ N(loc=0., scale=diag([level_scale, slope_scale])) +``` + +which implements the evolution of `[level, slope]` described above, and +the observation model: + +``` +observation_matrix = [[1., 0.]] +observation_noise ~ N(loc=0, scale=observation_noise_scale) +``` + +which picks out the first latent component, i.e., the `level`, as the +observation at each timestep. + +#### Examples + +A simple model definition: + +```python +linear_trend_model = LocalLinearTrendStateSpaceModel( + num_timesteps=50, + level_scale=0.5, + slope_scale=0.5, + initial_state_prior=tfd.MultivariateNormalDiag(scale_diag=[1., 1.])) + +y = linear_trend_model.sample() # y has shape [50, 1] +lp = linear_trend_model.log_prob(y) # log_prob is scalar +``` + +Passing additional parameter dimensions constructs a batch of models. The +overall batch shape is the broadcast batch shape of the parameters: + +```python +linear_trend_model = LocalLinearTrendStateSpaceModel( + num_timesteps=50, + level_scale=tf.ones([10]), + slope_scale=0.5, + initial_state_prior=tfd.MultivariateNormalDiag( + scale_diag=tf.ones([10, 10, 2]))) + +y = linear_trend_model.sample(5) # y has shape [5, 10, 10, 50, 1] +lp = linear_trend_model.log_prob(y) # has shape [5, 10, 10] +``` + +

__init__

+ +``` python +__init__( + num_timesteps, + level_scale, + slope_scale, + initial_state_prior, + observation_noise_scale=0.0, + initial_step=0, + validate_args=False, + allow_nan_stats=True, + name=None +) +``` + +Build a state space model implementing a local linear trend. + +#### Args: + +* `num_timesteps`: Scalar `int` `Tensor` number of timesteps to model + with this distribution. +* `level_scale`: Scalar (any additional dimensions are treated as batch + dimensions) `float` `Tensor` indicating the standard deviation of the + level transitions. +* `slope_scale`: Scalar (any additional dimensions are treated as batch + dimensions) `float` `Tensor` indicating the standard deviation of the + slope transitions. +* `initial_state_prior`: instance of `tfd.MultivariateNormal` + representing the prior distribution on latent states; must + have event shape `[2]`. +* `observation_noise_scale`: Scalar (any additional dimensions are + treated as batch dimensions) `float` `Tensor` indicating the standard + deviation of the observation noise. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `validate_args`: Python `bool`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are + invalid, correct behavior is not guaranteed. + Default value: `False`. +* `allow_nan_stats`: Python `bool`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member. If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. + Default value: `True`. +* `name`: Python `str` name prefixed to ops created by this class. + Default value: "LocalLinearTrendStateSpaceModel". + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

level_scale

+ +Standard deviation of the level transitions. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

observation_noise_scale

+ +Standard deviation of the observation noise. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

slope_scale

+ +Standard deviation of the slope transitions. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

forward_filter

+ +``` python +forward_filter(x) +``` + +Run a Kalman filter over a provided sequence of outputs. + +Note that the returned values `filtered_means`, `predicted_means`, and +`observation_means` depend on the observed time series `x`, while the +corresponding covariances are independent of the observed series; i.e., they +depend only on the model itself. This means that the mean values have shape +`concat([sample_shape(x), batch_shape, [num_timesteps, +{latent/observation}_size]])`, while the covariances have shape +`concat[(batch_shape, [num_timesteps, {latent/observation}_size, +{latent/observation}_size]])`, which does not depend on the sample shape. + +#### Args: + +* `x`: a float-type `Tensor` with rightmost dimensions + `[num_timesteps, observation_size]` matching + `self.event_shape`. Additional dimensions must match or be + broadcastable to `self.batch_shape`; any further dimensions + are interpreted as a sample shape. + + +#### Returns: + +* `log_likelihoods`: Per-timestep log marginal likelihoods `log + p(x_t | x_{:t-1})` evaluated at the input `x`, as a `Tensor` + of shape `sample_shape(x) + batch_shape + [num_timesteps].` +* `filtered_means`: Means of the per-timestep filtered marginal + distributions p(z_t | x_{:t}), as a Tensor of shape + `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`. +* `filtered_covs`: Covariances of the per-timestep filtered marginal + distributions p(z_t | x_{:t}), as a Tensor of shape + `batch_shape + [num_timesteps, latent_size, latent_size]`. +* `predicted_means`: Means of the per-timestep predictive + distributions over latent states, p(z_{t+1} | x_{:t}), as a + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, latent_size]`. +* `predicted_covs`: Covariances of the per-timestep predictive + distributions over latent states, p(z_{t+1} | x_{:t}), as a + Tensor of shape `batch_shape + [num_timesteps, latent_size, + latent_size]`. +* `observation_means`: Means of the per-timestep predictive + distributions over observations, p(x_{t} | x_{:t-1}), as a + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, observation_size]`. +* `observation_covs`: Covariances of the per-timestep predictive + distributions over observations, p(x_{t} | x_{:t-1}), as a + Tensor of shape `batch_shape + [num_timesteps, + observation_size, observation_size]`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/Seasonal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/Seasonal.md new file mode 100644 index 0000000000..45ab1d7528 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/Seasonal.md @@ -0,0 +1,291 @@ +
+ + + + + + + + + + + + + + +
+ +# tfp.sts.Seasonal + +## Class `Seasonal` + +Inherits From: [`StructuralTimeSeries`](../../tfp/sts/StructuralTimeSeries.md) + +Formal representation of a seasonal effect model. + +A seasonal effect model posits a fixed set of recurring, discrete 'seasons', +each of which is active for a fixed number of timesteps and, while active, +contributes a different effect to the time series. These are generally not +meteorological seasons, but represent regular recurring patterns such as +hour-of-day or day-of-week effects. Each season lasts for a fixed number of +timesteps. The effect of each season drifts from one occurrence to the next +following a Gaussian random walk: + +```python +effects[season, occurrence[i]] = ( + effects[season, occurrence[i-1]] + Normal(loc=0., scale=drift_scale)) +``` + +The `drift_scale` parameter governs the standard deviation of the random walk; +for example, in a day-of-week model it governs the change in effect from this +Monday to next Monday. + +#### Examples + +A seasonal effect model representing day-of-week seasonality on hourly data: + +```python +day_of_week = tfp.sts.Seasonal(num_seasons=7, + num_steps_per_season=24, + observed_time_series=y, + name='day_of_week') +``` + +A seasonal effect model representing month-of-year seasonality on daily data, +with explicit priors: + +```python +month_of_year = tfp.sts.Seasonal( + num_seasons=12, + num_steps_per_season=[31, 28, 31, 30, 30, 31, 31, 31, 30, 31, 30, 31], + drift_scale_prior=tfd.LogNormal(loc=-1., scale=0.1), + initial_effect_prior=tf.Normal(loc=0., scale=5.), + name='month_of_year') +``` + +Note that a general implementation of month-of-year seasonality would require +additional logic; this version works over time periods not involving a leap +year. + +A model representing both day-of-week and hour-of-day seasonality, on hourly +data: + +``` +day_of_week = tfp.sts.Seasonal(num_seasons=7, + num_steps_per_season=24, + observed_time_series=y, + name='day_of_week') +hour_of_day = tfp.sts.Seasonal(num_seasons=24, + num_steps_per_season=1, + observed_time_series=y, + name='hour_of_day') +model = tfp.sts.Sum(components=[day_of_week, hour_of_day], + observed_time_series=y) +``` + +

__init__

+ +``` python +__init__( + num_seasons, + num_steps_per_season=1, + drift_scale_prior=None, + initial_effect_prior=None, + observed_time_series=None, + name=None +) +``` + +Specify a seasonal effects model. + +#### Args: + +* `num_seasons`: Scalar Python `int` number of seasons. +* `num_steps_per_season`: Python `int` number of steps in each + season. This may be either a scalar (shape `[]`), in which case all + seasons have the same length, or a NumPy array of shape `[num_seasons]`. + Default value: 1. +* `drift_scale_prior`: optional `tfd.Distribution` instance specifying a prior + on the `drift_scale` parameter. If `None`, a heuristic default prior is + constructed based on the provided `observed_time_series`. + Default value: `None`. +* `initial_effect_prior`: optional `tfd.Distribution` instance specifying a + normal prior on the initial effect of each season. This may be either + a scalar `tfd.Normal` prior, in which case it applies independently to + every season, or it may be multivariate normal (e.g., + `tfd.MultivariateNormalDiag`) with event shape `[num_seasons]`, in + which case it specifies a joint prior across all seasons. If `None`, a + heuristic default prior is constructed based on the provided + `observed_time_series`. + Default value: `None`. +* `observed_time_series`: optional `float` `Tensor` of shape + `batch_shape + [T, 1]` (omitting the trailing unit dimension is also + supported when `T > 1`), specifying an observed time series. + Any priors not explicitly set will be given default values according to + the scale of the observed time series (or batch of time series). + Default value: `None`. +* `name`: the name of this model component. + Default value: 'Seasonal'. + + + +## Properties + +

batch_shape

+ +Static batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: A `tf.TensorShape` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape`. It may be partially + defined or unknown. + +

initial_state_prior

+ +Prior distribution on the initial latent state (level and scale). + +

latent_size

+ +Python `int` dimensionality of the latent space in this model. + +

name

+ +Name of this model component. + +

num_seasons

+ +Number of seasons. + +

num_steps_per_season

+ +Number of steps per season. + +

parameters

+ +List of Parameter(name, prior, bijector) namedtuples for this model. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor() +``` + +Runtime batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: `int` `Tensor` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape_tensor()`. + +

joint_log_prob

+ +``` python +joint_log_prob(observed_time_series) +``` + +Build the joint density `log p(params) + log p(y|params)` as a callable. + +#### Args: + +* `observed_time_series`: Observed `Tensor` trajectories of shape + `sample_shape + batch_shape + [num_timesteps, 1]` (the trailing + `1` dimension is optional if `num_timesteps > 1`), where + `batch_shape` should match `self.batch_shape` (the broadcast batch + shape of all priors on parameters for this structural time series + model). + + +#### Returns: + +log_joint_fn: A function taking a `Tensor` argument for each model + parameter, in canonical order, and returning a `Tensor` log probability + of shape `batch_shape`. Note that, *unlike* `tfp.Distributions` + `log_prob` methods, the `log_joint` sums over the `sample_shape` from y, + so that `sample_shape` does not appear in the output log_prob. This + corresponds to viewing multiple samples in `y` as iid observations from a + single model, which is typically the desired behavior for parameter + inference. + +

make_state_space_model

+ +``` python +make_state_space_model( + num_timesteps, + param_vals=None, + initial_state_prior=None, + initial_step=0 +) +``` + +Instantiate this model as a Distribution over specified `num_timesteps`. + +#### Args: + +* `num_timesteps`: Python `int` number of timesteps to model. +* `param_vals`: a list of `Tensor` parameter values in order corresponding to + `self.parameters`, or a dict mapping from parameter names to values. +* `initial_state_prior`: an optional `Distribution` instance overriding the + default prior on the model's initial state. This is used in forecasting + ("today's prior is yesterday's posterior"). +* `initial_step`: optional `int` specifying the initial timestep to model. + This is relevant when the model contains time-varying components, + e.g., holidays or seasonality. + + +#### Returns: + +* `dist`: a `LinearGaussianStateSpaceModel` Distribution object. + +

prior_sample

+ +``` python +prior_sample( + num_timesteps, + initial_step=0, + params_sample_shape=(), + trajectories_sample_shape=(), + seed=None +) +``` + +Sample from the joint prior over model parameters and trajectories. + +#### Args: + +* `num_timesteps`: Scalar `int` `Tensor` number of timesteps to model. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `params_sample_shape`: Number of possible worlds to sample iid from the + parameter prior, or more generally, `Tensor` `int` shape to fill with + iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `trajectories_sample_shape`: For each sampled set of parameters, number + of trajectories to sample, or more generally, `Tensor` `int` shape to + fill with iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `seed`: Python `int` random seed. + + +#### Returns: + +* `trajectories`: `float` `Tensor` of shape + `trajectories_sample_shape + params_sample_shape + [num_timesteps, 1]` + containing all sampled trajectories. +* `param_samples`: list of sampled parameter value `Tensor`s, in order + corresponding to `self.parameters`, each of shape + `params_sample_shape + prior.batch_shape + prior.event_shape`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/SeasonalStateSpaceModel.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/SeasonalStateSpaceModel.md new file mode 100644 index 0000000000..5b87b1d1a7 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/SeasonalStateSpaceModel.md @@ -0,0 +1,917 @@ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +# tfp.sts.SeasonalStateSpaceModel + +## Class `SeasonalStateSpaceModel` + +Inherits From: [`LinearGaussianStateSpaceModel`](../../tfp/distributions/LinearGaussianStateSpaceModel.md) + +State space model for a seasonal effect. + +A state space model (SSM) posits a set of latent (unobserved) variables that +evolve over time with dynamics specified by a probabilistic transition model +`p(z[t+1] | z[t])`. At each timestep, we observe a value sampled from an +observation model conditioned on the current state, `p(x[t] | z[t])`. The +special case where both the transition and observation models are Gaussians +with mean specified as a linear function of the inputs, is known as a linear +Gaussian state space model and supports tractable exact probabilistic +calculations; see tfp.distributions.LinearGaussianStateSpaceModel for +details. + +A seasonal effect model is a special case of a linear Gaussian SSM. The +latent states represent an unknown effect from each of several 'seasons'; +these are generally not meteorological seasons, but represent regular +recurring patterns such as hour-of-day or day-of-week effects. The effect of +each season drifts from one occurrence to the next, following a Gaussian +random walk: + +```python +effects[season, occurrence[i]] = ( + effects[season, occurrence[i-1]] + Normal(loc=0., scale=drift_scale)) +``` + +The latent state has dimension `num_seasons`, containing one effect for each +seasonal component. The parameters `drift_scale` and +`observation_noise_scale` are each (a batch of) scalars. The batch shape of +this `Distribution` is the broadcast batch shape of these parameters and of +the `initial_state_prior`. + +#### Mathematical Details + +The seasonal effect model implements a +tfp.distributions.LinearGaussianStateSpaceModel with +`latent_size = num_seasons` and `observation_size = 1`. The latent state +is organized so that the *current* seasonal effect is always in the first +(zeroth) dimension. The transition model rotates the latent state to shift +to a new effect at the end of each season: + +``` +transition_matrix[t] = (permutation_matrix([1, 2, ..., num_seasons-1, 0]) + if season_is_changing(t) + else eye(num_seasons) +transition_noise[t] ~ Normal(loc=0., scale_diag=( + [drift_scale, 0, ..., 0] + if season_is_changing(t) + else [0, 0, ..., 0])) +``` + +where `season_is_changing(t)` is `True` if ``t `mod` +sum(num_steps_per_season)`` is in the set of final days for each season, +given by `cumsum(num_steps_per_season) - 1`. The observation model always +picks out the effect for the current season, i.e., the first element of +the latent state: + +``` +observation_matrix = [[1., 0., ..., 0.]] +observation_noise ~ Normal(loc=0, scale=observation_noise_scale) +``` + +#### Examples + +A state-space model with day-of-week seasonality on hourly data: + +```python +day_of_week = SeasonalStateSpaceModel( + num_timesteps=30, + num_seasons=7, + drift_scale=0.1, + initial_state_prior=tfd.MultivariateNormalDiag( + scale_diag=tf.ones([7], dtype=tf.float32), + num_steps_per_season=24) +``` + +A model with basic month-of-year seasonality on daily data, demonstrating +seasons of varying length: + +```python +month_of_year = SeasonalStateSpaceModel( + num_timesteps=2 * 365, # 2 years + num_seasons=12, + drift_scale=0.1, + initial_state_prior=tfd.MultivariateNormalDiag( + scale_diag=tf.ones([12], dtype=tf.float32)), + num_steps_per_season=[31, 28, 31, 30, 30, 31, 31, 31, 30, 31, 30, 31], + initial_step=22) +``` + +Note that we've used `initial_step=22` to denote that the model begins +on January 23 (steps are zero-indexed). A general implementation of +month-of-year seasonality would require additional logic; this +version works over time periods not involving a leap year. + +

__init__

+ +``` python +__init__( + num_timesteps, + num_seasons, + drift_scale, + initial_state_prior, + observation_noise_scale=0.0, + num_steps_per_season=1, + initial_step=0, + validate_args=False, + allow_nan_stats=True, + name=None +) +``` + +Build a state space model implementing seasonal effects. + +#### Args: + +* `num_timesteps`: Scalar `int` `Tensor` number of timesteps to model + with this distribution. +* `num_seasons`: Scalar Python `int` number of seasons. +* `drift_scale`: Scalar (any additional dimensions are treated as batch + dimensions) `float` `Tensor` indicating the standard deviation of the + change in effect between consecutive occurrences of a given season. + This is assumed to be the same for all seasons. +* `initial_state_prior`: instance of `tfd.MultivariateNormal` + representing the prior distribution on latent states; must + have event shape `[num_seasons]`. +* `observation_noise_scale`: Scalar (any additional dimensions are + treated as batch dimensions) `float` `Tensor` indicating the standard + deviation of the observation noise. + Default value: 0. +* `num_steps_per_season`: Python `int` number of steps in each + season. This may be either a scalar (shape `[]`), in which case all + seasons have the same length, or a NumPy array of shape `[num_seasons]`. + Default value: 1. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `validate_args`: Python `bool`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are + invalid, correct behavior is not guaranteed. + Default value: `False`. +* `allow_nan_stats`: Python `bool`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member. If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. + Default value: `True`. +* `name`: Python `str` name prefixed to ops created by this class. + Default value: "SeasonalStateSpaceModel". + + +#### Raises: + +* `ValueError`: if `num_steps_per_season` has invalid shape (neither + scalar nor `[num_seasons]`). + + + +## Properties + +

allow_nan_stats

+ +Python `bool` describing behavior when a stat is undefined. + +Stats return +/- infinity when it makes sense. E.g., the variance of a +Cauchy distribution is infinity. However, sometimes the statistic is +undefined, e.g., if a distribution's pdf does not achieve a maximum within +the support of the distribution, the mode is undefined. If the mean is +undefined, then by definition the variance is undefined. E.g. the mean for +Student's T for df = 1 is undefined (no clear way to say it is either + or - +infinity), so the variance = E[(X - mean)**2] is also undefined. + +#### Returns: + +* `allow_nan_stats`: Python `bool`. + +

batch_shape

+ +Shape of a single sample from a single event index as a `TensorShape`. + +May be partially defined or unknown. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Returns: + +* `batch_shape`: `TensorShape`, possibly unknown. + +

drift_scale

+ +Standard deviation of the drift in effects between seasonal cycles. + +

dtype

+ +The `DType` of `Tensor`s handled by this `Distribution`. + +

event_shape

+ +Shape of a single sample from a single batch as a `TensorShape`. + +May be partially defined or unknown. + +#### Returns: + +* `event_shape`: `TensorShape`, possibly unknown. + +

name

+ +Name prepended to all ops created by this `Distribution`. + +

num_seasons

+ +Number of seasons. + +

num_steps_per_season

+ +Number of steps in each season. + +

observation_noise_scale

+ +Standard deviation of the observation noise. + +

parameters

+ +Dictionary of parameters used to instantiate this `Distribution`. + +

reparameterization_type

+ +Describes how samples from the distribution are reparameterized. + +Currently this is one of the static instances +`distributions.FULLY_REPARAMETERIZED` +or `distributions.NOT_REPARAMETERIZED`. + +#### Returns: + +An instance of `ReparameterizationType`. + +

validate_args

+ +Python `bool` indicating possibly expensive checks are enabled. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor(name='batch_shape_tensor') +``` + +Shape of a single sample from a single event index as a 1-D `Tensor`. + +The batch dimensions are indexes into independent, non-identical +parameterizations of this distribution. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `batch_shape`: `Tensor`. + +

cdf

+ +``` python +cdf( + value, + name='cdf' +) +``` + +Cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +cdf(x) := P[X <= x] +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

copy

+ +``` python +copy(**override_parameters_kwargs) +``` + +Creates a deep copy of the distribution. + +Note: the copy distribution may continue to depend on the original +initialization arguments. + +#### Args: + +* `**override_parameters_kwargs`: String/value dictionary of initialization + arguments to override with new values. + + +#### Returns: + +* `distribution`: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + +

covariance

+ +``` python +covariance(name='covariance') +``` + +Covariance. + +Covariance is (possibly) defined only for non-scalar-event distributions. + +For example, for a length-`k`, vector-valued distribution, it is calculated +as, + +```none +Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] +``` + +where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` +denotes expectation. + +Alternatively, for non-vector, multivariate distributions (e.g., +matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices +under some vectorization of the events, i.e., + +```none +Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] +``` + +where `Cov` is a (batch of) `k' x k'` matrices, +`0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function +mapping indices of this distribution's event dimensions to indices of a +length-`k'` vector. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `covariance`: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + +

cross_entropy

+ +``` python +cross_entropy( + other, + name='cross_entropy' +) +``` + +Computes the (Shannon) cross entropy. + +Denote this distribution (`self`) by `P` and the `other` distribution by +`Q`. Assuming `P, Q` are absolutely continuous with respect to +one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) +cross entropy is defined as: + +```none +H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) +``` + +where `F` denotes the support of the random variable `X ~ P`. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `cross_entropy`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + +

entropy

+ +``` python +entropy(name='entropy') +``` + +Shannon entropy in nats. + +

event_shape_tensor

+ +``` python +event_shape_tensor(name='event_shape_tensor') +``` + +Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + +#### Args: + +* `name`: name to give to the op + + +#### Returns: + +* `event_shape`: `Tensor`. + +

forward_filter

+ +``` python +forward_filter(x) +``` + +Run a Kalman filter over a provided sequence of outputs. + +Note that the returned values `filtered_means`, `predicted_means`, and +`observation_means` depend on the observed time series `x`, while the +corresponding covariances are independent of the observed series; i.e., they +depend only on the model itself. This means that the mean values have shape +`concat([sample_shape(x), batch_shape, [num_timesteps, +{latent/observation}_size]])`, while the covariances have shape +`concat[(batch_shape, [num_timesteps, {latent/observation}_size, +{latent/observation}_size]])`, which does not depend on the sample shape. + +#### Args: + +* `x`: a float-type `Tensor` with rightmost dimensions + `[num_timesteps, observation_size]` matching + `self.event_shape`. Additional dimensions must match or be + broadcastable to `self.batch_shape`; any further dimensions + are interpreted as a sample shape. + + +#### Returns: + +* `log_likelihoods`: Per-timestep log marginal likelihoods `log + p(x_t | x_{:t-1})` evaluated at the input `x`, as a `Tensor` + of shape `sample_shape(x) + batch_shape + [num_timesteps].` +* `filtered_means`: Means of the per-timestep filtered marginal + distributions p(z_t | x_{:t}), as a Tensor of shape + `sample_shape(x) + batch_shape + [num_timesteps, latent_size]`. +* `filtered_covs`: Covariances of the per-timestep filtered marginal + distributions p(z_t | x_{:t}), as a Tensor of shape + `batch_shape + [num_timesteps, latent_size, latent_size]`. +* `predicted_means`: Means of the per-timestep predictive + distributions over latent states, p(z_{t+1} | x_{:t}), as a + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, latent_size]`. +* `predicted_covs`: Covariances of the per-timestep predictive + distributions over latent states, p(z_{t+1} | x_{:t}), as a + Tensor of shape `batch_shape + [num_timesteps, latent_size, + latent_size]`. +* `observation_means`: Means of the per-timestep predictive + distributions over observations, p(x_{t} | x_{:t-1}), as a + Tensor of shape `sample_shape(x) + batch_shape + + [num_timesteps, observation_size]`. +* `observation_covs`: Covariances of the per-timestep predictive + distributions over observations, p(x_{t} | x_{:t-1}), as a + Tensor of shape `batch_shape + [num_timesteps, + observation_size, observation_size]`. + +

is_scalar_batch

+ +``` python +is_scalar_batch(name='is_scalar_batch') +``` + +Indicates that `batch_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_batch`: `bool` scalar `Tensor`. + +

is_scalar_event

+ +``` python +is_scalar_event(name='is_scalar_event') +``` + +Indicates that `event_shape == []`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `is_scalar_event`: `bool` scalar `Tensor`. + +

kl_divergence

+ +``` python +kl_divergence( + other, + name='kl_divergence' +) +``` + +Computes the Kullback--Leibler divergence. + +Denote this distribution (`self`) by `p` and the `other` distribution by +`q`. Assuming `p, q` are absolutely continuous with respect to reference +measure `r`, the KL divergence is defined as: + +```none +KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] +``` + +where `F` denotes the support of the random variable `X ~ p`, `H[., .]` +denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + +#### Args: + +* `other`: tfp.distributions.Distribution instance. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `kl_divergence`: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + +

log_cdf

+ +``` python +log_cdf( + value, + name='log_cdf' +) +``` + +Log cumulative distribution function. + +Given random variable `X`, the cumulative distribution function `cdf` is: + +```none +log_cdf(x) := Log[ P[X <= x] ] +``` + +Often, a numerical approximation can be used for `log_cdf(x)` that yields +a more accurate answer than simply taking the logarithm of the `cdf` when +`x << -1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `logcdf`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_prob

+ +``` python +log_prob( + value, + name='log_prob' +) +``` + +Log probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `log_prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

log_survival_function

+ +``` python +log_survival_function( + value, + name='log_survival_function' +) +``` + +Log survival function. + +Given random variable `X`, the survival function is defined: + +```none +log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] +``` + +Typically, different numerical approximations can be used for the log +survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

mean

+ +``` python +mean(name='mean') +``` + +Mean. + +

mode

+ +``` python +mode(name='mode') +``` + +Mode. + +

param_shapes

+ +``` python +param_shapes( + cls, + sample_shape, + name='DistributionParamShapes' +) +``` + +Shapes of parameters given the desired shape of a call to `sample()`. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. + +Subclasses should override class method `_param_shapes`. + +#### Args: + +* `sample_shape`: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. +* `name`: name to prepend ops with. + + +#### Returns: + +`dict` of parameter name to `Tensor` shapes. + +

param_static_shapes

+ +``` python +param_static_shapes( + cls, + sample_shape +) +``` + +param_shapes with static (i.e. `TensorShape`) shapes. + +This is a class method that describes what key/value arguments are required +to instantiate the given `Distribution` so that a particular shape is +returned for that instance's call to `sample()`. Assumes that the sample's +shape is known statically. + +Subclasses should override class method `_param_shapes` to return +constant-valued tensors when constant values are fed. + +#### Args: + +* `sample_shape`: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + +#### Returns: + +`dict` of parameter name to `TensorShape`. + + +#### Raises: + +* `ValueError`: if `sample_shape` is a `TensorShape` and is not fully defined. + +

prob

+ +``` python +prob( + value, + name='prob' +) +``` + +Probability density/mass function. + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `prob`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

quantile

+ +``` python +quantile( + value, + name='quantile' +) +``` + +Quantile function. Aka "inverse cdf" or "percent point function". + +Given random variable `X` and `p in [0, 1]`, the `quantile` is: + +```none +quantile(p) := x such that P[X <= x] == p +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `quantile`: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + +

sample

+ +``` python +sample( + sample_shape=(), + seed=None, + name='sample' +) +``` + +Generate samples of the specified shape. + +Note that a call to `sample()` without arguments will generate a single +sample. + +#### Args: + +* `sample_shape`: 0D or 1D `int32` `Tensor`. Shape of the generated samples. +* `seed`: Python integer seed for RNG +* `name`: name to give to the op. + + +#### Returns: + +* `samples`: a `Tensor` with prepended dimensions `sample_shape`. + +

stddev

+ +``` python +stddev(name='stddev') +``` + +Standard deviation. + +Standard deviation is defined as, + +```none +stddev = E[(X - E[X])**2]**0.5 +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `stddev.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `stddev`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + +

survival_function

+ +``` python +survival_function( + value, + name='survival_function' +) +``` + +Survival function. + +Given random variable `X`, the survival function is defined: + +```none +survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). +``` + +#### Args: + +* `value`: `float` or `double` `Tensor`. +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +`Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + +

variance

+ +``` python +variance(name='variance') +``` + +Variance. + +Variance is defined as, + +```none +Var = E[(X - E[X])**2] +``` + +where `X` is the random variable associated with this distribution, `E` +denotes expectation, and `Var.shape = batch_shape + event_shape`. + +#### Args: + +* `name`: Python `str` prepended to names of ops created by this function. + + +#### Returns: + +* `variance`: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/StructuralTimeSeries.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/StructuralTimeSeries.md new file mode 100644 index 0000000000..92f1e61b90 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/StructuralTimeSeries.md @@ -0,0 +1,203 @@ +
+ + + + + + + + + + + +
+ +# tfp.sts.StructuralTimeSeries + +## Class `StructuralTimeSeries` + + + +Base class for structural time series models. + +A StructuralTimeSeries object represents a declarative specification of a +structural time series model, including priors on model parameters. +It implements a joint probability model + `p(params, y) = p(params) p(y | params)`, +where `params` denotes a list of real-valued parameters specified by the child +class, and `p(y | params)` is a linear Gaussian state space model with +structure determined by the child class. + +

__init__

+ +``` python +__init__( + parameters, + latent_size, + name='StructuralTimeSeries' +) +``` + +Construct a specification for a structural time series model. + +#### Args: + +* `parameters`: list of Parameter namedtuples, each specifying the name + and prior distribution of a model parameter along with a + bijective transformation from an unconstrained space to the support + of that parameter. The order of this list determines the canonical + parameter ordering used by fitting and inference algorithms. +* `latent_size`: Python `int` specifying the dimensionality of the latent + state space for this model. +* `name`: Python `str` name for this model component. + + + +## Properties + +

batch_shape

+ +Static batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: A `tf.TensorShape` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape`. It may be partially + defined or unknown. + +

latent_size

+ +Python `int` dimensionality of the latent space in this model. + +

name

+ +Name of this model component. + +

parameters

+ +List of Parameter(name, prior, bijector) namedtuples for this model. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor() +``` + +Runtime batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: `int` `Tensor` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape_tensor()`. + +

joint_log_prob

+ +``` python +joint_log_prob(observed_time_series) +``` + +Build the joint density `log p(params) + log p(y|params)` as a callable. + +#### Args: + +* `observed_time_series`: Observed `Tensor` trajectories of shape + `sample_shape + batch_shape + [num_timesteps, 1]` (the trailing + `1` dimension is optional if `num_timesteps > 1`), where + `batch_shape` should match `self.batch_shape` (the broadcast batch + shape of all priors on parameters for this structural time series + model). + + +#### Returns: + +log_joint_fn: A function taking a `Tensor` argument for each model + parameter, in canonical order, and returning a `Tensor` log probability + of shape `batch_shape`. Note that, *unlike* `tfp.Distributions` + `log_prob` methods, the `log_joint` sums over the `sample_shape` from y, + so that `sample_shape` does not appear in the output log_prob. This + corresponds to viewing multiple samples in `y` as iid observations from a + single model, which is typically the desired behavior for parameter + inference. + +

make_state_space_model

+ +``` python +make_state_space_model( + num_timesteps, + param_vals=None, + initial_state_prior=None, + initial_step=0 +) +``` + +Instantiate this model as a Distribution over specified `num_timesteps`. + +#### Args: + +* `num_timesteps`: Python `int` number of timesteps to model. +* `param_vals`: a list of `Tensor` parameter values in order corresponding to + `self.parameters`, or a dict mapping from parameter names to values. +* `initial_state_prior`: an optional `Distribution` instance overriding the + default prior on the model's initial state. This is used in forecasting + ("today's prior is yesterday's posterior"). +* `initial_step`: optional `int` specifying the initial timestep to model. + This is relevant when the model contains time-varying components, + e.g., holidays or seasonality. + + +#### Returns: + +* `dist`: a `LinearGaussianStateSpaceModel` Distribution object. + +

prior_sample

+ +``` python +prior_sample( + num_timesteps, + initial_step=0, + params_sample_shape=(), + trajectories_sample_shape=(), + seed=None +) +``` + +Sample from the joint prior over model parameters and trajectories. + +#### Args: + +* `num_timesteps`: Scalar `int` `Tensor` number of timesteps to model. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `params_sample_shape`: Number of possible worlds to sample iid from the + parameter prior, or more generally, `Tensor` `int` shape to fill with + iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `trajectories_sample_shape`: For each sampled set of parameters, number + of trajectories to sample, or more generally, `Tensor` `int` shape to + fill with iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `seed`: Python `int` random seed. + + +#### Returns: + +* `trajectories`: `float` `Tensor` of shape + `trajectories_sample_shape + params_sample_shape + [num_timesteps, 1]` + containing all sampled trajectories. +* `param_samples`: list of sampled parameter value `Tensor`s, in order + corresponding to `self.parameters`, each of shape + `params_sample_shape + prior.batch_shape + prior.event_shape`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/sts/Sum.md b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/Sum.md new file mode 100644 index 0000000000..0f959874b2 --- /dev/null +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/sts/Sum.md @@ -0,0 +1,263 @@ +
+ + + + + + + + + + + + + +
+ +# tfp.sts.Sum + +## Class `Sum` + +Inherits From: [`StructuralTimeSeries`](../../tfp/sts/StructuralTimeSeries.md) + +Sum of structural time series components. + +This class enables compositional specification of a structural time series +model from basic components. Given a list of component models, it represents +an additive model, i.e., a model of time series that may be decomposed into a +sum of terms corresponding to the component models. + +Formally, the additive model represents a random process +`g[t] = f1[t] + f2[t] + ... + fN[t] + eps[t]`, where the `f`'s are the +random processes represented by the components, and +`eps[t] ~ Normal(loc=0, scale=observation_noise_scale)` is an observation +noise term. See the `AdditiveStateSpaceModel` documentation for mathematical +details. + +This model inherits the parameters (with priors) of its components, and +adds an `observation_noise_scale` parameter governing the level of noise in +the observed time series. + +#### Examples + +To construct a model combining a local linear trend with a day-of-week effect: + +``` + local_trend = tfp.sts.LocalLinearTrend( + observed_time_series=observed_time_series, + name='local_trend') + day_of_week_effect = tfp.sts.Seasonal( + num_seasons=7, + observed_time_series=observed_time_series, + name='day_of_week_effect') + additive_model = tfp.sts.Sum( + components=[local_trend, day_of_week_effect], + observed_time_series=observed_time_series) + + print([p.name for p in additive_model.parameters]) + # => `[observation_noise_scale, + # local_trend_level_scale, + # local_trend_slope_scale, + # day_of_week_effect_drift_scale`] + + print(local_trend.latent_size, + seasonal.latent_size, + additive_model.latent_size) + # => `2`, `7`, `9` +``` + +

__init__

+ +``` python +__init__( + components, + observation_noise_scale_prior=None, + observed_time_series=None, + name=None +) +``` + +Specify a structural time series model representing a sum of components. + +#### Args: + +* `components`: Python `list` of one or more StructuralTimeSeries instances. + These must have unique names. +* `observation_noise_scale_prior`: optional `tfd.Distribution` instance + specifying a prior on `observation_noise_scale`. If `None`, a heuristic + default prior is constructed based on the provided + `observed_time_series`. + Default value: `None`. +* `observed_time_series`: optional `float` `Tensor` of shape + `batch_shape + [T, 1]` (omitting the trailing unit dimension is also + supported when `T > 1`), specifying an observed time series. This is + used only if `observation_noise_scale_prior` is not provided, to + construct a default heuristic prior. + Default value: `None`. +* `name`: Python `str` name of this model component; used as `name_scope` + for ops created by this class. + Default value: 'Sum'. + + +#### Raises: + +* `ValueError`: if components do not have unique names. + + + +## Properties + +

batch_shape

+ +Static batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: A `tf.TensorShape` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape`. It may be partially + defined or unknown. + +

components

+ +List of component `StructuralTimeSeries` models. + +

components_by_name

+ +OrderedDict mapping component names to components. + +

latent_size

+ +Python `int` dimensionality of the latent space in this model. + +

name

+ +Name of this model component. + +

parameters

+ +List of Parameter(name, prior, bijector) namedtuples for this model. + + + +## Methods + +

batch_shape_tensor

+ +``` python +batch_shape_tensor() +``` + +Runtime batch shape of models represented by this component. + +#### Returns: + +* `batch_shape`: `int` `Tensor` giving the broadcast batch shape of + all model parameters. This should match the batch shape of + derived state space models, i.e., + `self.make_state_space_model(...).batch_shape_tensor()`. + +

joint_log_prob

+ +``` python +joint_log_prob(observed_time_series) +``` + +Build the joint density `log p(params) + log p(y|params)` as a callable. + +#### Args: + +* `observed_time_series`: Observed `Tensor` trajectories of shape + `sample_shape + batch_shape + [num_timesteps, 1]` (the trailing + `1` dimension is optional if `num_timesteps > 1`), where + `batch_shape` should match `self.batch_shape` (the broadcast batch + shape of all priors on parameters for this structural time series + model). + + +#### Returns: + +log_joint_fn: A function taking a `Tensor` argument for each model + parameter, in canonical order, and returning a `Tensor` log probability + of shape `batch_shape`. Note that, *unlike* `tfp.Distributions` + `log_prob` methods, the `log_joint` sums over the `sample_shape` from y, + so that `sample_shape` does not appear in the output log_prob. This + corresponds to viewing multiple samples in `y` as iid observations from a + single model, which is typically the desired behavior for parameter + inference. + +

make_state_space_model

+ +``` python +make_state_space_model( + num_timesteps, + param_vals=None, + initial_state_prior=None, + initial_step=0 +) +``` + +Instantiate this model as a Distribution over specified `num_timesteps`. + +#### Args: + +* `num_timesteps`: Python `int` number of timesteps to model. +* `param_vals`: a list of `Tensor` parameter values in order corresponding to + `self.parameters`, or a dict mapping from parameter names to values. +* `initial_state_prior`: an optional `Distribution` instance overriding the + default prior on the model's initial state. This is used in forecasting + ("today's prior is yesterday's posterior"). +* `initial_step`: optional `int` specifying the initial timestep to model. + This is relevant when the model contains time-varying components, + e.g., holidays or seasonality. + + +#### Returns: + +* `dist`: a `LinearGaussianStateSpaceModel` Distribution object. + +

prior_sample

+ +``` python +prior_sample( + num_timesteps, + initial_step=0, + params_sample_shape=(), + trajectories_sample_shape=(), + seed=None +) +``` + +Sample from the joint prior over model parameters and trajectories. + +#### Args: + +* `num_timesteps`: Scalar `int` `Tensor` number of timesteps to model. +* `initial_step`: Optional scalar `int` `Tensor` specifying the starting + timestep. + Default value: 0. +* `params_sample_shape`: Number of possible worlds to sample iid from the + parameter prior, or more generally, `Tensor` `int` shape to fill with + iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `trajectories_sample_shape`: For each sampled set of parameters, number + of trajectories to sample, or more generally, `Tensor` `int` shape to + fill with iid samples. + Default value: [] (i.e., draw a single sample and don't expand the + shape). +* `seed`: Python `int` random seed. + + +#### Returns: + +* `trajectories`: `float` `Tensor` of shape + `trajectories_sample_shape + params_sample_shape + [num_timesteps, 1]` + containing all sampled trajectories. +* `param_samples`: list of sampled parameter value `Tensor`s, in order + corresponding to `self.parameters`, each of shape + `params_sample_shape + prior.batch_shape + prior.event_shape`. + + + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions.md index 64ed653059..d9ecebfb36 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions.md @@ -1,5 +1,6 @@
+ @@ -10,7 +11,7 @@ Trainable distributions. -"Trainable distributions" are instances of `tfp.distributions` which are +"Trainable distributions" are instances of tfp.distributions which are parameterized by a transformation of a single input `Tensor`. The transformations are presumed to use TensorFlow variables and typically need to be fit, e.g., using `tf.train` optimizers or `tfp.optimizers`. @@ -31,11 +32,11 @@ be fit, e.g., using `tf.train` optimizers or `tfp.optimizers`. ## Other Members -`__all__` +

__all__

-`absolute_import` +

absolute_import

-`division` +

division

-`print_function` + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/bernoulli.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/bernoulli.md index 0a569cf9c6..022fe1bc18 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/bernoulli.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/bernoulli.md @@ -1,5 +1,6 @@
+
# tfp.trainable_distributions.bernoulli diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/multivariate_normal_tril.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/multivariate_normal_tril.md index 6e033c41ee..8b6b90489e 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/multivariate_normal_tril.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/multivariate_normal_tril.md @@ -1,5 +1,6 @@
+
# tfp.trainable_distributions.multivariate_normal_tril diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/normal.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/normal.md index 2ae2d9e814..074e2856e9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/normal.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/normal.md @@ -1,5 +1,6 @@
+
# tfp.trainable_distributions.normal diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/poisson.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/poisson.md index 762e353ba1..25815dd92f 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/poisson.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/poisson.md @@ -1,5 +1,6 @@
+
# tfp.trainable_distributions.poisson diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/softplus_and_shift.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/softplus_and_shift.md index 3342660bf4..679a661fe0 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/softplus_and_shift.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/softplus_and_shift.md @@ -1,5 +1,6 @@
+
# tfp.trainable_distributions.softplus_and_shift diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/tril_with_diag_softplus_and_shift.md b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/tril_with_diag_softplus_and_shift.md index 5da2399233..4f008d5bc9 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/tril_with_diag_softplus_and_shift.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/trainable_distributions/tril_with_diag_softplus_and_shift.md @@ -1,5 +1,6 @@
+
# tfp.trainable_distributions.tril_with_diag_softplus_and_shift diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/util.md b/tensorflow_probability/g3doc/api_docs/python/tfp/util.md index 101f3d5d8e..a68e7cd50b 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/util.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/util.md @@ -1,5 +1,6 @@
+
# Module: tfp.util diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring.md b/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring.md index a3cc623f15..1dfdff213d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring.md @@ -1,5 +1,6 @@
+ @@ -16,11 +17,11 @@ Utilities for programmable docstrings. ## Other Members -`__all__` +

__all__

-`absolute_import` +

absolute_import

-`division` +

division

-`print_function` + diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring/expand_docstring.md b/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring/expand_docstring.md index 9d300c0a2f..8cd96d2c38 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring/expand_docstring.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/util/docstring/expand_docstring.md @@ -1,5 +1,6 @@
+
# tfp.util.docstring.expand_docstring diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/util/externalize_variables_as_args.md b/tensorflow_probability/g3doc/api_docs/python/tfp/util/externalize_variables_as_args.md index 7c09f0f966..7aa17514e7 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/util/externalize_variables_as_args.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/util/externalize_variables_as_args.md @@ -1,5 +1,6 @@
+
# tfp.util.externalize_variables_as_args diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi.md index eb328f4743..6dc0312801 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi.md @@ -1,5 +1,6 @@
+
# Module: tfp.vi diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/amari_alpha.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/amari_alpha.md index 917918c91d..18699bd10c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/amari_alpha.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/amari_alpha.md @@ -1,5 +1,6 @@
+
# tfp.vi.amari_alpha diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/arithmetic_geometric.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/arithmetic_geometric.md index d969c13333..e08a94a14c 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/arithmetic_geometric.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/arithmetic_geometric.md @@ -1,5 +1,6 @@
+
# tfp.vi.arithmetic_geometric diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/chi_square.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/chi_square.md index a1e84a44bd..12256c9d73 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/chi_square.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/chi_square.md @@ -1,5 +1,6 @@
+
# tfp.vi.chi_square diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco.md index c1ae923bd9..e291ab5d11 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco.md @@ -1,5 +1,6 @@
+
# tfp.vi.csiszar_vimco diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco_helper.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco_helper.md index 14b4cc44e0..2b5fdc0700 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco_helper.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/csiszar_vimco_helper.md @@ -1,5 +1,6 @@
+
# tfp.vi.csiszar_vimco_helper diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/dual_csiszar_function.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/dual_csiszar_function.md index 86f372262a..0ed8583297 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/dual_csiszar_function.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/dual_csiszar_function.md @@ -1,5 +1,6 @@
+
# tfp.vi.dual_csiszar_function diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jeffreys.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jeffreys.md index 74723b65a2..82a0bc5fb6 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jeffreys.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jeffreys.md @@ -1,5 +1,6 @@
+
# tfp.vi.jeffreys diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jensen_shannon.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jensen_shannon.md index ed242c569a..6c8a2dc7e8 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jensen_shannon.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/jensen_shannon.md @@ -1,5 +1,6 @@
+
# tfp.vi.jensen_shannon diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_forward.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_forward.md index 45451be136..f3c106fe96 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_forward.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_forward.md @@ -1,5 +1,6 @@
+
# tfp.vi.kl_forward diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_reverse.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_reverse.md index 4463b76485..01aaf69e44 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_reverse.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/kl_reverse.md @@ -1,5 +1,6 @@
+
# tfp.vi.kl_reverse diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/log1p_abs.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/log1p_abs.md index 34b7a4068e..a484634ead 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/log1p_abs.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/log1p_abs.md @@ -1,5 +1,6 @@
+
# tfp.vi.log1p_abs diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/modified_gan.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/modified_gan.md index 7285028456..ac913067c7 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/modified_gan.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/modified_gan.md @@ -1,5 +1,6 @@
+
# tfp.vi.modified_gan diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/monte_carlo_csiszar_f_divergence.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/monte_carlo_csiszar_f_divergence.md index ce238294ad..8ebf4eba72 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/monte_carlo_csiszar_f_divergence.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/monte_carlo_csiszar_f_divergence.md @@ -1,5 +1,6 @@
+
# tfp.vi.monte_carlo_csiszar_f_divergence diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/pearson.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/pearson.md index 69f8c7c018..f4ff4f1597 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/pearson.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/pearson.md @@ -1,5 +1,6 @@
+
# tfp.vi.pearson diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/squared_hellinger.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/squared_hellinger.md index 69ec1aae53..cf76784521 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/squared_hellinger.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/squared_hellinger.md @@ -1,5 +1,6 @@
+
# tfp.vi.squared_hellinger diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/symmetrized_csiszar_function.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/symmetrized_csiszar_function.md index bb3e526405..3c20909803 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/symmetrized_csiszar_function.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/symmetrized_csiszar_function.md @@ -1,5 +1,6 @@
+
# tfp.vi.symmetrized_csiszar_function diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/t_power.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/t_power.md index 87eec44095..21eea22279 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/t_power.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/t_power.md @@ -1,5 +1,6 @@
+
# tfp.vi.t_power diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/total_variation.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/total_variation.md index d9ece2cc03..91de746a3d 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/total_variation.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/total_variation.md @@ -1,5 +1,6 @@
+
# tfp.vi.total_variation diff --git a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/triangular.md b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/triangular.md index c9ae23de43..f87289bf65 100644 --- a/tensorflow_probability/g3doc/api_docs/python/tfp/vi/triangular.md +++ b/tensorflow_probability/g3doc/api_docs/python/tfp/vi/triangular.md @@ -1,5 +1,6 @@
+
# tfp.vi.triangular