Skip to content

Commit 7a32859

Browse files
committed
update
1 parent b06f0fe commit 7a32859

File tree

2 files changed

+106
-0
lines changed

2 files changed

+106
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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}%")
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import pennylane as qml
2+
from pennylane import numpy as np
3+
from sklearn.datasets import make_classification
4+
from sklearn.model_selection import train_test_split
5+
from sklearn.preprocessing import StandardScaler
6+
7+
# Step 1: Generate a simple binary classification dataset
8+
X, y = make_classification(n_samples=100, n_features=2, n_informative=2,
9+
n_redundant=0, n_classes=2, random_state=42)
10+
X = StandardScaler().fit_transform(X)
11+
y = y * 2 - 1 # Convert to {-1, 1} for compatibility with Pauli measurements
12+
13+
# Step 2: Define the quantum device and circuit
14+
n_qubits = 2
15+
dev = qml.device("default.qubit", wires=n_qubits)
16+
17+
# Step 3: Encode classical data into quantum state
18+
def encode_data(x):
19+
qml.RY(x[0], wires=0)
20+
qml.RY(x[1], wires=1)
21+
22+
# Step 4: Variational circuit (the "neural network")
23+
def variational_layer(weights):
24+
qml.CNOT(wires=[0, 1])
25+
qml.RY(weights[0], wires=0)
26+
qml.RY(weights[1], wires=1)
27+
28+
@qml.qnode(dev)
29+
def qnn_circuit(x, weights):
30+
encode_data(x)
31+
variational_layer(weights)
32+
return qml.expval(qml.PauliZ(0))
33+
34+
# Step 5: Define cost function
35+
def cost(weights, X, y):
36+
predictions = [qnn_circuit(x, weights) for x in X]
37+
return np.mean((predictions - y)**2)
38+
39+
# Step 6: Train the QNN
40+
weights = np.random.uniform(low=0, high=2 * np.pi, size=(2,), requires_grad=True)
41+
opt = qml.GradientDescentOptimizer(stepsize=0.2)
42+
43+
for epoch in range(30):
44+
weights = opt.step(lambda w: cost(w, X, y), weights)
45+
current_loss = cost(weights, X, y)
46+
print(f"Epoch {epoch+1:02d} | Loss: {current_loss:.4f}")
47+
48+
# Step 7: Prediction example
49+
sample = X[0]
50+
predicted = qnn_circuit(sample, weights)
51+
print(f"Prediction for sample {sample}: {predicted:.3f}")

0 commit comments

Comments
 (0)