import cirq
obersv = 0
obersv += 0.5 * (cirq.Z(bits[0]) * cirq.Z(bits[1])) + 1 * (cirq.Z(bits[2]) * cirq.Z(bits[3]))
print(obersv)
0.500Z((0, 0)) * Z((0, 1))+1.000Z((0, 2)) * Z((0, 3))
搭建含参数量子线路(单量子比特,2个U3门,共6个参数)
import sympy
param_num_train = 6
train_syms = sympy.symbols('t0:%d' % param_num_train)
qubits = cirq.GridQubit.rect(1, 1)
circuit= cirq.Circuit()
circuit+= cirq.rz(train_syms [0]).on(qubits[0])
circuit+= cirq.ry(train_syms [1]).on(qubits[0])
circuit+= cirq.rz(train_syms [2]).on(qubits[0])
circuit+= cirq.rz(train_syms [3]).on(qubits[0])
circuit+= cirq.ry(train_syms [4]).on(qubits[0])
circuit+= cirq.rz(train_syms [5]).on(qubits[0])
import tensorflow as tf
import tensorflow_quantum as tfq
import numpy as np
#解析期望、有限差分求梯度
ideal_expectation_calculation = tfq.layers.Expectation(
differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01))
#采样期望、参数移位求梯度
#sampled_expectation_calculation = tfq.layers.SampledExpectation(
# differentiator=tfq.differentiators.ParameterShift())
value = np.random.uniform(-2 * np.pi, 2 * np.pi, param_num_train).tolist()
train_values_tensor = tf.convert_to_tensor([value], dtype='float32')
#测量第一个量子比特,可观测量设置为H = |0><0|=0.5(I+Z)
obersv = 0.5 * (cirq.Z(bits[0]) + cirq.I(bits[0]))
#计算期望
sampled_exp_outputs = ideal_expectation_calculation(circuit,
operators=obersv,
# repetitions=2000,
symbol_names= train_syms,
symbol_values= train_values_tensor)
print(sampled_exp_outputs)
tf.Tensor([[0.36264282]], shape=(1, 1), dtype=float32)
with tf.GradientTape() as g:
g.watch(train_values_tensor) #追踪train_value_tensor的梯度
#计算期望
sampled_exp_outputs = ideal_expectation_calculation(circuit,
operators=obersv,
# repetitions=2000,
symbol_names= train_syms,
symbol_values= train_values_tensor)
#计算梯度
sampled_finite_diff_gradients = g.gradient(sampled_exp_outputs, train_values_tensor)
tf.Tensor(
[[-7.6293945e-06 -7.7865601e-02 1.6986847e-02 1.6994476e-02
4.8110962e-01 0.0000000e+00]], shape=(1, 6), dtype=float32)
由于初始value是随机产生,计算出的结果不一定与示例结果一致。