# tfq.layers.SampledExpectation

A layer that calculates a sampled expectation value.

### Used in the notebooks

Used in the tutorials

Given an input circuit and set of parameter values, output expectation values of observables computed using measurement results sampled from the input circuit.

First define a simple helper function for generating a parametrized quantum circuit that we will use throughout:

def _gen_single_bit_rotation_problem(bit, symbols):
"""Generate a toy problem on 1 qubit."""
starting_state = [0.123, 0.456, 0.789]
circuit = cirq.Circuit(
cirq.rx(starting_state[0])(bit),
cirq.ry(starting_state[1])(bit),
cirq.rz(starting_state[2])(bit),
cirq.rz(symbols[2])(bit),
cirq.ry(symbols[1])(bit),
cirq.rx(symbols[0])(bit)
)
return circuit

In quantum machine learning there are two very common use cases that align with keras layer constructs. The first is where the circuits represent the input data points:

bit = cirq.GridQubit(0, 0)
symbols = sympy.symbols('x y z')
ops = [-1.0 * cirq.Z(bit), cirq.X(bit) + 2.0 * cirq.Z(bit)]
num_samples = [100, 200]
circuit_list = [
_gen_single_bit_rotation_problem(bit, symbols),
cirq.Circuit(
cirq.Z(bit) ** symbols[0],
cirq.X(bit) ** symbols[1],
cirq.Z(bit) ** symbols[2]
),
cirq.Circuit(
cirq.X(bit) ** symbols[0],
cirq.Z(bit) ** symbols[1],
cirq.X(bit) ** symbols[2]
)
]
sampled_expectation_layer = tfq.layers.SampledExpectation()
output = sampled_expectation_layer(
circuit_list,
symbol_names=symbols,
operators=ops,
repetitions=num_samples)
# Here output[i][j] corresponds to the sampled expectation
# of all the ops in ops w.r.t circuits[i] where Keras managed
# variables are placed in the symbols 'x', 'y', 'z'.
tf.shape(output)
tf.Tensor([3 2], shape=(2,), dtype=int32)

Here, different cirq.Circuit instances sharing the common symbols 'x', 'y' and 'z' are used as input. Keras uses the symbol_names argument to map Keras managed variables to these circuits constructed with sympy.Symbols. The shape of num_samples is equal to that of ops.

The second most common use case is where there is a fixed circuit and the expectation operators vary:

bit = cirq.GridQubit(0, 0)
symbols = sympy.symbols('x, y, z')
ops = [-1.0 * cirq.Z(bit), cirq.X(bit) + 2.0 * cirq.Z(bit)]
fixed_circuit = _gen_single_bit_rotation_problem(bit, symbols)
expectation_layer = tfq.layers.SampledExpectation()
output = expectation_layer(
fixed_circuit,
symbol_names=symbols,
operators=ops,
repetitions=5000,
initializer=tf.keras.initializers.RandomUniform(0, 2 * np.pi))
# Here output[i][j] corresponds to
# the sampled expectation of operators[i][j] using 5000 samples w.r.t
# the circuit where variable values are managed by keras and store
# numbers in the symbols 'x', 'y', 'z'.
tf.shape(output)
tf.Tensor([1 2], shape=(2,), dtype=int32)

Here different cirq.PauliSum or cirq.PauliString instances can be used as input to calculate the expectation on the fixed circuit that the layer was initially constructed with.

There are also some more complex use cases that provide greater flexibility. Notably these configurations all make use of the symbol_values parameter that causes the SampledExpectation layer to stop managing the sympy.Symbols in the quantum circuits and instead requires the user to supply inputs themselves. Lets look at the case where there is a single fixed circuit, some fixed operators and symbols that must be common to all circuits:

bit = cirq.GridQubit(0, 0)
symbols = sympy.symbols('x y z')
ops = [cirq.Z(bit), cirq.X(bit)]
num_samples = [100, 200]
circuit = _gen_single_bit_rotation_problem(bit, symbols)
values = [[1,1,1], [2,2,2], [3,3,3]]
sampled_expectation_layer = tfq.layers.SampledExpectation()
output = sampled_expectation_layer(
circuit,
symbol_names=symbols,
symbol_values=values,
operators=ops,
repetitions=num_samples)
# output[i][j] = The sampled expectation of ops[j] with
# values_tensor[i] placed into the symbols of the circuit
# with the order specified by feed_in_params.
# so output[1][2] = The sampled expectation of a circuit with parameter
# values [2,2,2] w.r.t Pauli X, estimated using 200 samples per term.
output  # Non-deterministic result. It can vary every time.
tf.Tensor(
[[0.52, 0.72],
[0.34, 1.  ],
[0.78, 0.48]], shape=(3, 2), dtype=float32)

Tip: you can compare the above result with that of Expectation: tf.Tensor( [[0.63005245 0.76338404] [0.25707167 0.9632684 ] [0.79086655 0.5441111 ]], shape=(3, 2), dtype=float32)

