Inconsistency error between input data and qnn network

I am new to training a Quantum Neural Network (QNN) and I am facing an issue that I need help with. The error message indicates that the input shape is expected to be 8, but I am passing data with dimensions of (3000,8). Can someone provide guidance on how to resolve this problem? Thank you in advance for any assistance.

My code is an
s fallows:

import pennylane as qml
from pennylane import numpy as np
import autograd.numpy as anp
from pennylane.optimize import NesterovMomentumOptimizer
import tensorflow as tf

from itertools import combinations
state_0 = [[1], [0]]
M = state_0 * np.conj(state_0).T

dev = qml.device("default.qubit")
def circuit(inputs, theta):
    #Featuremap1
    for i in range(4):
        qml.Hadamard(i)
        qml.RZ(2.0 * inputs[i], wires = i)
    for pair in list(combinations(range(4), 2)):
        q0 = pair[0]
        q1 = pair[1]
        qml.CZ(wires = [q0, q1])
        qml.RZ(2.0 * (np.pi - inputs[q0]) *
                (np.pi - inputs[q1]), wires = q1)
        qml.CZ(wires = [q0, q1])
        
        
    #tow local variational circuit 1
    #layer 1
    for i in range(4):
        qml.RY(theta[i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    #layer 2
    for i in range(4):
        qml.RY(theta[4+i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    #layer3
    for i in range(4):
        qml.RY(theta[8+i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    #layer 4
    for i in range(4):
        qml.RY(theta[12+i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    for i in range(4):
        qml.RY(theta[16+i], wires = i)
    
    #Featuremap2
    for i in range(4):
        qml.Hadamard(i)
        qml.RZ(2.0 * inputs[i+4], wires = i)
    for pair in list(combinations(range(4), 2)):
        q0 = pair[0]
        q1 = pair[1]
        qml.CZ(wires = [q0, q1])
        qml.RZ(2.0 * (np.pi - inputs[q0+4]) *
                (np.pi - inputs[q1+4]), wires = q1)
        qml.CZ(wires = [q0, q1])
    
    
    #tow local variational circuit 2
    #layer 1
    for i in range(4):
        qml.RY(theta[i+20], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    #layer 2
    for i in range(4):
        qml.RY(theta[24+i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    #layer3
    for i in range(4):
        qml.RY(theta[28+i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    #layer 4
    for i in range(4):
        qml.RY(theta[32+i], wires = i)
    for i in range(3):
        qml.CNOT(wires = [i, i + 1])
    for i in range(4):
        qml.RY(theta[36+i], wires = i)
    return qml.expval(qml.Hermitian(M, wires = [0]))

index=[0,7,14,21,28,25,42,45]
X=np.load('x_data_minmax_7-Copy1.20e+05_train.npy')[:3000]
X_test=np.load('x_data_minmax_7-Copy1.20e+05_test.npy')[720:720*6]
X_valid=np.load('x_data_minmax_7-Copy1.20e+05_valid.npy')
y_test=np.load('y_data_minmax_7-Copy1.20e+05_test.npy')[720:720*6]
y_tr=np.load('y_data_minmax_7-Copy1.20e+05_train.npy')[:3000]
y_val=np.load('y_data_minmax_7-Copy1.20e+05_valid.npy')
xs_tr=X[:,index]
xs_val=X_valid[:,index]
xs_test=X_test[:,index]

qnn = qml.QNode(circuit, dev, interface="tf")
weights = {"theta":40 }
qlayer = qml.qnn.KerasLayer(qnn,weights, output_dim=1)
model = tf.keras.models.Sequential([qlayer])
opt = tf.keras.optimizers.Adam(learning_rate = 0.005)
model.compile(opt, loss=tf.keras.losses.BinaryCrossentropy())

earlystop = tf.keras.callbacks.EarlyStopping(
    monitor = "val_loss", patience = 2, verbose = 1,
    restore_best_weights = True)

history = model.fit(xs_tr, y_tr) epochs = 70, shuffle = True,
    validation_data = (xs_test, y_test),
    batch_size = 120,
    callbacks = [earlystop])

and I get this error:

InvalidArgumentError                      Traceback (most recent call last)
/tmp/ipykernel_854/2875074947.py in <module>
----> 1 history = model.fit(xs_tr, y_tr, epochs = 70, shuffle = True,
      2     validation_data = (xs_test, y_test),
      3     batch_size = 120,
      4     callbacks = [earlystop])

/cvmfs/sft.cern.ch/lcg/views/LCG_105a_swan/x86_64-centos7-gcc11-opt/lib/python3.9/site-packages/keras/src/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

~/.local/lib/python3.9/site-packages/pennylane/qnn/keras.py in call(self, inputs)
    387             # pylint:disable=unexpected-keyword-arg,no-value-for-parameter
    388             new_shape = tf.concat([batch_dims, tf.shape(results)[1:]], axis=0)
--> 389             results = tf.reshape(results, new_shape)
    390 
    391         return results

InvalidArgumentError: Exception encountered when calling layer 'keras_layer' (type KerasLayer).

{{function_node __wrapped__Reshape_device_/job:localhost/replica:0/task:0/device:CPU:0}} Input to reshape is a tensor with 8 values, but the requested shape has 120 [Op:Reshape] name: 

Call arguments received by layer 'keras_layer' (type KerasLayer):
  • inputs=tf.Tensor(shape=(120, 8), dtype=float32)

qml.about():

Name: PennyLane
Version: 0.35.1
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page: GitHub - PennyLaneAI/pennylane: PennyLane is a cross-platform Python library for differentiable programming of quantum computers. Train a quantum computer the same way as a neural network.
Author:
Author-email:
License: Apache License 2.0
Location: /eos/home-i04/p/pkangazi/.local/lib/python3.9/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml, typing-extensions
Required-by: PennyLane_Lightning, PennyLane_Lightning_GPU

Platform info: Linux-6.6.13-200.fc39.x86_64-x86_64-with-glibc2.17
Python version: 3.9.12
Numpy version: 1.23.5
Scipy version: 1.11.3
Installed devices:

  • default.clifford (PennyLane-0.35.1)
  • default.gaussian (PennyLane-0.35.1)
  • default.mixed (PennyLane-0.35.1)
  • default.qubit (PennyLane-0.35.1)
  • default.qubit.autograd (PennyLane-0.35.1)
  • default.qubit.jax (PennyLane-0.35.1)
  • default.qubit.legacy (PennyLane-0.35.1)
  • default.qubit.tf (PennyLane-0.35.1)
  • default.qubit.torch (PennyLane-0.35.1)
  • default.qutrit (PennyLane-0.35.1)
  • null.qubit (PennyLane-0.35.1)
  • lightning.qubit (PennyLane-Lightning-0.35.1)
  • lightning.gpu (PennyLane-Lightning-GPU-0.35.1)

Hi @p.kangazi , welcome to the Forum!

Could you please share a minimal but self-contained version of your code?
Here I don’t have access to your data so I can’t try to replicate your code.
A good practice would be to create some fake data with a smaller size, for example random data with dimensions (10,8).
Also, you have a lot going on in your code. Do you still see the same issue if you remove all of the layers but one?
If removing those layers and featuremaps doesn’t solve the issue then it’s best to not share them here since they’re not the cause for the error.

We have this video with tips on how to make great forum posts. I think you’ll find it useful to understand what I mean with my previous comments.

Sometimes the process of removing extra stuff is helpful for finding the source of the error yourself! If you’re still facing the error and can’t figure out why, just share here your minimal non-working example and we’ll do our best to help you.