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.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):
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 对 q2 应用多控制 RY 旋转
multi_controlled_RY(angle_q2, control_qubits, data_qubits['q2'], ancilla)
# 对 q3 应用多控制 RY 旋转
multi_controlled_RY(angle_q3_val, control_qubits, data_qubits['q3'], ancilla)
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
for idx, data_set in enumerate(encoding_data):
data_qubits = data_set['data_qubits']
swap_qubit = data_set['swap_qubit']
angle_q2 = angles_q2_list[idx] # Tensor scalar
for layer in range(rot_weights.shape[0]):
angle_q3_values = angles_q3_list[idx, layer, :] # Tensor of shape (4,)
encode_group(control_qubits, data_qubits, angle_q2, angle_q3_values, ancilla)
应用交换操作
for data_set in encoding_data:
swap_qubit = data_set['swap_qubit']
data_qubits = data_set['data_qubits']
apply_controlled_swap(swap_qubit, data_qubits['q3'], data_qubits['q2'])
应用 Rot 层
for layer in range(rot_weights.shape[0]):
for qubit in range(rot_weights.shape[1]):
rot_angles = rot_weights[layer, qubit, :] # Tensor of shape (3,)
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
测量 PauliZ 期望值
results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]
for idx, data_set in enumerate(encoding_data):
data_qubits = data_set['data_qubits']
swap_qubit = data_set['swap_qubit']
angle_q2 = angles_q2_list[idx] # Tensor scalar
for layer in range(rot_weights.shape[0]):
angle_q3_values = angles_q3_list[idx, layer, :] # Tensor of shape (4,)
encode_group(control_qubits, data_qubits, angle_q2, angle_q3_values, ancilla)
应用交换操作
for data_set in encoding_data:
swap_qubit = data_set['swap_qubit']
data_qubits = data_set['data_qubits']
apply_controlled_swap(swap_qubit, data_set['data_qubits']['q3'], data_set['data_qubits']['q2'])
应用 Rot 层
for layer in range(rot_weights.shape[0]):
for qubit in range(rot_weights.shape[1]):
rot_angles = rot_weights[layer, qubit, :] # Tensor of shape (3,)
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
测量 PauliZ 期望值
results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]
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.")
sys.stdout = original_stdout
output_file.close()
print("脚本执行完成。查看 'output.log' 获取打印输出,查看当前目录获取保存的图表。")
上述为是代码1
from future import print_function
import pennylane as qml
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense # Using public API import
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from sklearn.metrics import roc_curve, auc
from pennylane.qnn.keras import KerasLayer
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'.format(roc_auc["micro"]))
for i in range(n_classes):
plt.plot(fpr[i], tpr[i],
label='ROC curve of class {0} (area = {1:0.2f})'.format(i, roc_auc[i]))
learning_rate = 0.1
epochs = 100
batch_size = 8
num_classes = 3 # Iris dataset has 3 classes
n_qubits = 4 # Number of qubits (should match the number of features)
n_layers = 2
Create model
model = QuantumNeuralNetwork(
n_qubits=n_qubits,
n_layers=n_layers,
num_classes=num_classes
)
Compile model
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),
loss='categorical_crossentropy', # Use softmax when from_logits=False
metrics=['accuracy']
)
Manually set model.loss attribute
model.loss = 'categorical_crossentropy'
Function to check if the model contains a quantum layer
def is_quantum_model(model):
for layer in model.layers:
if isinstance(layer, KerasLayer):
return True
return False
Check if the model contains a quantum layer
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.")
Train the model with or without importance sampling
if args.importance_training:
# Custom training with importance sampling
wrapped_model = ConstantTimeImportanceTraining(model)
history = wrapped_model.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test)
)
else:
# Standard Keras training
history = model.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test)
)
The significant disparity in accuracy between 代码1 (Code1) and 代码2 (Code2), despite Code1 utilizing a more complex quantum neural network (QNN) structure, can be attributed to several factors related to circuit complexity, encoding strategies, optimization methods, and potential implementation issues. Below, I outline the key reasons for this discrepancy and provide actionable steps to enhance Code1's performance without fundamentally altering its QNN structure.
**1. Quantum Circuit Complexity and Optimization Challenges
Code1 employs a highly intricate quantum circuit involving multiple controlled rotations, ancilla qubits, and controlled swap (CSWAP) operations. While increased complexity theoretically allows for more expressive power, it can also introduce several issues:
Overparameterization: Excessive parameters can make the optimization landscape rugged, leading to difficulties in training and potential overfitting, especially with limited data like the Iris dataset.
Barren Plateaus: Highly entangled and deep quantum circuits may result in regions of the parameter space where gradients vanish, making training via gradient-based methods ineffective.
Noise and Error Accumulation: Complex circuits are more susceptible to numerical instabilities and errors, especially when simulated on classical hardware.
Code2, on the other hand, utilizes a simpler and more standardized circuit structure with Angle Embeddings and Strongly Entangling Layers. This simplicity likely makes the optimization process smoother and more efficient, leading to better performance.
2. Encoding Strategy
Code1 uses a custom encoding strategy that involves multi-controlled RY rotations and controlled swap operations. While innovative, this approach may not align optimally with the problem's requirements, potentially complicating the learning process.
Code2 leverages AngleEmbedding and StronglyEntanglingLayers, which are well-established encoding and entangling strategies known to perform effectively on various datasets, including Iris.
3. Differentiation Method
Code1 uses the parameter-shift rule for differentiation, which is robust but can be computationally intensive and potentially less stable for complex circuits.
Code2 employs the backprop method, which is generally faster and may benefit from more stable gradient computations in simpler circuits.
4. Device Configuration
Code1 utilizes the lightning.qubit device with 11 wires, which is more complex and may introduce additional computational overhead compared to Code2’s default.qubit with 4 wires. This increase in qubits can also lead to more complex entanglement patterns and parameter interactions, complicating training.
5. Data Type and Precision
Both codes handle data types differently, with Code1 using float64 and Code2 using float32. While precision differences are unlikely to be the primary cause, maintaining consistency in data types across all components of the model can prevent subtle bugs or numerical instabilities.
Actionable Steps to Improve Code1's Accuracy
To enhance Code1’s performance without fundamentally altering its QNN structure (except for potentially adjusting the number of layers), consider the following strategies:
1. Simplify the Quantum Circuit
Reduce the Number of Ancilla Qubits: Ancilla qubits add complexity and potential sources of noise. Evaluate if all ancillas are necessary or if the circuit can be simplified.
Limit Controlled Operations: Excessive multi-controlled gates can make the circuit harder to train. Explore reducing the number of controlled RY and CSWAP operations.
2. Optimize Hyperparameters
Learning Rate Adjustment: Experiment with different learning rates. A lower learning rate (e.g., 0.01 or 0.001) might stabilize training.
Optimizer Choice: While SGD is simple, more advanced optimizers like Adam or RMSprop could provide better convergence by adapting learning rates dynamically.
Batch Size: Increasing the batch size can lead to more stable gradient estimates, which might aid in training complex models.
3. Enhance Initialization Strategies
Parameter Initialization: Ensure that weights are initialized properly to avoid starting in regions with vanishing or exploding gradients. Use initializers like Glorot (Xavier) or He initialization.
initializer = tf.keras.initializers.GlorotUniform()
# Apply this initializer to your quantum and classical layers
4. Regularization Techniques
Early Stopping: Implement early stopping to prevent overfitting and to halt training when validation performance stops improving.
Carefully adjust the number of layers to find a balance between expressiveness and trainability. Start with fewer layers and incrementally add more, monitoring performance improvements.
7. Monitoring and Debugging
Visualize the Quantum Circuit: Use qml.draw to ensure the circuit is constructed as intended without unintended complexities.
Check Gradient Flow: Verify that gradients are flowing correctly through the network, ensuring no layers are inadvertently blocking gradient propagation.
Log Intermediate Outputs: Capture and analyze intermediate outputs to identify where performance may be degrading.
8. Data Preprocessing Enhancements
Normalization: Ensure that input data is properly normalized or scaled to facilitate better training dynamics.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(X)
Feature Selection: Assess if all input features contribute positively to model performance or if dimensionality reduction could help.
9. Alternative Encoding Strategies
While maintaining the overall structure, experiment with different encoding schemes that might align better with the task, such as amplitude encoding or basis encoding, to see if they offer performance benefits.
10. Consistent Data Types
Ensure that all components of the model consistently use float64 to prevent potential type mismatches and numerical issues.
# Ensure all tensors are float64
sample_encoding_weights = tf.constant(np.zeros((3, n_layers, 4), dtype=np.float64))
Conclusion
The discrepancy between Code1 and Code2 primarily arises from the increased complexity and potential training challenges associated with Code1’s quantum circuit. By simplifying the circuit, optimizing hyperparameters, enhancing initialization and regularization strategies, and carefully monitoring the training process, you can significantly improve Code1’s performance without fundamentally altering its QNN structure. Implementing these strategies should help bridge the performance gap and achieve higher accuracy on the Iris dataset.
If after these adjustments the performance still lags, consider revisiting the quantum circuit design to ensure that it is well-suited for the classification task at hand. Balancing circuit expressiveness with trainability is crucial for effective quantum machine learning models.