Here is a simple model that uses this particular input signature of tfq.layers.SampledExpectation, that learns to undo the random rotation of the qubit:

bit = cirq.GridQubit(0, 0)
symbols = sympy.symbols('x, y, z')
circuit = _gen_single_bit_rotation_problem(bit, symbols)
control_input = tf.keras.Input(shape=(1,))
circuit_inputs = tf.keras.Input(shape=(), dtype=tf.dtypes.string)
d1 = tf.keras.layers.Dense(10)(control_input)
d2 = tf.keras.layers.Dense(3)(d1)
expectation = tfq.layers.SampledExpectation()(
circuit_inputs, # See note below!
symbol_names=symbols,
symbol_values=d2,
operators=cirq.Z(bit),
repetitions=5000)
data_in = np.array([[1], [0]], dtype=np.float32)
data_out = np.array([[1], [-1]], dtype=np.float32)
model = tf.keras.Model(
inputs=[circuit_inputs, control_input], outputs=expectation)
model.compile(
loss=tf.keras.losses.mean_squared_error)
history = model.fit(
x=[tfq.convert_to_tensor([circuit] * 2), data_in],
y=data_out,
epochs=100)

For an example featuring this layer, please check out Taking gradients in our dev website http://www.tensorflow.org/quantum/tutorials

Lastly symbol_values, operators and circuit inputs can all be fed Python list objects. In addition to this they can also be fed tf.Tensor inputs, meaning that you can input all of these things from other Tensor objects (like tf.keras.Dense layer outputs or tf.keras.Inputs etc).

backend Optional Backend to use to simulate states. Defaults to the native TensorFlow simulator (None), however users may also specify a preconfigured cirq simulation object to use instead, which must inherit cirq.SimulatesFinalState.
differentiator Optional Differentiator to use to calculate analytic derivative values of given operators_to_measure and circuit, which must inherit tfq.differentiators.Differentiator. Defaults to None, which uses parameter_shift.ParameterShift().

activity_regularizer Optional regularizer function for the output of this layer.
dtype Dtype used by the weights of the layer, set in the constructor.
dynamic Whether the layer is dynamic (eager-only); set in the constructor.
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.

input_spec InputSpec instance(s) describing the input format for this layer.

When you create a layer subclass, you can set self.input_spec to enable the layer to run input compatibility checks when it is called. Consider a Conv2D layer: it can only be called on a single input tensor of rank 4. As such, you can set, in __init__():

self.input_spec = tf.keras.layers.InputSpec(ndim=4)

Now, if you try to call the layer on an input that isn't rank 4 (for instance, an input of shape (2,), it will raise a nicely-formatted error:

ValueError: Input 0 of layer conv2d is incompatible with the layer:
expected ndim=4, found ndim=1. Full shape received: [2]

Input checks that can be specified via input_spec include:

• Structure (e.g. a single input, a list of 2 inputs, etc)
• Shape
• Rank (ndim)
• Dtype

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.

