Hello,
I am trying to follow this tutorial to try and connect a quantum circuit to a pretrained CNN. I keep getting this error when trying to use model.add(qlayer)
:
ValueError: Cannot infer num from shape (None, 2)
For reference I load in a model and then replace the final layers with a Dense(2)
layer to try to be consistent with the tutorial. Here are the final few layers of the model architecture:
batch_normalization_11 (Batc (None, 256) 1024
dense_6 (Dense) (None, 512) 131584
dense_7 (Dense) (None, 2) 1026
Does this error have to do with the variable batch size or is there something else that I am missing from the tutorial?
Thanks for your help!
Edit:
I got past the error by changing the imports to be consistent. I was importing from keras
and tensorflow
. I changed my imports to be:
import tensorflow as tf
from tensorflow import keras
That seemed to solve the Value error I was encountering but is brought up another problem. When I add the Quantum Keras Layer It has 0 params and is unused. How can I fix that?
import tensorflow as tf
from tensorflow import keras
import pennylane as qml
tf.keras.backend.set_floatx('float64')
base_model = keras.models.load_model('mnist_base_model.h5')
model = keras.models.Sequential()
for layer in base_model.layers[:-1]: # go through until last layer probably better way to do this
model.add(layer)
model.layers[-1].trainable = False
flat = tf.keras.layers.Flatten()
downsize_layer = tf.keras.layers.Dense(10)
model.add(Dense(10))
n_qubits = 2
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def qnode(inputs, weights):
qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
qml.templates.BasicEntanglerLayers(weights, wires=range(n_qubits))
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
n_layers = 6
weight_shapes = {"weights": (n_layers, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)
clayer = tf.keras.layers.Dense(2, activation="softmax")
model.add(qlayer)
model.add(clayer)
model.summary()
dense_6 (Dense) (None, 512) 131584
dense_40 (Dense) (None, 10) 5130
keras_layer_26 (KerasLayer) (None, 2) 0 (unused)
dense_41 (Dense) (None, 2) 6
Total params: 692,688
Trainable params: 5,136
Non-trainable params: 687,552