Clayer qlayer qnode keras giving ValueError: You tried to call count_params on layer keras_layer_4, but the layer isn't built. You can build it manually via: keras_layer_4.build(batch_input_shape)

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)

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

import pennylane as qml

n_qubits = 2
dev = qml.device(“default.qubit”, wires=n_qubits)

n_layers = 6
weight_shapes = {“weights”: (n_layers, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)

@qml.qnode(dev)
def qnode(inputs, weights):
qml.AngleEmbedding(inputs, wires=range(n_qubits))
qml.BasicEntanglerLayers(weights, wires=range(n_qubits))
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]

re-define the layers

clayer_1 = tf.keras.layers.Dense(4)
qlayer_1 = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)
qlayer_2 = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)
clayer_2 = tf.keras.layers.Dense(2, activation=“softmax”)

construct the model

inputs = tf.keras.Input(shape=(2,))
x = clayer_1(inputs)
x_1, x_2 = tf.split(x, 2, axis=1)
x_1 = qlayer_1(x_1)
x_2 = qlayer_2(x_2)
x = tf.concat([x_1, x_2], axis=1)
outputs = clayer_2(x)

model = tf.keras.Model(inputs=inputs, outputs=outputs)

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

model.build(input_shape=X.shape)
model.summary()

when i try to print summary it throws an error ValueError: You tried to call count_params on layer keras_layer_4, but the layer isn’t built. You can build it manually via: keras_layer_4.build(batch_input_shape)… python 3.9.18 and pennylane is 0,30.0

Hi @Amandeep, thank you for asking this question!

My first recommendation would be to upgrade your PennyLane version. You can use python -m pip install pennylane --upgrade

Also, please make sure to format your code here in the forum by using the “<>” button that you see at the top of the panel for writing your questions. Make sure to first click on the <> button and then add your code in between the backticks. This can allows us to try to replicate your problem.

Finally, please post the output of qml.about(), thanks!

Thanks Its working now.

1 Like