为了探索是否可以使用 tensorflow 训练 Qiskit Quantum 电路,我构建了一个小型玩具模型。这个玩具模型的目的是通过 tensorflow 找到正确的角度,以获得独立于输入的“零”输出。
import numpy as np
import qiskit
from qiskit.circuit import QuantumCircuit, QuantumRegister
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Layer
def QuantumCircuit(thetas, n_qubits=1):
simulator = qiskit.Aer.get_backend('qasm_simulator')
shots=1024
circuit= qiskit.QuantumCircuit(n_qubits)
circuit.h(0)
circuit.ry(float(thetas),0)
circuit.measure_all()
job = qiskit.execute(circuit,backend=simulator,shots=shots)
result = job.result().get_counts(circuit)
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array(expectation)
class Linear(Layer):
def __init__(self,units=1,input_dim=1):
super(Linear,self).__init__()
self.w = self.add_weight(shape=(input_dim,units),initializer='random_uniform', trainable=True)
def call(self, inputs, input_dim=1):
if (tf.executing_eagerly()):
return QuantumCircuit(self.w)
return inputs
x_train = np.arange(10)
y_train = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
inputs=Input(shape=(1,))
outputs=Linear()(inputs)
model=tf.keras.models.Model(inputs=inputs,outputs=outputs)
model.summary()
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
loss=tf.keras.losses.MeanSquaredError())
model.fit(x_train, y_train, epochs=100, batch_size=1, verbose=1)
不幸的是,玩具模型不起作用,我收到以下错误:
optimizer_v2.py:1219 _filter_grads ([v.name for _, v in grads_and_vars],)) ValueError:没有为任何变量提供梯度:['Variable:0']。
所以我尝试“自己”计算梯度:
@tf.custom_gradient
def custom_activation(w):
result = QuantumCircuit(w)
def grad(dy):
eps=0.0001
result1=QuantumCircuit(w)
result2=QuantumCircuit(w+eps)
grad=(result2-result1)/eps
return dy * [grad]
return result, grad
作为调用 Quantum 电路之前的中间步骤。但这两个都行不通:-(
是否有人有其他想法将 Qiskit 电路插入 tensorflow 并处理 tensorflow 的自动微分框架在这种情况下不起作用的事实?非常感谢 !!