|View source on GitHub|
Get a TensorFlow op that will calculate sampled expectation values.
tfq.get_sampled_expectation_op( backend=None )
This function produces a non-differentiable TF op that will calculate
batches of expectation values given tensor batches of
parameter values, and
cirq.PauliSum operators to measure.
Expectation is estimated by taking num_samples shots per term in the
# Simulate circuits with C++.
my_op = tfq.get_sampled_expectation_op()
# Prepare some inputs.
qubit = cirq.GridQubit(0, 0)
my_symbol = sympy.Symbol('alpha')
my_circuit_tensor = tfq.convert_to_tensor([
cirq.Circuit(cirq.H(qubit) ** my_symbol)
my_values = np.array([[0.123]])
my_paulis = tfq.convert_to_tensor([[
3.5 * cirq.X(qubit) - 2.2 * cirq.Y(qubit)
my_num_samples = np.array([])
# This op can now be run with:
output = my_op(
my_circuit_tensor, ['alpha'], my_values, my_paulis, my_num_samples)
tf.Tensor([[0.71530885]], shape=(1, 1), dtype=float32)
In order to make the op differentiable, a
tfq.differentiator object is
tfq.differentiators for more details. Below is a simple
example of how to make my_op from the above code block differentiable:
diff = tfq.differentiators.ForwardDifference()
my_differentiable_op = diff.generate_differentiable_op(
objectthat specifies what backend this op should use when evaluating circuits. It only accepts
callable with the following signature:
tf.Tensorof strings with shape [batch_size] containing the string representations of the circuits to be executed.
tf.Tensorof strings with shape [n_params], which is used to specify the order in which the values in
symbol_valuesshould be placed inside of the circuits in
tf.Tensorof real numbers with shape [batch_size, n_params] specifying parameter values to resolve into the circuits specified by programs, following the ordering dictated by
tf.Tensorof strings with shape [batch_size, n_ops] containing the string representation of the operators that will be used on all of the circuits in the expectation calculations.
n_samples[i][j]is equal to the number of samples to draw in each term of
pauli_sums[i][j]when estimating the expectation. It can also be tiled up to the shape of pauli_sums by broadcasting if tf.shape(num_samples) or tf.shape(num_samples) is 1 and the other dimension is the same with that of pauli_sums.
tf.Tensorwith shape [batch_size, n_ops] that holds the expectation value for each circuit with each op applied to it (after resolving the corresponding parameters in).