# Weights in qunatum layers

**URL:** <https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876>\
**Category:** PennyLane Help\
**Created:** [May 3, 2022, 3:13pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876 "2022-05-03T15:13:57Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Muhammad\_Kashif](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/muhammad_kashif/32/558_2.png) [@Muhammad\_Kashif](https://discuss.pennylane.ai/u/Muhammad_Kashif)\
**Post date:** [May 3, 2022, 3:13pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876/1 "2022-05-03T15:13:57Z")

</div>

Hi there,

How can I set the weights of customized quantum layer (to be converted to keras layer later on), instead of using built-in templates.

```
n_qubits = 6
dev = qml.device("default.qubit", wires=n_qubits)

@qml.qnode(dev, interface = "tf", diff_method="adjoint")
def qnode(inputs, w1):
    qml.templates.AmplitudeEmbedding(inputs, wires=range(n_qubits), pad_with=2, normalize = True)
    for i in range(n_qubits):
        qml.RX(w1[i], i)
    return [qml.expval(qml.PauliZ(wires=[i])) for i in range(n_qubits)]

n_layers = 2
weight_shapes = {"w1":(1,n_qubits)}

```

when I convert the above qnode into Keras Layer following [this](https://pennylane.ai/qml/demos/tutorial_qnn_module_tf.html) template and later train the model, I get the following error:

```
InvalidArgumentError: Exception encountered when calling layer "keras_layer_4" (type KerasLayer).

slice index 1 of dimension 0 out of bounds. [Op:StridedSlice] name: model_4/keras_layer_4/strided_slice/

```

Any pointers to why is this the case would be appreciated…  
Thanks

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [May 4, 2022, 9:16pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876/2 "2022-05-04T21:16:29Z")

</div>

Hi @Muhammad_Kashif, unfortunately I’m not being able to reproduce your error. Could you please post a minimal non-working example of your code? Basically your full code but stripped off any elements that don’t contribute to you getting this error. Please include your data too so that I can run it and try to see what the problem may be.

---

<div class="post-metadata">

**Author:** ![Muhammad\_Kashif](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/muhammad_kashif/32/558_2.png) [@Muhammad\_Kashif](https://discuss.pennylane.ai/u/Muhammad_Kashif)\
**Post date:** [May 4, 2022, 11:30pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876/3 "2022-05-04T23:30:32Z")

</div>

Hi @CatalinaAlbornoz,

Thanks for looking into my query. Below is my code example:

# imports

```
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import datasets

```

# dataset loading

`x_train, x_test = datasets.load_digits().data, datasets.load_digits().target`

# splitting train and test data

```
x_train, x_test, y_train, y_test = train_test_split(
    x_train, x_test, test_size=0.25, random_state=42)

```

# creating qnode

```
n_qubits = 6
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def qnode(inputs, w1):
    qml.templates.AmplitudeEmbedding(inputs, wires=range(n_qubits), pad_with=2, normalize = True)

    for i in range(n_qubits):
        qml.RY(w1[i], wires = i)
    return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]

```

# defining weight shapes for quantum gates

`weight_shapes = {"w1": (1,6)}`

# qnode to keras layer

`qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)`

# creating a hybrid NN

```
clayer = tf.keras.layers.Dense(10, activation="softmax")
model = tf.keras.models.Sequential([qlayer, clayer])

```

# compiling the NN model

```
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="sparse_categorical_crossentropy", metrics=["accuracy"])

```

# start training the model

`fitting = model.fit(x_train, y_train, epochs=1, batch_size=16, validation_data=(x_test, y_test))`

The above results in the following error:  
`InvalidArgumentError: slice index 1 of dimension 0 out of bounds. [Op:StridedSlice] name: sequential_20/keras_layer_21/strided_slice/`

Now the issue I am facing here is regarding the `weight_shapes`. since I am using single parametrized gate `RY` means it should have a single dimension weight (as per my understanding) and hence the first argument in weight\_shapes dictionary is `1` and since I am using 6 qubits the second argument is `6`. which means `6` weights of dimension 1 (correct me if I am wrong)? but it gives the error mentioned above.

If I set the `weight_shapes = {"w1": (1)}` and not use `w1[i]` in the qnode where I pass the weights to `RY` the code works fine but in that case, I think we are only training the `6 RY` gates with same weights which is, in a way, same like training a single weight or single RY gate, whereas all 6 RY gates should have different weights, right?  
I hope I made my question clear. Any help would be appreciated.  
Thanks

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [May 5, 2022, 2:45pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876/4 "2022-05-05T14:45:18Z")

</div>

Hi @Muhammad_Kashif,

I was able to reproduce your error now. Your error is effectively in the weight shapes. You want it to be a vector of size 6. This means that the weights shape should be: `weight_shapes = {"w1": (6)}`

This has solved the problem on my end. Please let me know if it works for you too!

---

<div class="post-metadata">

**Author:** ![Muhammad\_Kashif](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/muhammad_kashif/32/558_2.png) [@Muhammad\_Kashif](https://discuss.pennylane.ai/u/Muhammad_Kashif)\
**Post date:** [May 5, 2022, 7:32pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876/5 "2022-05-05T19:32:20Z")

</div>

Hi @CatalinaAlbornoz,

It works.  
Thanks for the help…!!

I asked a query [here](http://discuss.pennylane.ai/t/local-cost-function-hybrid-neural-networks/1756/7) few days back. Any update on this so far?

Thanks

---

<div class="post-metadata">

**Author:** ![CatalinaAlbornoz](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/catalinaalbornoz/32/1196_2.png) [@CatalinaAlbornoz](https://discuss.pennylane.ai/u/CatalinaAlbornoz)\
**Post date:** [May 9, 2022, 6:22pm UTC](https://discuss.pennylane.ai/t/weights-in-qunatum-layers/1876/6 "2022-05-09T18:22:10Z")

</div>

Hi @Muhammad_Kashif,

I’m glad this solved your issue!

Regarding the other query I will give you an answer there.
