import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.datasets import load_wine # 修改为加载Wine数据集
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler # 添加MinMaxScaler用于数据标准化
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from pennylane.qnn.keras import KerasLayer
重定向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, angle_q3_val in zip(control_values, angle_q3):
# 使用 tf.print 进行调试输出
tf.print(f"angle_q2: {angle_q2}, angle_q3_val: {angle_q3_val}")
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 对 q2 应用受控 RY 旋转,使用动态 angle_q2
qml.ctrl(qml.RY, control=control_qubits)(angle_q2, wires=data_qubits['q2'])
# 对 q3 应用受控 RY 旋转,使用动态 angle_q3_val
qml.ctrl(qml.RY, control=control_qubits)(angle_q3_val, wires=data_qubits['q3'])
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
print("脚本执行完成。查看 'output.log' 获取打印输出,查看当前目录获取保存的图表。")
代码出现如下报错
Traceback (most recent call last):
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\examples\wine_renew_usesoftmax_NQNN.py", line 326, in
history = wrapped_model.fit(
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\importance_sampling\training.py", line 132, in fit
return self.fit_dataset(
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\importance_sampling\training.py", line 273, in fit_dataset
loss_value, metrics_results, scores = self.train_batch(x_batch, y_batch, w)
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\importance_sampling\training.py", line 336, in train_batch
y_pred = self.model.model(x, training=True)
File "C:\Users\liuwenjing.conda\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\examples\wine_renew_usesoftmax_NQNN.py", line 260, in call
q_output = self.quantum_layer(inputs)
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\examples\wine_renew_usesoftmax_NQNN.py", line 238, in call
outputs = tf.map_fn(
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_file6w11ioka.py", line 12, in tf__apply_qnode
result = ag_.converted_call(ag__.ld(quantum_neural_network), (ag__.ld(x), ag__.ld(self).encoding_weights, ag__.ld(self).rot_weights), None, fscope)
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_file9aj3yqmq.py", line 41, in tf____call_
res = ag__.converted_call(ag__.ld(self).qtape.execute, (), dict(device=ag__.ld(self).device), fscope)
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_file8ta99_x6.py", line 64, in tf__execute
retval = ag__.converted_call(ag__.ld(self).execute, (ag_.ld(params),), dict(device=ag__.ld(device)), fscope)
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_filemfv1ivr4.py", line 55, in tf__execute_device
ag_.if_stmt(ag__.converted_call(ag__.ld(isinstance), (ag__.ld(device), ag__.ld(qml).QubitDevice), None, fscope), if_body_1, else_body_1, get_state_1, set_state_1, ('res',), 1)
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_filemfv1ivr4.py", line 49, in if_body_1
res = ag_.converted_call(ag__.ld(device).execute, (ag__.ld(self),), None, fscope)
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_filen1h2sta6.py", line 228, in tf__execute
ag_.if_stmt(ag__.not_(do_return), if_body_9, else_body_9, get_state_10, set_state_10, ('do_return', 'retval_', 'self.cache_execute[circuit_hash]', 'self.num_executions', 'self.samples'), 5)
File "C:\Users\LIUWEN~1\AppData\Local\Temp_autograph_generated_filen1h2sta6.py", line 83, in if_body_9
ag.converted_call(ag.ld(self).check_validity, (ag__.ld(circuit).operations, ag__.ld(circuit).observables), None, fscope)
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_fileo_fhd82h.py", line 77, in tf__check_validity
ag_.for_stmt(ag__.ld(queue), None, loop_body, get_state_3, set_state_3, (), {'iterate_names': 'o'})
File "C:\Users\LIUWEN1\AppData\Local\Temp_autograph_generated_fileo_fhd82h.py", line 73, in loop_body
ag_.if_stmt(ag__.not_(ag__.converted_call(ag__.ld(self).supports_operation, (ag__.ld(operation_name),), None, fscope)), if_body_2, else_body_2, get_state_2, set_state_2, (), 0)
File "C:\Users\LIUWEN~1\AppData\Local\Temp_autograph_generated_fileo_fhd82h.py", line 69, in if_body_2
raise ag_.converted_call(ag__.ld(DeviceError), (ag__.converted_call('Gate {} not supported on device {}'.format, (ag__.ld(operation_name), ag__.ld(self).short_name), None, fscope),), None, fscope)
pennylane._device.DeviceError: Exception encountered when calling layer "quantum_neural_network_layer" " f"(type QuantumNeuralNetworkLayer).
in user code:
code
File "C:\代码备份库\importance-sampling-master-wine-QNN-pennylane\examples\wine_renew_usesoftmax_NQNN.py", line 234, in apply_qnode *
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
File "C:\Users\liuwenjing\.conda\envs\pennylane2\lib\site-packages\pennylane\qnode.py", line 555, in __call__ *
res = self.qtape.execute(device=self.device)
File "C:\Users\liuwenjing\.conda\envs\pennylane2\lib\site-packages\pennylane\tape\tape.py", line 1235, in execute *
return self._execute(params, device=device)
File "C:\Users\liuwenjing\.conda\envs\pennylane2\lib\site-packages\pennylane\tape\tape.py", line 1266, in execute_device *
res = device.execute(self)
File "C:\Users\liuwenjing\.conda\envs\pennylane2\lib\site-packages\pennylane\_qubit_device.py", line 181, in execute *
self.check_validity(circuit.operations, circuit.observables)
File "C:\Users\liuwenjing\.conda\envs\pennylane2\lib\site-packages\pennylane\_device.py", line 670, in check_validity *
raise DeviceError(
DeviceError: Gate ControlledOperation not supported on device default.qubit.tf
Call arguments received by layer "quantum_neural_network_layer" " f"(type QuantumNeuralNetworkLayer):
• inputs=tf.Tensor(shape=(8, 13), dtype=float32)