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 # Use public API
from example_utils import get_parser # Ensure this module exists
from importance_sampling.training import ConstantTimeImportanceTraining # Ensure this module exists
from pennylane.qnn.keras import KerasLayer
# 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'])
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')
# Plot training and validation loss
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
# Set Keras default float type to float64
tf.keras.backend.set_floatx('float64')
# Increase number of qubits to 17 (0 to 16)
n_encoding_groups = 4 # Iris dataset has 4 features, hence 4 encoding groups
n_qubits = 17 # Adjust to 17 qubits to accommodate ancilla=16
dev = qml.device("lightning.qubit", wires=n_qubits)
def multi_controlled_RY(angle, control_qubits, target, ancilla):
"""
Implement a double-controlled RY gate decomposition.
"""
qml.CNOT(wires=[control_qubits[0], ancilla])
qml.CNOT(wires=[control_qubits[1], ancilla])
qml.RY(angle / 2, wires=target)
qml.CNOT(wires=[ancilla, target])
qml.RY(-angle / 2, wires=target)
qml.CNOT(wires=[control_qubits[1], ancilla])
qml.CNOT(wires=[control_qubits[0], ancilla])
def encode_group(control_qubits, data_qubits, angle_q2, angle_q3, ancilla):
"""
Modular method for angle encoding on a group of qubits.
"""
control_values = [[0, 0], [0, 1], [1, 0], [1, 1]]
for cv, angle_q3_val in zip(control_values, angle_q3):
# Flip control qubits that are 0 to use controlled RY gates
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# Apply multi-controlled RY rotation on q2
multi_controlled_RY(angle_q2, control_qubits, data_qubits['q2'], ancilla)
# Apply multi-controlled RY rotation on q3
multi_controlled_RY(angle_q3_val, control_qubits, data_qubits['q3'], ancilla)
# Restore control qubits to original state
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.
"""
# Apply Hadamard gate to swap_qubit
qml.Hadamard(wires=swap_qubit)
# Apply controlled SWAP gate
qml.CSWAP(wires=[swap_qubit, q_swap1, q_swap2])
# Apply Hadamard gate again to restore swap_qubit
qml.Hadamard(wires=swap_qubit)
# Define a Quantum Node (QNode) for KerasLayer
@qml.qnode(dev, interface='tf', diff_method='parameter-shift')
def quantum_neural_network_for_keras(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
ancillas = [12, 13, 14, 15] # Adjusted for 17 qubits
encoding_data = [
{'data_qubits': {'q2': 2, 'q3': 3}, 'swap_qubit': 4, 'ancilla': 12},
{'data_qubits': {'q2': 5, 'q3': 6}, 'swap_qubit': 7, 'ancilla': 13},
{'data_qubits': {'q2': 8, 'q3': 9}, 'swap_qubit': 10, 'ancilla': 14},
{'data_qubits': {'q2': 11, 'q3': 12}, 'swap_qubit': 15, 'ancilla': 16}
]
n_layers = rot_weights.shape[0]
for layer in range(n_layers):
for idx, data_set in enumerate(encoding_data):
data_qubits = data_set['data_qubits']
swap_qubit = data_set['swap_qubit']
ancilla = data_set['ancilla']
# Ensure inputs are correctly shaped
angle_q2 = inputs[idx, 0] * encoding_weights[idx, layer, 0]
angle_q3 = inputs[idx, 1:5] * encoding_weights[idx, layer, 1:5]
angles_q2 = [angle_q2] * 4 # To match control_values in encode_group
encode_group(control_qubits, data_qubits, angle_q2, angle_q3, ancilla)
# Apply swap operations after encoding for this layer
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 rotation layers for this layer
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)
# Measurement
results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]
return results
# Define a Quantum Node (QNode) for drawing the circuit
@qml.qnode(dev)
def quantum_neural_network_draw(inputs, encoding_weights, rot_weights):
control_qubits = [0, 1]
ancillas = [12, 13, 14, 15]
encoding_data = [
{'data_qubits': {'q2': 2, 'q3': 3}, 'swap_qubit': 4, 'ancilla': 12},
{'data_qubits': {'q2': 5, 'q3': 6}, 'swap_qubit': 7, 'ancilla': 13},
{'data_qubits': {'q2': 8, 'q3': 9}, 'swap_qubit': 10, 'ancilla': 14},
{'data_qubits': {'q2': 11, 'q3': 12}, 'swap_qubit': 15, 'ancilla': 16}
]
n_layers = rot_weights.shape[0]
for layer in range(n_layers):
for idx, data_set in enumerate(encoding_data):
data_qubits = data_set['data_qubits']
swap_qubit = data_set['swap_qubit']
ancilla = data_set['ancilla']
angle_q2 = inputs[idx, 0] * encoding_weights[idx, layer, 0]
angle_q3 = inputs[idx, 1:5] * encoding_weights[idx, layer, 1:5]
angles_q2 = [angle_q2] * 4
encode_group(control_qubits, data_qubits, angle_q2, angle_q3, ancilla)
# Apply swap operations after encoding for this layer
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['q3'], data_set['q2'])
# Apply rotation layers for this layer
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)
# Measurement
results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]
return results
# Define a Quantum Neural Network Layer using KerasLayer
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 Quantum Layer using KerasLayer
self.quantum_layer = KerasLayer(
quantum_neural_network_for_keras,
weight_shapes={
"encoding_weights": (n_encoding_groups, n_layers, 4), # 4 encoding groups
"rot_weights": (n_layers, n_qubits, 3)
},
output_dim=n_encoding_groups # Output dimension set to number of encoding groups
)
def call(self, inputs):
return self.quantum_layer(inputs)
# 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 Dense layer with float64
self.dense = Dense(num_classes, activation='softmax', dtype='float64')
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()
# Load and preprocess Iris dataset
iris = load_iris()
X = iris['data'].astype(np.float64) # Ensure data type is float64
y = iris['target'].reshape(-1, 1)
# Handle scikit-learn version differences
import sklearn
from packaging import version
sklearn_version = sklearn.__version__
print(f"scikit-learn version: {sklearn_version}")
if version.parse(sklearn_version) >= version.parse("1.2"):
encoder = OneHotEncoder(sparse_output=False)
else:
encoder = OneHotEncoder(sparse=False)
y = encoder.fit_transform(y).astype(np.float64) # Convert to float64
# Split into training and testing sets
x_train, x_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=116
)
# Hyperparameters
learning_rate = 0.05
epochs = 100
batch_size = 8
num_classes = 3 # Iris dataset has 3 classes
n_qubits = n_qubits # Already set to 17
n_layers = 3 # Three layers
# Create the model
model = QuantumNeuralNetwork(
n_qubits=n_qubits,
n_layers=n_layers,
num_classes=num_classes
)
# Compile the model
optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate)
model.compile(
optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Function to check if model contains a Quantum layer
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:")
# Use NumPy constants and ensure type is float64
sample_inputs = np.ones((4,), dtype=np.float64) * (np.pi / 2) # 4 input features
sample_encoding_weights = np.zeros((4, n_layers, 4), dtype=np.float64) # 4 encoding groups
sample_rot_weights = np.zeros((n_layers, n_qubits, 3), dtype=np.float64) # float64
print(qml.draw(quantum_neural_network_draw)(sample_inputs, sample_encoding_weights, sample_rot_weights)) # Use draw QNode
# Train the model
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)
)
# Evaluate the model
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Calculate and display mean and fluctuation of validation accuracy
mean_accuracy, fluctuation = calculate_accuracy_fluctuation(history)
print('Mean validation accuracy:', mean_accuracy)
print('Accuracy fluctuation:', fluctuation)
# Plot training history
plot_history(history)
# Close 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.")