class MyLayer(tf.keras.layers.Layer):
def call(self, inputs):
return inputs
l = MyLayer()
l(np.ones((10, 1)))
l.losses
[1.0]
inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Activity regularization.
model.losses
[<tf.Tensor 'Abs:0' shape=() dtype=float32>]
inputs = tf.keras.Input(shape=(10,))
d = tf.keras.layers.Dense(10, kernel_initializer='ones')
x = d(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Weight regularization.
model.losses
[<tf.Tensor: shape=(), dtype=float32, numpy=1.0>]

input = tf.keras.layers.Input(shape=(3,))
d = tf.keras.layers.Dense(2)
output = d(input)
[m.name for m in d.metrics]
['max', 'min']

name Name of the layer (string), set in the constructor.
name_scope Returns a tf.name_scope instance for this class.
non_trainable_weights List of all non-trainable weights tracked by this layer.

Non-trainable weights are not updated during training. They are expected to be updated manually in call().

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.

submodules Sequence of all sub-modules.

Submodules are modules which are properties of this module, or found as properties of modules which are properties of this module (and so on).

a = tf.Module()
b = tf.Module()
c = tf.Module()
a.b = b
b.c = c
list(a.submodules) == [b, c]
True
list(b.submodules) == [c]
True
list(c.submodules) == []
True

trainable

trainable_weights List of all trainable weights tracked by this layer.

Trainable weights are updated via gradient descent during training.

weights Returns the list of all layer variables/weights.

## Methods

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.

This method can be used inside a subclassed layer or model's call function, in which case losses should be a Tensor or list of Tensors.

#### Example:

class MyLayer(tf.keras.layers.Layer):
def call(self, inputs):
return inputs

This method can also be called directly on a Functional Model during construction. In this case, any loss Tensors passed to this Model must be symbolic and be able to be traced back to the model's Inputs. These losses become part of the model's topology and are tracked in get_config.

#### Example:

inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Activity regularization.

If this is not the case for your loss (if, for example, your loss references a Variable of one of the model's layers), you can wrap your loss in a zero-argument lambda. These losses are not tracked as part of the model's topology since they can't be serialized.

#### Example:

inputs = tf.keras.Input(shape=(10,))
d = tf.keras.layers.Dense(10)
x = d(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Weight regularization.

Arguments
losses Loss tensor, or list/tuple of tensors. Rather than tensors, losses may also be zero-argument callables which create a loss tensor.
**kwargs Additional keyword arguments for backward compatibility. Accepted values: inputs - Deprecated, will be automatically inferred.

Adds metric tensor to the layer.

This method can be used inside the call() method of a subclassed layer or model.

class MyMetricLayer(tf.keras.layers.Layer):
def __init__(self):
super(MyMetricLayer, self).__init__(name='my_metric_layer')
self.mean = metrics_module.Mean(name='metric_1')

def call(self, inputs):
return inputs

This method can also be called directly on a Functional Model during construction. In this case, any tensor passed to this Model must be symbolic and be able to be traced back to the model's Inputs. These metrics become part of the model's topology and are tracked when you save the model via save().

inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)

Args
value Metric tensor.
name String metric name.
**kwargs Additional keyword arguments for backward compatibility. Accepted values: aggregation - When the value tensor provided is not the result of calling a keras.Metric instance, it will be aggregated by default using a keras.Metric.Mean.

### build

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).

Arguments
inputs Tensor or list of tensors.
mask Tensor or list of tensors.

Returns
None or a tensor (or list of tensors, one per output tensor of the layer).

### compute_output_shape

Computes the output shape of the layer.

If the layer has not been built, this method will call build on the layer. This assumes that the layer will later be used with inputs that match the input shape provided here.

Arguments
input_shape Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer.

Returns
An input shape tuple.

### 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

Creates a layer from its config.

This method is the reverse of get_config, capable of instantiating the same layer from the config dictionary. It does not handle layer connectivity (handled by Network), nor weights (handled by set_weights).

Arguments
config A Python dictionary, typically the output of get_config.

Returns
A layer instance.

### get_config

Returns the config of the layer.

A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration.

The config of a layer does not include connectivity information, nor the layer class name. These are handled by Network (one layer of abstraction above).

Returns
Python dictionary.

### get_weights

Returns the current weights of the layer.

The weights of a layer represent the state of the layer. This function returns both trainable and non-trainable weight values associated with this layer as a list of Numpy arrays, which can in turn be used to load state into similarly parameterized layers.

For example, a Dense layer returns a list of two values-- per-output weights and the bias value. These can be used to set the weights of another Dense layer:

a = tf.keras.layers.Dense(1,
kernel_initializer=tf.constant_initializer(1.))
a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
b = tf.keras.layers.Dense(1,
kernel_initializer=tf.constant_initializer(2.))
b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
b.set_weights(a.get_weights())
b.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]

Returns
Weights values as a list of numpy arrays.

### set_weights

Sets the weights of the layer, from Numpy arrays.

The weights of a layer represent the state of the layer. This function sets the weight values from numpy arrays. The weight values should be passed in the order they are created by the layer. Note that the layer's weights must be instantiated before calling this function by calling the layer.

For example, a Dense layer returns a list of two values-- per-output weights and the bias value. These can be used to set the weights of another Dense layer:

a = tf.keras.layers.Dense(1,
kernel_initializer=tf.constant_initializer(1.))
a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
b = tf.keras.layers.Dense(1,
kernel_initializer=tf.constant_initializer(2.))
b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
b.set_weights(a.get_weights())
b.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]

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.

### with_name_scope

Decorator to automatically enter the module name scope.

class MyModule(tf.Module):
@tf.Module.with_name_scope
def __call__(self, x):
if not hasattr(self, 'w'):
self.w = tf.Variable(tf.random.normal([x.shape[1], 3]))
return tf.matmul(x, self.w)

Using the above module would produce tf.Variables and tf.Tensors whose names included the module name:

mod = MyModule()
mod(tf.ones([1, 2]))
<tf.Tensor: shape=(1, 3), dtype=float32, numpy=..., dtype=float32)>
mod.w
<tf.Variable 'my_module/Variable:0' shape=(2, 3) dtype=float32,
numpy=..., dtype=float32)>

Args
method The method to wrap.

Returns
The original method wrapped such that it enters the module's name scope.

### __call__

Wraps call, applying pre- and post-processing steps.

Arguments
*args Positional arguments to be passed to self.call.
**kwargs Keyword arguments to be passed to self.call.

Returns
Output tensor(s).

#### Note:

• The following optional keyword arguments are reserved for specific uses:
• training: Boolean scalar tensor of Python boolean indicating whether the call is meant for training or inference.