### Just beginning the Quantum programming? you’re at the right place. Shall we hang out with the qubits and get into superposition with them? Only if you don’t have any complications

## I’ll help you to make a quick start in quantum machine learning, so try reading it at least twice if you find it hard to read due to the mathematics used. I have tried to explain everything theoretically rather than much mathematical stuff.

## Introduction

T*he need to locomote from classical to quantum computing is not just casual and hence accelerating the revolution of technology by unleashing the vision towards the quantum era. Blending Artificial Intelligence and Quantum computing can yield wonders. And that’s what in the coming generations is going to pop out. So it’s our allegiance to be ready and get a bit closer to the future of computers.*

The Introduction seems much futuristic. Just ignore it and get to work.. firstly we’ll take a quick tour of the topic we going to catch sight of.

We are about to implement a basic quantum mechanism to rotate a qubit, In the python programming language using a cool library known as pennylane. It’s a cross-platform Python library for differentiable programming of quantum computers. Just assume differential programming as the machine learning for now.

## Suggestion

Make a quick pip install

NOTE: The library supports python version 3.6 or newer. OR if you are viewing this article later from the date or in the week it was published.

`pip install pennylane --upgrade`

You can even build it from the source.

## Quick overview of qubit

Qubit is nothing but the basic building block of the Quantum computers similar to the binary bits in the computers we use every day. Let’s go deeper and visualize the qubit states in a clean way using the Bloch-sphere.

Here is the sphere

The Bloch sphere is the geometric representation of qubits states. Single qubit operations can be easily visualized using the Bloch sphere. The pure state ψ can be written as a complex superposition of the vectors ∣0⟩ and ∣1⟩

## ∣ψ⟩ = α∣0⟩ + β∣1⟩

Each qubit state can be represented as the linear combination ∣0⟩ and ∣1⟩. The above equation represents a qubit state only if the sum of the square of|α|and square of |β|is 1 with radius (r) =1. The probability of qubit in state ∣0⟩ is ∣*α*∣2 and the probability that it will be measured in the state ∣1⟩ is ∣*β*∣2. Hence the sum of the observed probability is 1.

Where α and β are the complex numbers, they are nothing but the probability amplitudes

The alternate symbol used for state 1 is ∣-⟩ and for state 2 ∣+⟩. Both states form an orthonormal basis, that are located to the opposite side of the block sphere. In the figure of the Bloch sphere, θ, φ are real numbers. where the numbers 0 ≤ θ ≤ π and 0 ≤ φ ≤ 2π define a point on a unit three-dimensional sphere. That is the state of the qubit.

The Phase difference between ∣0⟩ and ∣1⟩ is referred to as a relative phase.

The arbitrary single state of a qubit can be written as

In the above equation θ, φ and γ are real numbers. But the arbitrary values of γ and the factorial of e to the power iγ show no observable effect and also the defined point of the state of the qubit lies on the same location. Therefore the equation of the qubit state in the Hilbert space is written as

## Rotation Operation

The states of the qubit can be transformed by rotating it around axis x, y, and z.

The operation used to rotate a single qubit around X-axis. The Rx gate implements a rotation of π i.e 180 degrees around the X-axis of the block sphere. The X gate is also called the NOT gate. Which gives state ∣0⟩ for ∣1⟩ and ∣1⟩ for ∣0⟩ when passed through the gate.

Similarly, the Ry operation is used to rotate a single qubit around Y-axis

And the Z-gate operation used to rotate a single qubit around Z-axis to π of the block sphere.

The H gate is implemented to move the qubit away from the poles of the block sphere and create a superposition of two states

The Controlled-NOT gate is a two-qubit operation, where the first is referred to as a control qubit and the second one is the target qubit. The CNOT gate flips the target qubit if the control qubit is ∣1⟩

Measurements: This is the step at the end of a quantum circuit that observes or kind of measures the outputs of the circuit, which are the probabilities in a form of state i.e the probabilistic states

Bra-kets:(Invented by Paul Dirac) The Bracket notation is nothing but a symbolic way of enclosing bits and bits strings in asymmetrical brackets called kets where we write |0⟩ and |1⟩ instead of 0 and 1.

## Implementation

Well, after a long theoretical phase, let us play with some code.

I hope you have Pennylane installed. It allows us to perform the backpropagation with the same optimizer we used in classical machine learning.

We’ll try to implement a circuit for the qubit rotation, while the qubit in the ground state |0⟩. Firstly import the Pennylane library with the NumPy library which comes with Pennylane integration for better performance.

#import libsimportpennylaneasqmlfrompennylaneimportnumpyasnp

