Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first (to be fixed) layers test with keras #15

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/qiboml/models/layers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from qiboml.models.layers.training import QuantumLayer
1 change: 1 addition & 0 deletions src/qiboml/models/layers/encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Encoding layers with Qiboml."""
32 changes: 32 additions & 0 deletions src/qiboml/models/layers/training.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import keras
import qibo
import tensorflow as tf


class QuantumLayer(keras.layers.Layer):
def __init__(self, circuit: qibo.Circuit, **kwargs):
super().__init__(**kwargs)
self.circuit = circuit
nparams = len(circuit.get_parameters())
self.qparams = self.add_weight(
shape=(nparams,),
initializer="random_normal",
trainable=True,
dtype="float64",
)

def call(self, inputs):
# Check input shape
if inputs.shape[1] != 2**self.circuit.nqubits:
raise ValueError(
f"Input of a QuantumLayer has to be a vector of length 2**{self.circuit.nqubits}"
)
# Update circuit parameters with trainable weights
self.circuit.set_parameters(self.qparams.value)
# Execute circuit
state = self.circuit(initial_state=inputs).state()
# Ensure return type is compatible with TensorFlow
return tf.abs(state)

def compute_output_shape(self, input_shape):
return (input_shape[0], 2**self.circuit.nqubits)
49 changes: 49 additions & 0 deletions test_keras.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import os

import keras
import matplotlib.pyplot as plt
import numpy as np

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"

import tensorflow as tf

tf.get_logger().setLevel("ERROR")


import qibo

import qiboml
import qiboml.models
import qiboml.models.layers
from qiboml.models.ansatze import reuploading_circuit

qibo.set_backend("tensorflow")

x = np.linspace(-1, 1, 500)
y = np.sin(6 * x) ** 2 + np.random.normal(0, 0.1, 500)

nqubits = 3
nlayers = 1

circuit = reuploading_circuit(nqubits, nlayers)

model = keras.Sequential()
model.add(keras.layers.Input(shape=(1,)))
model.add(keras.layers.Dense(2**nqubits, activation="relu"))
model.add(qiboml.models.layers.QuantumLayer(circuit=circuit))
model.add(keras.layers.Dense(32, input_shape=(8,), activation="relu"))
model.add(keras.layers.Dense(1, activation="linear"))
model.compile(optimizer="adam", loss="mse")
model.summary()

model.fit(x, y, batch_size=32, epochs=100)

test_x = np.linspace(-1, 1, 100)
test_y = model.predict(test_x)

plt.figure(figsize=(6, 6 * 6 / 8))
plt.plot(x, y, marker=".", color="royalblue", label="Training")
plt.plot(test_x, test_y, marker=".", color="red", label="Test")
plt.legend()
plt.savefig("data.png")
Loading