Quantum layer in keras cannot be saved

On basis of this tutorial I have integrated a qantum node into a keras model together with two classical layers. Everything worked fine as described in the article. However, when I try to save the model I get the following exception:

ValueError: Cannot infer num from shape (None, 2)

Is it possible to save such a hybrid model? In general, I haven’t fully understood whether the QNode is used during execution/prediction or only for the training of a model. It would be great if you could help me

Hi @c4ristian, welcome to the forum!

As you can see in the diagrams in the tutorial the QNode becomes an integral part of the model.

During the training what you do is that you find the weights (parameters) of the quantum circuit and the weights of the classical layers that give you the lower mean absolute error.

Once you find the optimal weights you still need to use the QNode for making predictions because it will be an integral part of your model.

Please let me know if this is more clear, otherwise I can try to explain it differently!

Regarding the problem with saving the model, could you please share the code that you’re using for saving?

Hi @CatalinaAlbornoz, thank you very much for your reply. That is clear now. I just wasn’t sure if the resulting layer will be classical or quantum after conversion.

For saving the model I tried to use the standard keras method:


Meanwhile, I have read in another thread that this is not supported for QNodes currently. A workaround seems to be saving the weights instead. I guess this works for me :slight_smile:

I’m glad my explanation helped @c4ristian!

And I agree that saving the weights is a good workaround.

Enjoy using PennyLane! :smile:

Thank you very much @CatalinaAlbornoz. I am really excited about PennyLane :slight_smile: In my eyes the framework is a brilliant idea

Thank you @c4ristian! I’m very happy to see that you’re excited about PennyLane. I encourage you to participate in the Carnival which is going on during November and to keep learning and doing quantum computing with PennyLane!