ValueError: Must specify a shape for every non-input parameter in the QNode

X, y = make_moons(n_samples=200, noise=0.1)
y_hot = tf.keras.utils.to_categorical(y, num_classes=2)

n_qubits = 2
n_layers = 4
dev = qml.device("strawberryfields.fock", wires=2, cutoff_dim=4) 

def layer(theta, phi, wires):
    M = len(wires)
    phi_nonlinear = np.pi / 2

    qml.templates.Interferometer(
        theta, phi, np.zeros(M), wires=wires, mesh="rectangular", beamsplitter="pennylane"
    )

    for i in wires:
        qml.Kerr(phi_nonlinear, wires=i)

@qml.qnode(dev, interface="tf")
def quantum_neural_net(inputs, weights):
    wires = list(range(len(inputs)))

    for i in wires:
        qml.FockState(inputs[i], wires=i)

    # "layer" subcircuits
    for i, v in enumerate(weights):
        layer(v[: len(v) // 2], v[len(v) // 2 :], wires)

    return [qml.expval(qml.NumberOperator(w)) for w in wires]

qlayer = qml.qnn.KerasLayer(quantum_neural_net, weight_shapes, output_dim=4)

model.add(qlayer)
opt = tf.keras.optimizers.SGD()
model.compile(opt, loss = 'mae', metrics =['accuracy'])

history = model.fit(X, y_hot, epochs=2, batch_size=4, validation_split=0.25, verbose=2)

When i try to run qlayer with qml.qnn…it throws an error of shape.
and not able to fit the model.
Can you please look in to it.

Hey @Amandeep, can you please include all of your imports, the full error message, and your package versions?

Hi @isaacdevlugt

import tensorflow as tf
import pennylane as qml

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons

# Set random seeds
np.random.seed(42)
tf.random.set_seed(42)

from tensorflow import keras
from tensorflow.keras import layers

#pennylane=0.28.0

@isaacdevlugt
I changed the code. Trying to work with qnode. It works but the issue is that the model accuracy and loss not making any progress as it showing in Turning quantum nodes into Keras Layers — PennyLane documentation

weight_shapes = {"weights": (6, 2)}
weight_shapes

qlayer = qml.qnn.KerasLayer(quantum_neural_net, weight_shapes, output_dim=2)
clayer_2 = tf.keras.layers.Dense(2, activation="softmax")
model = tf.keras.models.Sequential([qlayer, clayer_2])

opt = keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss = 'mae', metrics =['accuracy'])

fitting = model.fit(X, y_hot, epochs=10, batch_size=8, validation_split=0.25, verbose=2)

rest of the above code remains same.

Can you please place the full code in one area? It’s not obvious to me how everything gets pieced together to match exactly what you have.

@isaacdevlugt here’s the code

import tensorflow as tf
import pennylane as qml

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons

# Set random seeds
np.random.seed(42)
tf.random.set_seed(42)

from tensorflow import keras
from tensorflow.keras import layers


tf.keras.backend.set_floatx('float64')

X, y = make_moons(n_samples=200, noise=0.1)
y_hot = tf.keras.utils.to_categorical(y, num_classes=2)  # one-hot encoded labels

n_qubits = 2
n_layers = 4
dev = qml.device("strawberryfields.fock", wires=2, cutoff_dim=4) 

def layer(theta, phi, wires):
    M = len(wires)
    phi_nonlinear = np.pi / 2

    qml.templates.Interferometer(
        theta, phi, np.zeros(M), wires=wires, mesh="rectangular", beamsplitter="pennylane"
    )

    for i in wires:
        qml.Kerr(phi_nonlinear, wires=i)

@qml.qnode(dev)
def quantum_neural_net(inputs, weights):
    wires = list(range(len(inputs)))

    for i in wires:
        qml.FockState(inputs[i], wires=i)

    # "layer" subcircuits
    for i, v in enumerate(weights):
        layer(v[: len(v) // 2], v[len(v) // 2 :], wires)

    return [qml.expval(qml.NumberOperator(w)) for w in wires]

weight_shapes = {"weights": (6, 2)}
weight_shapes

qlayer = qml.qnn.KerasLayer(quantum_neural_net, weight_shapes, output_dim=2)
clayer_2 = tf.keras.layers.Dense(2, activation="softmax")
model = tf.keras.models.Sequential([qlayer, clayer_2])

opt = keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss = 'mae', metrics =['accuracy'])

fitting = model.fit(X, y_hot, epochs=10, batch_size=8, validation_split=0.25, verbose=2)

It works but the issue is that the model accuracy and loss not making any progress as it showing in Turning quantum nodes into Keras Layers — PennyLane documentation

… the model accuracy and loss not making any progress …

You’re trying out a very different hybrid model here compared to what’s in the tutorial. I was able to run your code and see that your loss and accuracy are changing, albeit not very much. This is probably an opportunity to reflect on your quantum model’s structure, your optimizer, and other hyperparameters.

@isaacdevlugt

is there anything missing? or I need to add

The code works in that it’s doing what it’s programmed to do. It’s just not doing it very well :sweat_smile:. It’s probably a good idea to tinker with hyperparameters, different loss functions, etc.

1 Like