New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Variational Quantum Regression using the Parameter Shift Rule #654
Merged
Merged
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
0f3b980
first upload vqregressor code
MatteoRobbiati 4b1bd1d
removed cma from vqregressor
MatteoRobbiati 185d40c
uploaded main.py
MatteoRobbiati f3c643b
uploaded first image
MatteoRobbiati aa512c7
Create README.md
MatteoRobbiati 7decefa
Update README.md
MatteoRobbiati e2c0d6a
renamed images' folder
MatteoRobbiati 16bd536
added results image
MatteoRobbiati 3c566d9
Update README.md
MatteoRobbiati 4f077bb
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 52faa49
fixed output and added comments
MatteoRobbiati eabab15
solving conflicts
MatteoRobbiati d4f029a
fixing output bugs
MatteoRobbiati b00c984
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] e07960c
solving conflicts in vqregressor.py
MatteoRobbiati c831af3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 61efae8
Added code link to README.md
MatteoRobbiati 171cb8b
Update applications.rst adding vqregressor
MatteoRobbiati 3514f99
Added vqregressor to doc
MatteoRobbiati 6bf7d01
fixed typo in symbolic link
MatteoRobbiati 9f637e1
fixed formulas in README.md with images
MatteoRobbiati File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
../../../../../examples/vqregressor/README.md | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
../../../../../examples/vqregressor/images |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# Parameter Shift Rule for an hardware-compatible Variational Quantum Regressor | ||
|
||
Code at: [https://github.com/qiboteam/qibo/tree/vqregressor/examples/vqregressor](https://github.com/qiboteam/qibo/tree/vqregressor/examples/vqregressor) | ||
|
||
### Problem overview | ||
|
||
We want to tackle a simple one dimensional regression problem using a single qubit Variational Quantum Circuit (VQC) as model, | ||
initialized using a [re-uploading strategy](https://arxiv.org/abs/1907.02085). In particular, in this example we | ||
fit the function $y = \sin (2x)$, picking the $x$ points from the interval $\mathcal{I}=[-1,1]$. | ||
The optimization is performed using an [Adam](https://arxiv.org/abs/1412.6980) optimizer. | ||
It needs the circuit's gradients, which we evaluate through the [Parameter Shift Rule](https://arxiv.org/abs/1811.11184) (PSR). | ||
|
||
A method like this is | ||
needed because in quantum computation we can't perform the [Back-Propagation Algorithm](https://www.nature.com/articles/323533a0) on the hardware: | ||
in that case the values of the target function in the middle of the propagation are needed, but for evaluating them on the hardware we have to measure, | ||
and measuring we provoke the collapse of the system and the loss of all the information wealth. The PSR provide us with a numerical tool, with which we | ||
can perform a gradient descent even on the physical qubit. | ||
|
||
### The Parameter Shift Rule in a nutshell | ||
|
||
Let's consider a circuit $\mathcal{U}(\vec{\theta})$, in which we build up a gate of the form $\mathcal{G}=\exp \bigl[-i\mu G \bigr]$ with $\mu \in \vec{\theta}$, | ||
(which represents an unitary operator with at most two eigenvalues $\pm r$), and an observable $B$. | ||
Finally, let $q_f$ be the state we obtain by applying $\mathcal{U}$ to $| 0 \rangle$. | ||
|
||
We are interested in evaluating the gradients of the following expression: | ||
|
||
$$ f(\mu) \equiv \langle q_f | B | q_f \rangle,$$ | ||
|
||
where we specify that $f$ depends directly on $\mu$. We are interested in this result because the expectation value of $B$ is typically involved | ||
in computing predictions in quantum machine learning problems. The PSR allows us to calculate the derivative of $f(\mu)$ with respect to $\mu$ evaluating | ||
$f$ twice more: | ||
|
||
$$ \partial_{\mu} f(\mu) = r \bigl( f(\mu^+) - f(\mu^-) \bigr), $$ | ||
|
||
where $\mu^{\pm}=\mu \pm s$ and $s = \pi/4 r$. Finally, if we pick $G$ from the rotations generators $\frac{1}{2}$ { $\sigma_x, \sigma_y, \sigma_z$ }, | ||
we can use $s=\pi/2$ and $r=1/2$. | ||
|
||
In the end, we have to use PSR into a gradient descent strategy. We choose an [MSE loss function](https://en.wikipedia.org/wiki/Mean_squared_error), which leads to the following explicit formula: | ||
|
||
$$ \partial_{\mu} J_{mse} = 2 \langle B \rangle_{x_j} \partial_{\mu} \langle B \rangle_{x_j} - 2y\langle B \rangle_{x_j}, $$ | ||
|
||
where we indicate with the subscript $x_j$ the dipendence of $J$ on $x_j$ and $y$ is the correct label of $x_j$ under the true law. | ||
|
||
### This example | ||
|
||
As mentioned above, we use a Variational Quantum Circuit based on a re-uploading strategy. In particular, we use the following architecture: | ||
|
||
![ansatz](https://github.com/qiboteam/qibo/blob/vqregressor/examples/vqregressor/images/ansatz.png) | ||
|
||
At the end of the circuit execution we perform a measurement on the qubit. After $N_{shots}$ measurements, we use the difference of the probabilities | ||
of occurrence of the two states $|0 \rangle$ and $| 1 \rangle$ as estimator for $y$. | ||
|
||
### How to use it? | ||
|
||
In this example we use only two files: | ||
|
||
- `vqregressor.py` contains the variational quantum regressor's implementation, with all the methods required for the optimization; | ||
- `main.py` contains a commented example of usage of the regressor. | ||
|
||
The user can change the target function modifying the method `vqregressor.label_points`, in which the true law is written and normalized. Once in the folder, one have to run a command like the following: | ||
|
||
`python3 main.py --layers 1 --learning_rate 0.05 --epochs 200 --batches 1 --ndata 30 --J_treshold 1e-4` | ||
|
||
for performing an optimization. At the end of the process it shows a plot containing true labels of the training sample and the predictions purposed | ||
by the model in a form like the following: | ||
|
||
![results](https://github.com/qiboteam/qibo/blob/vqregressor/examples/vqregressor/images/results.png) |
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# -*- coding: utf-8 -*- | ||
import argparse | ||
|
||
import numpy as np | ||
from vqregressor import VQRegressor | ||
|
||
parser = argparse.ArgumentParser() | ||
parser.add_argument( | ||
"--layers", default=3, help="Number of layers you want to involve", type=int | ||
) | ||
parser.add_argument( | ||
"--learning_rate", | ||
default=0.045, | ||
help="Learning rate for the Adam Descent", | ||
type=float, | ||
) | ||
parser.add_argument("--epochs", default=150, help="Number of training epochs", type=int) | ||
parser.add_argument( | ||
"--batches", | ||
default=1, | ||
help="Number of batches which divide the training sample", | ||
type=int, | ||
) | ||
parser.add_argument( | ||
"--ndata", default=100, help="Number of data in the training set", type=int | ||
) | ||
parser.add_argument( | ||
"--J_treshold", default=1e-4, help="Number of data in the training set", type=float | ||
) | ||
|
||
|
||
def main(layers, learning_rate, epochs, batches, ndata, J_treshold): | ||
|
||
# We initialize the quantum regressor | ||
vqr = VQRegressor(layers=layers, ndata=ndata) | ||
# and the initial parameters | ||
initial_params = np.random.randn(3 * layers) | ||
# Let's go with the training | ||
vqr.train_with_psr( | ||
epochs=epochs, | ||
learning_rate=learning_rate, | ||
batches=batches, | ||
J_treshold=J_treshold, | ||
) | ||
vqr.show_predictions("Predictions of the VQR after training", False) | ||
|
||
|
||
if __name__ == "__main__": | ||
args = vars(parser.parse_args()) | ||
main(**args) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This file has a typo.