QNN KerasLayer with Model

Hey @cnada,

PennyLane’s KerasLayer is a subclass of the Layer class in Keras. This means that you can treat it just like any other layer in Keras.

For example, suppose we turn our QNode into a Keras Layer:

qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=2)

We can use the Sequential model to create a hybrid:

clayer = tf.keras.layers.Dense(2)
clayer2 = tf.keras.layers.Dense(2)
model = tf.keras.models.Sequential([clayer, qlayer, clayer2])

We can also use Keras’ functional API approach:

inputs = tf.keras.Input(shape=(2,))
x = tf.keras.layers.Dense(2, activation="tanh")(inputs)
x = qlayer(x)
outputs = tf.keras.layers.Dense(2)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)

You can also add qlayer to an existing model using:

  • model.add(qlayer) is using a Sequential model
  • If using the functional API approach:
outputs2 = qlayer(outputs)
model = tf.keras.Model(inputs=inputs, outputs=outputs2)

Hope this helps!