tfp.layers.IndependentBernoulli

Class IndependentBernoulli

Inherits From: DistributionLambda

An Independent-Bernoulli Keras layer from prod(event_shape) params.

Typical choices for convert_to_tensor_fn include:

  • tfd.Distribution.sample
  • tfd.Distribution.mean
  • tfd.Distribution.mode
  • tfd.Bernoulli.logits

Example

tfk = tf.keras
tfkl = tf.keras.layers
tfd = tfp.distributions
tfpl = tfp.layers

# Load data.
n = int(1e4)
scale_tril = np.array([[1.6180, 0.],
                       [-2.7183, 3.1416]]).astype(np.float32)
scale_noise = 0.01
x = tfd.Normal(loc=0, scale=1).sample([n, 2])
eps = tfd.Normal(loc=0, scale=scale_noise).sample([n, 2])
y = tfd.Bernoulli(logits=tf.reshape(
    tf.matmul(x, scale_tril) + eps,
    shape=[n, 1, 2, 1])).sample()

# Create model.
event_shape = y.shape[1:].as_list()
model = tfk.Sequential([
    tfkl.Dense(tfpl.IndependentBernoulli.params_size(event_shape)),
    tfpl.IndependentBernoulli(event_shape),
])

# Fit.
model.compile(optimizer=tf.train.AdamOptimizer(learning_rate=0.5),
              loss=lambda y, model: -model.log_prob(y),
              metrics=[])
batch_size = 100
model.fit(x, y,
          batch_size=batch_size,
          epochs=10,
          steps_per_epoch=n // batch_size,
          shuffle=True)
print(model.get_weights())
# ==> [np.array([[1.6180, 0.],
#                [-2.7183, 3.1416]], np.float32),
#      array([0., 0.], np.float32)]   # Within 15% rel. error.

__init__

__init__(
    event_shape=(),
    convert_to_tensor_fn=tfd.Distribution.sample,
    sample_dtype=None,
    validate_args=False,
    **kwargs
)

Initialize the IndependentBernoulli layer.

Args:

  • event_shape: integer vector Tensor representing the shape of single draw from this distribution.
  • convert_to_tensor_fn: Python callable that takes a tfd.Distribution instance and returns a tf.Tensor-like object. For examples, see class docstring. Default value: tfd.Distribution.sample.
  • sample_dtype: dtype of samples produced by this distribution. Default value: None (i.e., previous layer's dtype).
  • 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.
  • **kwargs: Additional keyword arguments passed to tf.keras.Layer.

Properties

activity_regularizer

Optional regularizer function for the output of this layer.

dtype

dynamic

input

Retrieves the input tensor(s) of a layer.

Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer.

Returns:

Input tensor or list of input tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.

Raises:

  • RuntimeError: If called in Eager mode.
  • AttributeError: If no inbound nodes are found.

input_mask

Retrieves the input mask tensor(s) of a layer.

Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.

Returns:

Input mask tensor (potentially None) or list of input mask tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.

input_shape

Retrieves the input shape(s) of a layer.

Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer, or if all inputs have the same shape.

Returns:

Input shape, as an integer shape tuple (or list of shape tuples, one tuple per input tensor).

Raises:

  • AttributeError: if the layer has no defined input_shape.
  • RuntimeError: if called in Eager mode.

losses

Losses which are associated with this Layer.

Variable regularization tensors are created when this property is accessed, so it is eager safe: accessing losses under a tf.GradientTape will propagate gradients back to the corresponding variables.

Returns:

A list of tensors.

name

non_trainable_variables

non_trainable_weights

output

Retrieves the output tensor(s) of a layer.

Only applicable if the layer has exactly one output, i.e. if it is connected to one incoming layer.

Returns:

Output tensor or list of output tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.
  • RuntimeError: if called in Eager mode.

output_mask

Retrieves the output mask tensor(s) of a layer.

Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.

Returns:

Output mask tensor (potentially None) or list of output mask tensors.

Raises:

  • AttributeError: if the layer is connected to more than one incoming layers.

output_shape

Retrieves the output shape(s) of a layer.

Only applicable if the layer has one output, or if all outputs have the same shape.

Returns:

Output shape, as an integer shape tuple (or list of shape tuples, one tuple per output tensor).

Raises:

  • AttributeError: if the layer has no defined output shape.
  • RuntimeError: if called in Eager mode.

trainable_variables

trainable_weights

updates

variables

Returns the list of all layer variables/weights.

Alias of self.weights.

Returns:

A list of variables.

weights

Returns the list of all layer variables/weights.

Returns:

A list of variables.

Methods

__call__

__call__(
    inputs,
    *args,
    **kwargs
)

__setattr__

__setattr__(
    name,
    value
)

apply

apply(
    inputs,
    *args,
    **kwargs
)

Apply the layer on a input.

This is an alias of self.__call__.

Arguments:

  • inputs: Input tensor(s).
  • *args: additional positional arguments to be passed to self.call.
  • **kwargs: additional keyword arguments to be passed to self.call.

Returns:

Output tensor(s).

build

build(input_shape)

Creates the variables of the layer (optional, for subclass implementers).

This is a method that implementers of subclasses of Layer or Model can override if they need a state-creation step in-between layer instantiation and layer call.

This is typically used to create the weights of Layer subclasses.

Arguments:

  • input_shape: Instance of TensorShape, or list of instances of TensorShape if the layer expects a list of inputs (one instance per input).

compute_mask

compute_mask(
    inputs,
    mask=None
)

compute_output_shape

compute_output_shape(
    instance,
    input_shape
)

count_params

count_params()

Count the total number of scalars composing the weights.

Returns:

An integer count.

Raises:

  • ValueError: if the layer isn't yet built (in which case its weights aren't yet defined).

