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=6_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=6.py", line 303, in
history = wrapped_model.fit(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=6_4feature _AngCode\importance_sampling\training.py", line 132, in fit
return self.fit_dataset(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=6_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=6_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=6_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=6.py", line 248, 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=6_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=6.py", line 219, 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=6_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=6.py", line 118, in quantum_neural_network *
encode_group(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=6_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=6.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)
The error you're encountering stems from attempting to iterate over symbolic TensorFlow tensors within your Quantum Neural Network (QNN) implemented using PennyLane. TensorFlow's graph execution mode does not support Python control flows (like for loops) that iterate over tensors. Specifically, the encode_group function in your yuanweihua.py script is trying to iterate over angle_values and angle_weights, which are tensors when the QNode is executed within a TensorFlow context.
To resolve this issue, you need to avoid iterating over tensors within the QNode. Instead, unroll the loops manually for a fixed number of operations based on the known dimensions of your data. Here's how you can modify your yuanweihua.py file to achieve this:
Step-by-Step Solution
Understand the Root Cause:
Error Origin: The encode_group function attempts to iterate over angle_values and angle_weights, which are symbolic tensors in TensorFlow's graph mode.
Why It's a Problem: TensorFlow's AutoGraph does not allow iteration over symbolic tensors because it cannot unroll dynamic Python loops during graph compilation.
Modify the encode_group Function:
Objective: Replace the dynamic for loop with a fixed sequence of operations.
Assumption: Based on your QNN setup, data_qubits has a fixed length (e.g., 2 qubits per layer).
Action: Manually apply the controlled RY gates for each qubit without using loops.
Adjust Weight Dimensions if Necessary:
Ensure that the dimensions of encoding_weights and rot_weights align with the fixed operations in encode_group.
For instance, if you're assigning multiple features to a single qubit, ensure that the weights are structured accordingly.
Modified yuanweihua.py
Here's the revised version of your yuanweihua.py file with the necessary changes:
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()
output_file = open('output.log', 'w', encoding='utf-8')
original_stdout = sys.stdout
sys.stdout = Tee(sys.stdout, output_file)
def save_plot(fig, filename):
fig.savefig(filename)
plt.close(fig)
def plot_history(history):
# 绘制训练和验证准确率
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['accuracy'])
ax.plot(history.history['val_accuracy'])
ax.set_title('Model Accuracy')
ax.set_ylabel('Accuracy')
ax.set_xlabel('Epoch')
ax.legend(['Train', 'Validation'], loc='upper left')
save_plot(fig, 'accuracy_plot.png')
# 绘制训练和验证损失
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['loss'])
ax.plot(history.history['val_loss'])
ax.set_title('Model Loss')
ax.set_ylabel('Loss')
ax.set_xlabel('Epoch')
ax.legend(['Train', 'Validation'], loc='upper left')
save_plot(fig, 'loss_plot.png')
def calculate_accuracy_fluctuation(history):
val_accuracies = history.history['val_accuracy']
mean_accuracy = np.mean(val_accuracies)
fluctuation = np.sum(np.abs(val_accuracies - mean_accuracy))
return mean_accuracy, fluctuation
# 定义设备,使用14个量子比特以支持6层
dev = qml.device("default.qubit", wires=14)
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 旋转,编码特征值和权重
# **手动展开循环,避免在图中迭代**
# 假设有2个数据量子比特,每个量子比特对应2个特征值
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])
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)
def apply_controlled_swap(swap_control_qubit, data_qubits):
# 应用 Hadamard 门到 swap_control_qubit
qml.Hadamard(wires=swap_control_qubit)
# 应用受控 SWAP 门
qml.CSWAP(wires=[swap_control_qubit, data_qubits[0], data_qubits[1]])
# 再次应用 Hadamard 门到 swap_control_qubit
qml.Hadamard(wires=swap_control_qubit)
@qml.qnode(dev, interface='tf', diff_method='backprop')
def quantum_neural_network(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
num_layers = encoding_weights.shape[0]
num_features = inputs.shape[0]
# 定义量子比特索引,每层使用固定的量子比特组
data_qubits_groups = [
[2, 3],
[4, 5],
[6, 7],
[8, 9],
[10, 11],
[12, 13] # 第六层使用新的数据比特
]
# 为每层分配不同的swap控制比特,确保不重复且在量子比特范围内
# 这里选择 swap 控制比特为4,6,8,10,12,最后一层不进行swap操作
swap_control_qubits = [4, 6, 8, 10, 12, None] # 第六层不进行swap
for layer_idx in range(num_layers):
data_qubits = data_qubits_groups[layer_idx]
swap_control_qubit = swap_control_qubits[layer_idx]
# 编码层
encode_group(
control_qubits,
data_qubits,
inputs, # 特征值
encoding_weights[layer_idx] # 权重
)
# 应用 swap 门,除了最后一层
if swap_control_qubit is not None:
apply_controlled_swap(swap_control_qubit, data_qubits)
# 应用旋转层
for qubit in range(dev.num_wires):
rot_angles = rot_weights[layer_idx, qubit, :]
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# 测量 swap 控制比特(不包括最后一层)
results = []
for swap_control_qubit in swap_control_qubits:
if swap_control_qubit is not None:
results.append(qml.expval(qml.PauliZ(wires=swap_control_qubit)))
return results
@qml.qnode(dev)
def quantum_neural_network_draw(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
num_layers = encoding_weights.shape[0]
num_features = inputs.shape[0]
# 定义量子比特索引,每层使用固定的量子比特组
data_qubits_groups = [
[2, 3],
[4, 5],
[6, 7],
[8, 9],
[10, 11],
[12, 13] # 第六层使用新的数据比特
]
# 为每层分配不同的swap控制比特,确保不重复且在量子比特范围内
# 这里选择 swap 控制比特为4,6,8,10,12,最后一层不进行swap操作
swap_control_qubits = [4, 6, 8, 10, 12, None] # 第六层不进行swap
for layer_idx in range(num_layers):
data_qubits = data_qubits_groups[layer_idx]
swap_control_qubit = swap_control_qubits[layer_idx]
# 编码层
encode_group(
control_qubits,
data_qubits,
inputs, # 特征值
encoding_weights[layer_idx] # 权重
)
# 应用 swap 门,除了最后一层
if swap_control_qubit is not None:
apply_controlled_swap(swap_control_qubit, data_qubits)
# 应用旋转层
for qubit in range(dev.num_wires):
rot_angles = rot_weights[layer_idx, qubit, :]
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# 测量 swap 控制比特(不包括最后一层)
results = []
for swap_control_qubit in swap_control_qubits:
if swap_control_qubit is not None:
results.append(qml.expval(qml.PauliZ(wires=swap_control_qubit)))
return results
# 定义一个量子神经网络层
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
def __init__(self, n_layers, n_features=4, **kwargs):
super(QuantumNeuralNetworkLayer, self).__init__(**kwargs)
self.n_layers = n_layers
self.n_features = n_features
# 定义编码权重
# 修改n_features为2,因为每数据量子比特对应2个特征(angle_value和angle_weight)
self.encoding_weights = self.add_weight(
shape=(n_layers, n_features // 2), # 调整形状以匹配2个数据量子比特
initializer=tf.keras.initializers.GlorotUniform(),
trainable=True,
name='encoding_weights',
dtype=tf.float32 # 使用 float32 确保数据类型一致性
)
# 总量子比特数 = 14(包括控制和数据比特)
self.rot_weights = self.add_weight(
shape=(n_layers, dev.num_wires, 3), # 更新形状以匹配新的量子比特数
initializer=tf.keras.initializers.GlorotUniform(),
trainable=True,
name='rot_weights',
dtype=tf.float32 # 使用 float32 确保数据类型一致性
)
def call(self, inputs):
def apply_qnode(x):
x = tf.cast(x, dtype=tf.float32) # 确保输入为 float32
# 调整输入和编码权重的形状
# 假设每数据量子比特对应2个特征
# Reshape inputs to match the expected number of angle_values
angle_values = x[:self.n_features // 2]
angle_weights = self.encoding_weights
result = quantum_neural_network(angle_values, angle_weights, self.rot_weights)
return tf.cast(result, dtype=tf.float32)
outputs = tf.map_fn(
apply_qnode,
inputs,
dtype=tf.float32
)
# 打印权重(调试用)
tf.print("Encoding Weights:", self.encoding_weights)
tf.print("Rot Weights:", self.rot_weights)
return outputs
# 定义一个量子神经网络模型
class QuantumNeuralNetwork(tf.keras.Model):
def __init__(self, n_layers, num_classes, n_features=4, **kwargs):
super(QuantumNeuralNetwork, self).__init__(**kwargs)
self.n_layers = n_layers
self.num_classes = num_classes
# Quantum layer
self.quantum_layer = QuantumNeuralNetworkLayer(n_layers, n_features)
# Classical layers
self.dense = Dense(num_classes, activation='softmax')
def call(self, inputs):
q_output = self.quantum_layer(inputs)
return self.dense(q_output)
if __name__ == "__main__":
parser = get_parser("Train model on Iris dataset")
args = parser.parse_args()
iris = load_iris()
X = iris['data'].astype(np.float32)
y = iris['target'].reshape(-1, 1)
encoder = OneHotEncoder(sparse_output=False)
y = encoder.fit_transform(y).astype(np.float32)
x_train, x_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=116
)
learning_rate = 0.2
epochs = 100
batch_size = 8
num_classes = 3
n_layers = 6 # 修改层数为6,代表整个QNN的层数
model = QuantumNeuralNetwork(
n_layers=n_layers,
num_classes=num_classes
)
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),
loss='categorical_crossentropy',
metrics=['accuracy']
)
def is_quantum_model(model):
for layer in model.layers:
if isinstance(layer, QuantumNeuralNetworkLayer):
return True
return False
if is_quantum_model(model):
print("The model contains a Quantum Neural Network (QNN) layer.")
else:
print("The model does not contain a Quantum Neural Network (QNN) layer.")
print("\nQuantum Circuit Diagram:")
sample_inputs = np.ones(2, dtype=np.float32) * (np.pi / 2) # 使用2个特征
sample_encoding_weights = np.zeros((n_layers, 2), dtype=np.float32) # encoding_weights
sample_rot_weights = np.zeros((n_layers, dev.num_wires, 3), dtype=np.float32) # rot_weights
print(qml.draw(quantum_neural_network_draw)(sample_inputs, sample_encoding_weights, sample_rot_weights)) # 使用绘制专用的 QNode
if args.importance_training:
wrapped_model = ConstantTimeImportanceTraining(model, score="loss")
history = wrapped_model.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test)
)
else:
history = model.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test)
)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
mean_accuracy, fluctuation = calculate_accuracy_fluctuation(history)
print('Mean validation accuracy:', mean_accuracy)
print('Accuracy fluctuation:', fluctuation)
plot_history(history)
# 关闭输出文件并恢复stdout
sys.stdout = original_stdout
output_file.close()
print("脚本执行完成。查看 'output.log' 获取打印输出,查看当前目录获取保存的图表。")
Key Changes Explained
Unrolled for Loop in encode_group:
Removed the dynamic iteration over angle_values and angle_weights.
Manually applied the controlled RY gates for each data qubit.
This ensures compatibility with TensorFlow's graph execution by avoiding Python loops over tensors.
Adjusted Weight Dimensions:
Changed n_features in QuantumNeuralNetworkLayer from 4 to 2, assuming each data qubit corresponds to two features (one for angle_value and one for angle_weight).
Updated the shape of encoding_weights to (n_layers, 2) to match the number of data qubits.
Modified Sample Inputs for Circuit Drawing:
Updated sample_inputs to have 2 features to align with the adjusted n_features.
Updated the shapes of sample_encoding_weights and sample_rot_weights accordingly.
Ensured Consistent Mapping:
The encode_group function now correctly maps each feature to its corresponding data qubit without relying on dynamic iteration.
This maintains the integrity of the quantum circuit while ensuring compatibility with TensorFlow.
Additional Recommendations
Validation of Feature Mapping:
Ensure that the number of features (n_features) and the number of data qubits align correctly.
If you intend to use more features per qubit, further adjustments to encode_group and weight shapes might be necessary.
Testing:
After implementing these changes, run the script to ensure that the error is resolved.
Verify that the QNN behaves as expected during training and evaluation.
Logging and Debugging:
Utilize the output.log for detailed logs of the training process and weight updates.
Consider adding more tf.print statements if further debugging is required.
By unrolling the loops and ensuring that all operations within the QNode are compatible with TensorFlow's execution mode, you should be able to eliminate the OperatorNotAllowedInGraphError and successfully train your Quantum Neural Network.