import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
重定向stdout以捕获打印输出
class Tee(object):
def init(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
for cv in control_values:
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 对数据量子比特应用受控 RY 旋转,编码特征值和权重
for data_qubit, angle_value, angle_weight in zip(data_qubits, angle_values, angle_weights):
qml.ctrl(qml.RY, control=control_qubits)(angle_value, wires=data_qubit)
qml.ctrl(qml.RY, control=control_qubits)(angle_weight, wires=data_qubit)
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
上述是training.py文件
出现报错
Traceback (most recent call last):
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 301, in
history = wrapped_model.fit(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\importance_sampling\training.py", line 132, in fit
return self.fit_dataset(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\importance_sampling\training.py", line 304, in fit_dataset
val_loss, val_metrics = self.evaluate(dataset.test_data)
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\importance_sampling\training.py", line 399, in evaluate
y_pred = self.model.model.predict(x_test, batch_size=128)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "G:\anaconda3\envs\pennylane2\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1233, in autograph_handler
raise e.ag_error_metadata.to_exception(e)
tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: in user code:
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 2041, in predict_function *
return step_function(self, iterator)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 2027, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 2015, in run_step **
outputs = model.predict_step(data)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 1983, in predict_step
return self(x, training=False)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
OperatorNotAllowedInGraphError: Exception encountered when calling layer "quantum_neural_network" " f"(type QuantumNeuralNetwork).
in user code:
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 246, in call *
q_output = self.quantum_layer(inputs)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler **
raise e.with_traceback(filtered_tb) from None
OperatorNotAllowedInGraphError: Exception encountered when calling layer "quantum_neural_network_layer" " f"(type QuantumNeuralNetworkLayer).
in user code:
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 217, in apply_qnode *
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\pennylane\qnode.py", line 552, in __call__ *
self.construct(args, kwargs)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\pennylane\qnode.py", line 481, in construct *
self.qfunc_output = self.func(*args, **kwargs)
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 117, in quantum_neural_network *
encode_group(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 76, in encode_group *
for data_qubit, angle_value, angle_weight in zip(data_qubits, angle_values, angle_weights):
OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
Call arguments received by layer "quantum_neural_network_layer" " f"(type QuantumNeuralNetworkLayer):
• inputs=tf.Tensor(shape=(None, 4), dtype=float32)
Call arguments received by layer "quantum_neural_network" " f"(type QuantumNeuralNetwork):
• inputs=tf.Tensor(shape=(None, 4), dtype=float32)
def encode_group(control_qubits, data_qubits, angle_values, angle_weights):
control_values = [[0, 0], [0, 1], [1, 0], [1, 1]]
for cv in control_values:
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 对数据量子比特应用受控 RY 旋转,编码特征值和权重
for data_qubit, angle_value, angle_weight in zip(data_qubits, angle_values, angle_weights):
qml.ctrl(qml.RY, control=control_qubits)(angle_value, wires=data_qubit)
qml.ctrl(qml.RY, control=control_qubits)(angle_weight, wires=data_qubit)
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
其中,angle_values 和 angle_weights 是 TensorFlow 的符号张量,尝试在图模式下通过 zip 进行迭代会导致 OperatorNotAllowedInGraphError。
def encode_group(control_qubits, data_qubits, angle_values, angle_weights):
control_values = [[0, 0], [0, 1], [1, 0], [1, 1]]
for cv in control_values:
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 手动展开对每个数据量子比特的操作
if len(data_qubits) > 0:
qml.ctrl(qml.RY, control=control_qubits)(angle_values[0], wires=data_qubits[0])
qml.ctrl(qml.RY, control=control_qubits)(angle_weights[0], wires=data_qubits[0])
if len(data_qubits) > 1:
qml.ctrl(qml.RY, control=control_qubits)(angle_values[1], wires=data_qubits[1])
qml.ctrl(qml.RY, control=control_qubits)(angle_weights[1], wires=data_qubits[1])
# 根据需要继续展开,假设最多有2个数据量子比特
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
单独测试 QNode:在集成到 Keras 模型之前,单独测试 quantum_neural_network QNode,确保其能够接受单个输入并返回预期的结果。
检查权重初始化:确保权重的初始化不会导致量子电路参数无效(例如,不要让 RY 旋转角度过大或过小)。
调整批处理大小:如果遇到性能问题,可以尝试减少批处理大小以减轻图计算的负担。
完整修改后的代码示例
以下是 encode_group 函数的修改示例:
def encode_group(control_qubits, data_qubits, angle_values, angle_weights):
control_values = [[0, 0], [0, 1], [1, 0], [1, 1]]
for cv in control_values:
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 手动展开对每个数据量子比特的受控 RY 旋转
if len(data_qubits) >= 1:
qml.ctrl(qml.RY, control=control_qubits)(angle_values[0], wires=data_qubits[0])
qml.ctrl(qml.RY, control=control_qubits)(angle_weights[0], wires=data_qubits[0])
if len(data_qubits) >= 2:
qml.ctrl(qml.RY, control=control_qubits)(angle_values[1], wires=data_qubits[1])
qml.ctrl(qml.RY, control=control_qubits)(angle_weights[1], wires=data_qubits[1])
# 如果有更多数据量子比特,继续手动展开
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
结论
通过消除 encode_group 函数中的动态 for 循环,并手动展开量子门操作,您可以避免在 TensorFlow 的图模式下对符号张量进行迭代的问题。这不仅解决了当前的错误,还使您的量子电路定义更加明确和稳定。如果未来需要处理更多量子比特或层,您可以进一步优化代码结构,或者探索使用 qml.map 等更高级的量子编程技术。