from_config

from_config(
    cls,
    config,
    custom_objects=None
)

get_config

get_config()

get_input_at

get_input_at(node_index)

Retrieves the input tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A tensor (or list of tensors if the layer has multiple inputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_input_mask_at

get_input_mask_at(node_index)

Retrieves the input mask tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A mask tensor (or list of tensors if the layer has multiple inputs).

get_input_shape_at

get_input_shape_at(node_index)

Retrieves the input shape(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A shape tuple (or list of shape tuples if the layer has multiple inputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_losses_for

get_losses_for(inputs)

Retrieves losses relevant to a specific set of inputs.

Arguments:

  • inputs: Input tensor or list/tuple of input tensors.

Returns:

List of loss tensors of the layer that depend on inputs.

Raises:

  • RuntimeError: If called in Eager mode.

get_output_at

get_output_at(node_index)

Retrieves the output tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A tensor (or list of tensors if the layer has multiple outputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_output_mask_at

get_output_mask_at(node_index)

Retrieves the output mask tensor(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A mask tensor (or list of tensors if the layer has multiple outputs).

get_output_shape_at

get_output_shape_at(node_index)

Retrieves the output shape(s) of a layer at a given node.

Arguments:

  • node_index: Integer, index of the node from which to retrieve the attribute. E.g. node_index=0 will correspond to the first time the layer was called.

Returns:

A shape tuple (or list of shape tuples if the layer has multiple outputs).

Raises:

  • RuntimeError: If called in Eager mode.

get_updates_for

get_updates_for(inputs)

Retrieves updates relevant to a specific set of inputs.

Arguments:

  • inputs: Input tensor or list/tuple of input tensors.

Returns:

List of update ops of the layer that depend on inputs.

Raises:

  • RuntimeError: If called in Eager mode.

get_weights

get_weights()

Returns the current weights of the layer.

Returns:

Weights values as a list of numpy arrays.

new

@staticmethod
new(
    params,
    event_shape=(),
    dtype=None,
    validate_args=False,
    name=None
)

Create the distribution instance from a params vector.

params_size

@staticmethod
params_size(
    event_shape=(),
    name=None
)

The number of params needed to create a single distribution.

set_weights

set_weights(weights)

Sets the weights of the layer, from Numpy arrays.

Arguments:

  • weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the layer (i.e. it should match the output of get_weights).

Raises:

  • ValueError: If the provided weights list does not match the layer's specifications.