next, we’ll initialize the quantum device. You can initialize it with either a hardware device using API of IBM quantum experience or alternatives.

**device = qml.device("default.qubit", wires=2)**

Where ** wires** are the number of Subsystems to be used, as we are using 2 qubit operation well use 2 wires. And the

**is the default simulator device we gonna use.**

*default.qubit*we’ll need a function to apply quantum operations over qubits which involves certain Quantum gates.

**def** circuit(params):

qml.RX(params[0], wires=0)

qml.RY(params[1], wires=1)

**return** qml.expval(qml.PauliZ(0))

The first instruction is the RX gate we saw above in the theoretical part, it rotates the qubit to 180 degrees over the X-axis the second instruction is the RY gate will rotate the qubit around the y-axis. The* expval *will perform the final measurement over the value output by the Pauli Z gate which rotates the qubit around Z-axis to π , It is also among the observables we need to add the decorator before the function to make it a Q node and to run it on a device we initialized previously.

**@qml.qnode(device)**

def circuit(params):

qml.RX(params[0], wires=0)

qml.RY(params[1], wires=1)

**return** qml.expval(qml.PauliZ(0))

Creating the cost function in the same way we create in classical machine learning.

**def** cost(x, y):

**return** np.sin(np.abs(circuit(x, y))) - 1

we’ll create a cost function to measure the performance of our circuit function which we also usually do in classical machine learning. And we’ll further try to optimize it.

**opt** = qml.grad(cost, argnum=[0, 1])

Here we finally optimized our rotations using the gradient descent optimizer with a cost function by passing bool values as the parameters to the cost function. It will return an object type output.

So this was just a starter for Quantum machine learning. Now we’ll try to perform quantum machine learning using the package we commonly use Like PyTorch. So let’s dig in.

## PyTorch Implementation

Make Pytorch installation and import libraries

Make sur that you've installed PyTorch

For PyTorch latest release -Hereimportpennylaneasqml

from pennylane importnumpyasnpimporttorchfromtorch.autogradimportVariable

Firstly, Initialize the quantum device with a simulator for 2 qubits. we can also use the quantum hardware which can be manually initialized just by changing this line above.

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

As usual, we will create a quantum function that will include the instructions to rotate the qubit. And we’ll also transform it into a qnode by initializing it with the quantum device.

`@qml.qnode(dev, interface='torch')`

def circuit(phi1, phi2):

qml.RX(phi1, wires=0)

qml.RY(phi2, wires=1)

return qml.expval(qml.PauliZ(0))

This look’s almost similar to the one we created before. The quantum node can output probabilities, variance, exceptional values that are differentiable. The qnode is the interface between quantum computers and machine learning libraries

`def cost(phi1, phi2):`

expval = circuit(phi1, phi2)

return torch.abs(expval - (-1))**2

The cost function is the same used in classical processing.

`phi = torch.tensor([0.011, 0.012], requires_grad=`**True**)

theta = torch.tensor(0.05, requires_grad=**True**)

these are 2 input parameters in a PyTorch tensor format that have to be feed to the circuit

`opt = torch.optim.Adam([phi, theta], lr = 0.1)`

We’ll finally use the Adam optimizer we usually use in our machine learning with a learning rate, we can use other optimizers too. The optimizers automatically update the parameters of the machine learning model.

steps = 200defclosure():

opt.zero_grad()

loss = cost(phi, theta)

loss.backward()

returnlossforiinrange(steps):

opt.step(closure)

And here starts the training, with 200 steps

*What are variational circuits?*

The circuits that require parameters to get an output are called variational circuits or parameterized quantum circuits.

The algorithm involves certain steps:

- Composing the initial state or ground state i.e the 0 state. The qubit state preparations are done using classes like BasisState or QubitStateVector which we haven’t used over here. we have just tried to see the core Idea of Quantum machine learning.
- A quantum circuit in which the parameters have to be passed.
- And the last step involves the measurements of the observables from each wire in the circuit.

Similar, to PyTorch we can also use the TensorFlow library as an interface in quantum machine learning.

Hybrid computations are the combination of classical and quantum computations for instance the *variational quantum eigensolvers*

So, finally, you’re ready to dive into quantum machine learning. I hope you may have got everything crystal clear, I still made it much simpler to understand and if you didn’t you can post a comment and get in touch with me. I will be going much deeper in the future articles so stay close. Please don’t forget to hit claps and follow me over medium. Thank you.

## Things to try

you can also try solving a classification problem in quantum machine learning not necessarily using the same library, but anyone of your choice.

## References

Please go through the references as well, they made me learn more.

## Leave a Reply