|
| 1 | + |
| 2 | +import pennylane as qml |
| 3 | +from pennylane import numpy as np |
| 4 | +import tensorflow as tf |
| 5 | +from sklearn.datasets import make_classification |
| 6 | +from sklearn.preprocessing import StandardScaler |
| 7 | +from sklearn.model_selection import train_test_split |
| 8 | + |
| 9 | +# Generate dataset |
| 10 | +X, y = make_classification(n_samples=200, n_features=2, n_informative=2, |
| 11 | + n_redundant=0, n_classes=2, random_state=42) |
| 12 | +X = StandardScaler().fit_transform(X) |
| 13 | +y = y.reshape(-1, 1) |
| 14 | + |
| 15 | +# Split dataset |
| 16 | +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) |
| 17 | + |
| 18 | +# Quantum circuit parameters |
| 19 | +n_qubits = 2 |
| 20 | +dev = qml.device("default.qubit", wires=n_qubits) |
| 21 | + |
| 22 | +# Define the QNN layer using a variational circuit |
| 23 | +def qnn_circuit(inputs, weights): |
| 24 | + for i in range(n_qubits): |
| 25 | + qml.RY(inputs[i], wires=i) |
| 26 | + qml.CNOT(wires=[0, 1]) |
| 27 | + for i in range(n_qubits): |
| 28 | + qml.RY(weights[i], wires=i) |
| 29 | + return qml.expval(qml.PauliZ(0)) |
| 30 | + |
| 31 | +weight_shapes = {"weights": (n_qubits,)} |
| 32 | + |
| 33 | +qlayer = qml.qnn.KerasLayer(qml.QNode(qnn_circuit, dev, interface="tf", diff_method="parameter-shift"), |
| 34 | + weight_shapes, output_dim=1) |
| 35 | + |
| 36 | +# Build a hybrid quantum-classical model |
| 37 | +model = tf.keras.models.Sequential([ |
| 38 | + tf.keras.layers.Input(shape=(2,)), |
| 39 | + qlayer, |
| 40 | + tf.keras.layers.Activation("sigmoid") |
| 41 | +]) |
| 42 | + |
| 43 | +#tf.keras.optimizers.legacy.Adam |
| 44 | + |
| 45 | +# Compile the model |
| 46 | +model.compile(optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.1), |
| 47 | + loss="binary_crossentropy", |
| 48 | + metrics=["accuracy"]) |
| 49 | + |
| 50 | +# Train the model |
| 51 | +model.fit(X_train, y_train, epochs=30, batch_size=16, validation_split=0.1) |
| 52 | + |
| 53 | +# Evaluate the model |
| 54 | +loss, accuracy = model.evaluate(X_test, y_test) |
| 55 | +print(f"Test accuracy: {accuracy * 100:.2f}%") |
0 commit comments