ValueError: Weights tensor must have second dimension of length 4; got 2

Hi, thanks in advance for your help.

I’m tryying to use StronglyEntanglerLayers for the scikitlearn moons dataset but I get an error. Please help me.

ValueError: Weights tensor must have second dimension of length 4; got 2

# Put code here

If you want help with diagnosing an error, please put the full error message below:

# Put full error message here

And, finally, make sure to include the versions of your packages. Specifically, show us the output of qml.about().

Hi, @I_love_quantum
thanks for your question!

I will provide some tips that could help. If that works, great! but if it doesn’t, it would be better to provide your code (remember, 100% self-contained — someone can copy-paste exactly what is here and run it to reproduce the behaviour you are observing).

I understand that you are trying to use StronglyEntanglingLayers, and getting an error related to the dimension of the weights tensor. The weights tensor should be of dimension (L, M, 3), where L is the number of layers and M is the number of wires (qubits). You could start by making sure that this is consistent.

A similar question has been asked in the past, it might help to check it out here

I hope this helps. If it doesn’t or you have anymore questions, please let me know. Remember to provide you self-contained code.

Thank you @dangulom !

I have 4 qubits but I don’t knpw how many laayers I need. This is my code. Can you please help me?

import matplotlib.pyplot as plt

import torch

from sklearn.datasets import make_moons

Set random seeds

torch.manual_seed(42)

np.random.seed(42)

X, y = make_moons(n_samples=200, noise=0.1)

y_ = torch.unsqueeze(torch.tensor(y), 1) # used for one-hot encoded labels

y_hot = torch.scatter(torch.zeros((200, 2)), 1, y_, 1)

c = [“#1f77b4” if y_ == 0 else “#ff7f0e” for y_ in y] # colours for each class

plt.axis(“off”)

plt.scatter(X[:, 0], X[:, 1], c=c)

plt.show()

print(X.shape)

X_new = X.reshape((-1,4,3))

print(X_new.shape)

dev = qml.device(‘default.qubit’, wires=4)

@qml.qnode(dev)
def circuit(parameters):
qml.StronglyEntanglingLayers(weights=parameters, wires=range(4))
return qml.expval(qml.Z(0))

weights = X_new

qml.draw_mpl(circuit, level=“device”)(weights);
circuit(weights)

And this is the error I get
ValueError: cannot reshape array of size 400 into shape (4,3)

Ah! I see.
Thanks for providing your code.
Let’s talk about StronglyEntanglingLayers first and implement it in a simple circuit with four qubits and two layers to clarify a few things.

import pennylane as qml
import numpy as np

dev = qml.device('default.qubit', wires=4)

@qml.qnode(dev)
def circuit(parameters):
    qml.StronglyEntanglingLayers(weights=parameters, wires=range(4))
    return qml.expval(qml.Z(0))

shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4)
weights = np.random.random(size=shape)
print(weights)
print(qml.draw(circuit, level="device")(weights))

The output looks like this:

[[[0.49074878 0.7228961  0.82086147]
  [0.71845727 0.53503673 0.47661948]
  [0.83858256 0.20507756 0.96799407]
  [0.71095248 0.19950693 0.73624718]]

 [[0.52984002 0.7072301  0.7677795 ]
  [0.08729018 0.50610396 0.93201434]
  [0.32064219 0.5938831  0.36923048]
  [0.45426797 0.54860312 0.54892198]]]
0: ──Rot(0.49,0.72,0.82)─╭●───────╭X──Rot(0.53,0.71,0.77)─╭●────╭X────┤  <Z>
1: ──Rot(0.72,0.54,0.48)─╰X─╭●────│───Rot(0.09,0.51,0.93)─│──╭●─│──╭X─┤     
2: ──Rot(0.84,0.21,0.97)────╰X─╭●─│───Rot(0.32,0.59,0.37)─╰X─│──╰●─│──┤     
3: ──Rot(0.71,0.20,0.74)───────╰X─╰●──Rot(0.45,0.55,0.55)────╰X────╰●─┤     

You can see that the variable weights has dimension (2, 4, 3). So you need three parameters per qubit (for each rotation) to give a total of 12 parameters per layer.

I believe that you want to use the scikitlearn moons dataset as the input values for the rotations. If that is the case, first you want to make sure that the number of elements of the dataset is a multiple of 12 if you want to use reshape (in your example, 400 doesn’t work since it is not a multiple of 12). I used n_samples=36 in your code and it worked! :partying_face: without even specifying the number of layers, but now we know why this would work and give six layers.

Something else to consider is that the dataset is a 2D binary classification dataset (each sample has two features) and if you do X.reshape, you will end up with layers whose parameters are groups of samples of only two features.

In summary, you can start by deciding the number of layers you require and adjust the dimension (and features) of your dataset accordingly given that the number of qubits is 4.

Let me know if this helped and if there are any other questions.

Oh I get it now !

Thank you so much @dangulom, this was very helpful :pray:

1 Like