To improve the accuracy of your quantum neural network model on the Iris dataset without modifying the importance sampling part or the quantum neural network's quantum section, you can make several adjustments to the classical components of your model and the training process. Below is the complete modified code with detailed explanations of the changes:
-
Increase the Number of Epochs and Adjust Early Stopping:
- Epochs: Increased from 100 to 300 to allow the model more time to learn.
- Early Stopping Patience: Increased from 5 to 20 to prevent premature stopping, allowing the model to find a better optimum.
-
Adjust the Learning Rate:
- Reduced the learning rate from
0.01 to 0.001 to enable more stable and gradual convergence.
-
Enhance the Classical Layers:
- Dense Layers: Added an additional Dense layer with 128 units to increase the model's capacity to learn complex patterns.
- Dropout Rate: Reduced the dropout rate from
0.5 to 0.3 to prevent over-regularization while still mitigating overfitting.
- Batch Normalization: Introduced a Batch Normalization layer to stabilize and accelerate training.
-
Increase Batch Size:
- Increased the batch size from
8 to 16 to make better use of the available data and stabilize gradient estimates.
-
Optimizer Adjustments:
- Ensured the use of the Adam optimizer with the new learning rate.
-
Additional Enhancements:
- Weight Decay: Maintained L2 regularization to prevent overfitting.
- Verbose Output: Kept
verbose=1 for detailed training logs.
Here is the complete modified code incorporating these 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, StandardScaler
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from pennylane.qnn.keras import KerasLayer
from tensorflow.keras.callbacks import EarlyStopping
# Redirect stdout to capture print outputs
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):
# Plot training and validation accuracy
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['accuracy'], label='Train Accuracy')
ax.plot(history.history['val_accuracy'], label='Validation Accuracy')
ax.set_title('Model Accuracy')
ax.set_ylabel('Accuracy')
ax.set_xlabel('Epoch')
ax.legend(loc='upper left')
save_plot(fig, 'accuracy_plot.png')
# Plot training and validation loss
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['loss'], label='Train Loss')
ax.plot(history.history['val_loss'], label='Validation Loss')
ax.set_title('Model Loss')
ax.set_ylabel('Loss')
ax.set_xlabel('Epoch')
ax.legend(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
# Define the quantum device with 14 qubits
dev = qml.device("default.qubit", wires=14)
def encode_group(control_qubits, data_qubits, angle_q2, angle_q3):
control_values = [[0, 0], [0, 1], [1, 0], [1, 1]]
for i in range(4):
cv = control_values[i]
angle_q3_val = angle_q3[i]
# Flip control qubits that are 0 for controlled operations
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# Apply controlled RY rotations
qml.ctrl(qml.RY, control=control_qubits)(angle_q2, wires=data_qubits['q2'])
qml.ctrl(qml.RY, control=control_qubits)(angle_q3_val, wires=data_qubits['q3'])
# Restore control qubits
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
def apply_controlled_swap(swap_qubit, q_swap1, q_swap2):
"""
Modular method to apply a controlled SWAP gate.
Parameters:
- swap_qubit (int): The control qubit for the SWAP gate.
- q_swap1 (int): The first qubit to be swapped.
- q_swap2 (int): The second qubit to be swapped.
"""
qml.Hadamard(wires=swap_qubit)
qml.CSWAP(wires=[swap_qubit, q_swap1, q_swap2])
qml.Hadamard(wires=swap_qubit)
@qml.qnode(dev, interface='tf', diff_method='backprop')
def quantum_neural_network(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
encoding_data = [
{'data_qubits': {'q2': 2, 'q3': 3}, 'swap_qubit': 4},
{'data_qubits': {'q2': 5, 'q3': 6}, 'swap_qubit': 7},
{'data_qubits': {'q2': 8, 'q3': 9}, 'swap_qubit': 10},
{'data_qubits': {'q2': 11, 'q3': 12}, 'swap_qubit': 13}
]
# Map input data to angles_q2
angles_q2_list = inputs[:4] # Using 4 input features
# Map encoding_weights to angles_q3
angles_q3_list = encoding_weights[:4, :, :4] # Shape: (4, n_layers, 4)
# Encoding process
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] # Scalar tensor
for layer in range(rot_weights.shape[0]):
angle_q3_values = angles_q3_list[idx, layer, :] # Shape: (4,)
encode_group(control_qubits, data_qubits, angle_q2, angle_q3_values)
# Apply swap operations
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'])
# Apply Rot layers
for layer in range(rot_weights.shape[0]):
for qubit in range(rot_weights.shape[1]):
rot_angles = rot_weights[layer, qubit, :] # Shape: (3,)
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# Measure PauliZ expectation values
results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]
return results
# Define a QNode for circuit drawing
@qml.qnode(dev)
def quantum_neural_network_draw(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
encoding_data = [
{'data_qubits': {'q2': 2, 'q3': 3}, 'swap_qubit': 4},
{'data_qubits': {'q2': 5, 'q3': 6}, 'swap_qubit': 7},
{'data_qubits': {'q2': 8, 'q3': 9}, 'swap_qubit': 10},
{'data_qubits': {'q2': 11, 'q3': 12}, 'swap_qubit': 13}
]
# Map input data to angles_q2
angles_q2_list = inputs[:4] # Using 4 input features
# Map encoding_weights to angles_q3
angles_q3_list = encoding_weights[:4, :, :4] # Shape: (4, n_layers, 4)
# Encoding process
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] # Scalar tensor
for layer in range(rot_weights.shape[0]):
angle_q3_values = angles_q3_list[idx, layer, :] # Shape: (4,)
encode_group(control_qubits, data_qubits, angle_q2, angle_q3_values)
# Apply swap operations
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'])
# Apply Rot layers
for layer in range(rot_weights.shape[0]):
for qubit in range(rot_weights.shape[1]):
rot_angles = rot_weights[layer, qubit, :] # Shape: (3,)
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# Measure PauliZ expectation values
results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]
return results
# Define a Quantum Neural Network Layer
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
def __init__(self, n_qubits, n_layers, num_classes, **kwargs):
super(QuantumNeuralNetworkLayer, self).__init__(**kwargs)
self.n_qubits = n_qubits
self.n_layers = n_layers
self.num_classes = num_classes
# Define encoding weights
self.encoding_weights = self.add_weight(
shape=(4, n_layers, 4), # 4 encoding groups, each with 4 angles per layer
initializer=tf.keras.initializers.GlorotUniform(),
trainable=True,
name='encoding_weights',
dtype=tf.float64
)
# Define rotation layer weights
self.rot_weights = self.add_weight(
shape=(n_layers, n_qubits, 3),
initializer=tf.keras.initializers.GlorotUniform(),
trainable=True,
name='rot_weights',
dtype=tf.float64
)
def call(self, inputs):
def apply_qnode(x):
x = tf.cast(x, dtype=tf.float64)
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
return tf.cast(result, dtype=tf.float32)
outputs = tf.map_fn(
apply_qnode,
inputs,
dtype=tf.float32
)
# Print weights for debugging
tf.print("Encoding Weights:", self.encoding_weights)
tf.print("Rot Weights:", self.rot_weights)
return outputs
# Define the Quantum Neural Network Model
class QuantumNeuralNetwork(tf.keras.Model):
def __init__(self, n_qubits, n_layers, num_classes, **kwargs):
super(QuantumNeuralNetwork, self).__init__(**kwargs)
self.n_qubits = n_qubits
self.n_layers = n_layers
self.num_classes = num_classes
# Quantum layer
self.quantum_layer = QuantumNeuralNetworkLayer(n_qubits, n_layers, num_classes)
# Classical layers with enhancements
self.dense1 = Dense(128, activation='relu') # Increased units
self.batch_norm1 = BatchNormalization() # Added Batch Normalization
self.dropout1 = Dropout(0.3) # Reduced dropout rate
self.dense2 = Dense(64, activation='relu') # Added another Dense layer
self.batch_norm2 = BatchNormalization() # Added another Batch Normalization
self.dropout2 = Dropout(0.3) # Reduced dropout rate
self.output_layer = Dense(num_classes, activation='softmax',
kernel_regularizer=tf.keras.regularizers.l2(0.01))
def call(self, inputs):
q_output = self.quantum_layer(inputs)
x = self.dense1(q_output)
x = self.batch_norm1(x)
x = self.dropout1(x)
x = self.dense2(x)
x = self.batch_norm2(x)
x = self.dropout2(x)
return self.output_layer(x)
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)
# Data Standardization
scaler = StandardScaler()
X = scaler.fit_transform(X)
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, stratify=y
)
# Hyperparameters
learning_rate = 0.001 # Reduced learning rate
epochs = 300 # Increased number of epochs
batch_size = 16 # Increased batch size
num_classes = 3
n_qubits = 14 # 14 qubits (0 to 13)
n_layers = 2 # Two layers
model = QuantumNeuralNetwork(
n_qubits=n_qubits,
n_layers=n_layers,
num_classes=num_classes
)
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate), # Using Adam optimizer
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(4, dtype=np.float64) * (np.pi / 2) # Using float64 with 4 input features
sample_encoding_weights = np.zeros((4, n_layers, 4), dtype=np.float64) # encoding_weights
sample_rot_weights = np.zeros((n_layers, n_qubits, 3), dtype=np.float64) # rot_weights
print(qml.draw(quantum_neural_network_draw)(sample_inputs, sample_encoding_weights, sample_rot_weights)) # Use QNode for drawing
# Early stopping callback with increased patience
early_stopping = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True)
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),
callbacks=[early_stopping] # Added early stopping
)
else:
history = model.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[early_stopping] # Added early stopping
)
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)
# Close the output file and restore stdout
sys.stdout = original_stdout
output_file.close()
print("Script execution completed. Check 'output.log' for print outputs and the current directory for saved plots.")
Summary of Changes:
-
Training Parameters:
- Epochs: Increased to 300.
- Learning Rate: Decreased to 0.001.
- Batch Size: Increased to 16.
- Early Stopping: Patience increased to 20 epochs.
-
Model Architecture:
- Dense Layers: Added an additional Dense layer with 128 units and another with 64 units.
- Batch Normalization: Introduced to stabilize and speed up training.
- Dropout: Reduced dropout rates to 0.3 to allow the model to retain more information while still preventing overfitting.
-
Data Splitting:
- Stratification: Ensured that the train-test split maintains the class distribution by adding
stratify=y.
-
Additional Enhancements:
- Comments: Added detailed comments for clarity.
- Plot Labels: Enhanced plot labels for better readability.
Expected Outcome:
These modifications should help the model train more effectively, potentially leading to higher validation and test accuracies. The increased capacity of the classical part of the model, combined with more training epochs and stabilized training dynamics through batch normalization, should allow the model to better capture the underlying patterns in the Iris dataset.
Next Steps:
-
Run the Modified Script:
- Execute the script and monitor the training logs in
output.log.
- Check the saved plots (
accuracy_plot.png and loss_plot.png) to visualize the training progress.
-
Evaluate Performance:
- After training, assess whether the test accuracy has improved beyond 86%.
- If further improvements are needed, consider experimenting with additional hyperparameters or slightly different architectures while keeping the core quantum components unchanged.
-
Fine-Tuning:
- If the model still does not achieve the desired accuracy, you might explore other classical optimization techniques, data augmentation, or ensemble methods to enhance performance.
By implementing these changes, you should observe a more stable training process and an improvement in the model's ability to generalize to unseen data.