import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler, MinMaxScaler, LabelEncoder
from sklearn.decomposition import PCA # 导入 PCA
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense
from importance_sampling.training import ConstantTimeImportanceTraining
from importance_sampling.samplers import ConstantTimeSampler
from importance_sampling.datasets import InMemoryDataset
from importance_sampling.reweighting import BiasedReweightingPolicy
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
import logging
import pandas as pd
import seaborn as sns # 导入 seaborn 用于加载 Penguins 数据集
def plot_history(history):
# Plot training and validation accuracy
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['accuracy'], label='Training Accuracy')
if 'val_accuracy' in history.history:
ax.plot(history.history['val_accuracy'], label='Validation Accuracy')
else:
print("Validation accuracy not found in history.")
ax.set_title('Model Accuracy')
ax.set_ylabel('Accuracy')
ax.set_xlabel('Epoch')
ax.legend(loc='upper left')
save_plot(fig, 'accuracy_plot.png')
Assistant
code
# Plot training and validation loss
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['loss'], label='Training Loss')
if 'val_loss' in history.history:
ax.plot(history.history['val_loss'], label='Validation Loss')
else:
print("Validation loss not found in history.")
ax.set_title('Model Loss')
ax.set_ylabel('Loss')
ax.set_xlabel('Epoch')
ax.legend(loc='upper right')
save_plot(fig, 'loss_plot.png')
def calculate_accuracy_fluctuation(history):
if 'val_accuracy' in history.history:
accuracies = history.history['val_accuracy']
elif 'accuracy' in history.history:
accuracies = history.history['accuracy']
else:
print("Accuracy metric not found in history.")
return None, None
mean_accuracy = np.mean(accuracies)
fluctuation = np.sum(np.abs(accuracies - mean_accuracy))
return mean_accuracy, fluctuation
for i in range(4):
cv = control_values[i]
angle_q2 = angle_q2_values[i]
angle_q3_val = angle_q3_values[i]
# Flip control qubits if control value is 0
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# Apply double controlled RY gates
double_controlled_ry(control_qubits[0], control_qubits[1], data_qubits['q2'], angle_q2)
double_controlled_ry(control_qubits[0], control_qubits[1], data_qubits['q3'], angle_q3_val)
# Restore control qubits
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
Definition of swap gate
def apply_controlled_swap(swap_qubit, q_swap1, q_swap2):
"""
Modular method to apply a controlled SWAP gate.
code
Parameters:
- swap_qubit (int): Control qubit for the SWAP gate.
- q_swap1 (int): First qubit to swap.
- q_swap2 (int): Second qubit to swap.
"""
qml.Hadamard(wires=swap_qubit)
qml.CSWAP(wires=[swap_qubit, q_swap1, q_swap2])
qml.Hadamard(wires=swap_qubit)
def is_quantum_model(model):
for layer in model.layers:
if isinstance(layer, QuantumNeuralNetworkLayer):
return True
elif hasattr(layer, 'layers'):
if is_quantum_model(layer):
return True
return False
if name == "main":
# Load Penguins Dataset
penguins = sns.load_dataset('penguins')
code
# Drop samples with missing values
penguins = penguins.dropna()
# Features and labels
features = penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
categorical_features = penguins[['island', 'sex']]
# One-Hot encode categorical features
categorical_features_encoded = pd.get_dummies(categorical_features)
# Combine numerical and encoded categorical features
X = pd.concat([features, categorical_features_encoded], axis=1).values.astype(np.float32)
# Encode target variable
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(penguins['species'])
y = y.reshape(-1, 1)
# One-Hot encode labels
encoder = OneHotEncoder(sparse_output=False)
y_encoded = encoder.fit_transform(y).astype(np.float32)
num_classes = y_encoded.shape[1]
# Split into training and testing sets
x_full_train, x_test, y_full_train, y_test = train_test_split(
X, y_encoded, test_size=0.2, random_state=116, stratify=y_encoded
)
# Further split the training set into training and validation sets
x_train, x_val, y_train, y_val = train_test_split(
x_full_train, y_full_train, test_size=0.25, random_state=42, stratify=y_full_train
)
# Now, x_train is 60% of the data, x_val is 20%, x_test is 20%
# Standardize data (fit only on training set)
scaler = StandardScaler()
X_train_standardized = scaler.fit_transform(x_train).astype(np.float32)
X_val_standardized = scaler.transform(x_val).astype(np.float32)
X_test_standardized = scaler.transform(x_test).astype(np.float32)
# Apply PCA to reduce dimensionality to 4 components
pca = PCA(n_components=4) # 保留4个主成分
X_train_pca = pca.fit_transform(X_train_standardized)
X_val_pca = pca.transform(X_val_standardized)
X_test_pca = pca.transform(X_test_standardized)
# Map features to [0, π/2] range
min_max_scaler = MinMaxScaler(feature_range=(0, np.pi/2))
X_train_mapped = min_max_scaler.fit_transform(X_train_pca).astype(np.float32)
X_val_mapped = min_max_scaler.transform(X_val_pca).astype(np.float32)
X_test_mapped = min_max_scaler.transform(X_test_pca).astype(np.float32)
# Hyperparameters
learning_rate = 0.01 # Learning rate
epochs = 100 # Number of training epochs
batch_size = 16 # Batch size
n_qubits = 11 # 11 qubits as per the original QNN
n_layers = 3 # Number of layers
model = QuantumNeuralNetwork(
n_qubits=n_qubits,
n_layers=n_layers,
num_classes=num_classes
)
if is_quantum_model(model):
print("The model contains quantum neural network (QNN) layers.")
else:
print("The model does not contain quantum neural network (QNN) layers.")
# Draw the quantum circuit
sample_inputs = np.ones(4, dtype=np.float32) * (np.pi / 4) # Inputs mapped to [0, π/2]
sample_encoding_weights = np.zeros((3, n_layers, 4), dtype=np.float32)
sample_rot_weights = np.zeros((n_layers, n_qubits, 3), dtype=np.float32)
sample_entangle_weights = np.zeros((n_layers, n_qubits - 1), dtype=np.float32)
print("\nQuantum circuit diagram:")
print(qml.draw(quantum_neural_network)(sample_inputs, sample_encoding_weights, sample_rot_weights, sample_entangle_weights))
steps_per_epoch = len(X_train_mapped) // batch_size
total_steps = epochs * steps_per_epoch
# Create dataset (including validation set)
dataset = InMemoryDataset(
X_train_mapped,
y_train,
X_val_mapped,
y_val,
categorical=True
)
# Initialize reweighting policy
reweighting_policy = BiasedReweightingPolicy(k=1.0)
# Initialize importance sampling training
wrapped_model = ConstantTimeImportanceTraining(model, score="loss") # Use loss as score
# Modify sampler to use dynamic alpha and beta
def custom_sampler(dataset, batch_size, steps_per_epoch, epochs):
return ConstantTimeSampler(
dataset,
reweighting_policy,
model=wrapped_model.model,
)
# Assign custom sampler to wrapped_model
wrapped_model.sampler = custom_sampler
# Use per-sample loss function
loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=False, reduction=tf.keras.losses.Reduction.NONE)
# Compile model
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss=loss_fn,
metrics=['accuracy'],
run_eagerly=False # Set to False for better performance
)
# Create a callback class to save training metrics
class MetricsHistory(tf.keras.callbacks.Callback):
def on_train_begin(self, logs=None):
self.history = {'loss': [], 'accuracy': [], 'val_loss': [], 'val_accuracy': []}
def on_epoch_end(self, epoch, logs=None):
self.history['loss'].append(logs.get('loss'))
self.history['accuracy'].append(logs.get('accuracy'))
self.history['val_loss'].append(logs.get('val_loss'))
self.history['val_accuracy'].append(logs.get('val_accuracy'))
# Instantiate callbacks
metrics_history = MetricsHistory()
# Add early stopping callback
callbacks = [
metrics_history,
EarlyStopping(monitor='val_loss', patience=100, restore_best_weights=True)
]
# Train model using fit_dataset
history = wrapped_model.fit_dataset(
dataset=dataset,
batch_size=batch_size,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
verbose=1,
callbacks=callbacks
)
# Evaluate model on test set
score = wrapped_model.evaluate((X_test_mapped, y_test))
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Plot graphs using history from custom callback
plot_history(metrics_history)
mean_accuracy, fluctuation = calculate_accuracy_fluctuation(metrics_history)
if mean_accuracy is not None and fluctuation is not None:
print('Validation set mean accuracy:', mean_accuracy)
print('Accuracy fluctuation:', fluctuation)
# Close output file and restore stdout
sys.stdout = original_stdout
output_file.close()
print("Script execution completed. Please check 'penguins_layers=3.log' for print output and check the saved plots in the current directory.")
上述代码训练过程中在准确率为60%之后就基本不变了,如何提升准确率
The plateau in accuracy you're experiencing (around 60%) indicates that the model might be underfitting or that there are issues with the model architecture, data preprocessing, or training procedure. Here are several steps and suggestions to help improve the model's performance:
Simplify the Training Process:
Remove the importance sampling and custom training components (ConstantTimeImportanceTraining, BiasedReweightingPolicy, and custom samplers). These advanced techniques can introduce complexity and may not be necessary at this stage. Simplifying the training process will help isolate the issue.
Changes:
Remove the imports related to importance sampling:
python
# from importance_sampling.training import ConstantTimeImportanceTraining
# from importance_sampling.samplers import ConstantTimeSampler
# from importance_sampling.datasets import InMemoryDataset
# from importance_sampling.reweighting import BiasedReweightingPolicy
Remove the code that sets up the importance sampling and custom samplers.
Replace the custom training loop with TensorFlow's standard model.fit() method.
Modify the loss function to use the standard reduction method.
Modified Training Code:
python
# Use standard CategoricalCrossentropy loss function
loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=False)
# Compile the model
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss=loss_fn,
metrics=['accuracy'],
run_eagerly=False
)
# Train the model using the standard fit method
history = model.fit(
X_train_mapped, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(X_val_mapped, y_val),
callbacks=callbacks,
verbose=1
)
Adjust Data Preprocessing:
Use Original Features Without PCA:
Reducing dimensionality with PCA can sometimes lead to loss of important information, especially if too few components are retained. Since you have only nine features, consider using them all without PCA.
Changes:
Remove the PCA steps and use the standardized features directly:
python
# Remove PCA and use the standardized features directly
X_train_processed = X_train_standardized
X_val_processed = X_val_standardized
X_test_processed = X_test_standardized
Review Feature Scaling:
Ensure that scaling the features to the [0, π/2] range makes sense for your application. Alternatively, map the features to a different range, such as [0, 2π], or consider not scaling them if the quantum circuit can handle the original range.
Changes:
If you choose to scale features to [0, 2π]:
python
# Map features to [0, 2π] range
min_max_scaler = MinMaxScaler(feature_range=(0, 2 * np.pi))
X_train_mapped = min_max_scaler.fit_transform(X_train_processed).astype(np.float32)
X_val_mapped = min_max_scaler.transform(X_val_processed).astype(np.float32)
X_test_mapped = min_max_scaler.transform(X_test_processed).astype(np.float32)
Or, if you decide not to map the features:
python
# Use the standardized features without additional mapping
X_train_mapped = X_train_processed.astype(np.float32)
X_val_mapped = X_val_processed.astype(np.float32)
X_test_mapped = X_test_processed.astype(np.float32)
Increase Model Capacity:
Increase the Number of Layers and Qubits:
If the model is underfitting, increasing its capacity might help. You can try increasing the number of layers (n_layers) and possibly the number of qubits if your computational resources allow.
Changes:
python
# Increase the number of layers and qubits
n_qubits = 11 # Keep as is, or increase if feasible
n_layers = 5 # Increase from 3 to 5
Modify Classical Layers:
Consider adding more neurons to the classical dense layers or adding additional layers.
Changes:
python
# Modify classical layers
self.dense1 = tf.keras.layers.Dense(
32, # Increase from 16 to 32
activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.01),
dtype=tf.float32
)
self.dense2 = tf.keras.layers.Dense(
16, # Increase from 8 to 16
activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.01),
dtype=tf.float32
)
# Optionally add another dense layer
self.dense3 = tf.keras.layers.Dense(
8,
activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.01),
dtype=tf.float32
)
# Adjust the call method accordingly
def call(self, inputs):
q_output = self.quantum_layer(inputs)
x = self.dense1(q_output)
x = self.dense2(x)
x = self.dense3(x)
return self.output_layer(x)
Adjust Hyperparameters:
Increase the Number of Epochs:
The model might need more epochs to train fully. Try increasing the number of epochs to 200 or more.
Changes:
python
epochs = 200 # Increase from 100 to 200
Adjust the Learning Rate:
A lower learning rate can help the model converge more smoothly.
Changes:
python
learning_rate = 0.001 # Decrease from 0.01 to 0.001
Modify Batch Size:
Experiment with different batch sizes, such as 32 or 64, to see if that affects training.
Changes:
python
batch_size = 32 # Increase from 16 to 32
Verify Quantum Circuit Implementation:
There might be issues in how the gates are applied or how the quantum circuit is structured.
Check Rotations and Gates:
Ensure that the rotations and gates are correctly implemented and that they receive the correct parameters.
Visualize the Quantum Circuit:
Use qml.draw() to visualize the circuit and inspect if it aligns with your expectations.
Try simplifying the quantum circuit to a minimal version to ensure it's working correctly.
Train a Classical Neural Network for Comparison:
As a sanity check, train a purely classical neural network on the same dataset. If the classical model achieves significantly higher accuracy, this indicates that the issue might be with the quantum model's capacity or implementation.
Example Classical Model Code:
python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Define a simple classical neural network
classical_model = Sequential([
Dense(32, activation='relu', input_shape=(X_train_mapped.shape[1],)),
Dense(16, activation='relu'),
Dense(num_classes, activation='softmax')
])
# Compile the model
classical_model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Train the model
classical_model.fit(
X_train_mapped, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(X_val_mapped, y_val),
callbacks=callbacks,
verbose=1
)
# Evaluate on test set
score = classical_model.evaluate(X_test_mapped, y_test, verbose=0)
print('Classical model test loss:', score[0])
print('Classical model test accuracy:', score[1])
Monitor and Debug Training:
Check for Overfitting or Underfitting:
Plot the training and validation loss and accuracy. If both training and validation accuracy plateau at around 60%, the model is underfitting. If training accuracy is high but validation accuracy is low, the model is overfitting.
Use EarlyStopping with Patience:
Adjust the patience parameter in EarlyStopping to give the model more time to improve.
Verify that the labels are correctly encoded and match the outputs of the model.
Balance the Dataset:
If the classes are imbalanced, consider techniques like resampling to balance them.
Experiment with Different Activation Functions:
Try using different activation functions in the classical layers to see if they improve performance.
Changes:
python
self.dense1 = tf.keras.layers.Dense(
32,
activation='tanh', # Change from 'relu' to 'tanh'
kernel_regularizer=tf.keras.regularizers.l2(0.01),
dtype=tf.float32
)
Regularization Techniques:
Adjust Regularization Parameters:
The L2 regularization factor (0.01) might be too high, causing the model to underfit. Try reducing it.
Changes:
python
regularizer = tf.keras.regularizers.l2(0.001) # Decrease from 0.01 to 0.001
Add Dropout Layers:
Introduce dropout to prevent overfitting.
Changes:
python
self.dropout = tf.keras.layers.Dropout(0.3)
def call(self, inputs):
q_output = self.quantum_layer(inputs)
x = self.dense1(q_output)
x = self.dropout(x)
x = self.dense2(x)
x = self.dropout(x)
return self.output_layer(x)
By implementing these changes step by step, you can identify what impacts the model's performance and incrementally improve it. Remember to change one thing at a time to isolate its effect. This systematic approach will help you pinpoint the factors that lead to better accuracy and a more effective model.