How To Build A Quantum Artificial Intelligence Model With Python Code Examples
How To Build A Quantum Artificial Intelligence Model With Python Code Examples
Tiago Monteiro
Machine learning (ML) is one of the most important subareas of AI used in
building great AI systems.
However, there is a big problem with deep learning: computational efficiency. Creating big
and effective AI systems with neural networks often requires a lot of energy, which is
expensive.
So, the more efficient the hardware is, the better. There are many solutions to solve this
problem, one of which is quantum computing.
1/21
This article hopes to show, in plain English, the connection between quantum computing and
artificial intelligence.
The bigger the neural network, the more capable it is of doing awesome things – like
ChatGPT, for example, which uses natural language processing to answer questions and
interact with users.
To truly understand the basics of neural networks – what every single AI model has in
common that enables it to work – we need to understand activation layers.
2/21
At the core of deep learning is the training of neural networks. That means using data to get
the right values for each neuron to be able to predict what we want.
Neural networks are made of neurons organized in layers. Each layer extracts unique
features from the data.
This layered structure allows deep learning models to analyze and interpret complex data.
Deep learning powers a lot of the transformation AI makes in the society. However, it comes
with a big problem: computational efficiency.
Training deep learning AI systems requires massive amounts of data and computational
power. This can take minutes to weeks and in the process, it consumes a lot of energy and
computational resources.
There are many solutions to this problem, such as better algorithmic efficiency.
In large language models, this has been the focus of much AI research. To make smaller
models have the same performance as larger ones.
3/21
Another solution, besides algorithmic efficiency, is better computational efficiency. Quantum
computing is one of the solutions related to better computational efficiency.
While normal computers work in bits (either 0 or 1), quantum computers work with qubits –
can be 0 and 1 at the same time.
With the qubits representing 0 and 1 at the same time, it is possible to process many
possibilities simultaneously, thanks to a property called superposition in quantum physics.
This makes the quantum computers, for certain tasks, far more efficient than normal
computers.
This way, it is also possible to have quantum-based algorithms that are more efficient than
normal algorithms. This way, reducing the energy consumption used when creating AI
models.
The problem with quantum computation is that there isn't a good, cheap physical
representation of qubits.
Bits are created and managed with logic gates made from tiny transistors, which can be
easily created by the billions.
Qubits are created and managed by superconducting circuits, trapped ions, and topological
qubits, which are all very expensive.
This is the biggest problem in quantum computation. However, IBM, Amazon, and many
others in cloud services allow people to run code on their quantum computers.
4/21
Photo by Pixabay: https://www.pexels.com/photo/two-clear-glass-jars-beside-several-flasks-248152/
What is the lowest energy level of the H₂ molecule using quantum computing?
Quantum chemistry is a field of science that looks at how electrons behave in atoms and
molecules.
It is about using quantum physics to understand how electrons, atoms, molecules and many
more tiny particles interact and form different chemical substances.
Water
Organic compounds
Stars
5/21
Actually, life on Earth would not be possible without it.
By finding the "ground state energy," which is the lowest possible energy that the molecule
can have, we can know its most stable form and properties.
With classical computers, this problem can be very complex due to a huge number of
possibilities and intricate interactions.
With quantum computers, qubits are good representations of electrons, which can directly
simulate the behavior of electrons in molecules.
The Variational Quantum Eigensolver (VQE) is a hybrid algorithm that leverages both
quantum and classical computing.
In this example, the VQE algorithm is used to find the ground state energy of a simple H₂
molecule.
The code is designed to run on a quantum simulator (which is a classical computer running a
quantum algorithm).
This would involve using both quantum and classical resources in practice. Let’s go through
the code step by step!
6/21
import pennylane as qml
import numpy as np
import matplotlib.pyplot as plt
# Choose an optimizer
optimizer = qml.GradientDescentOptimizer(stepsize=0.4)
# Optimization loop
energies = []
for n in range(max_iterations):
params, prev_energy = optimizer.step_and_cost(cost_fn, params)
energy = cost_fn(params)
energies.append(energy)
if np.abs(energy - prev_energy) < conv_tol:
7/21
break
iterations = range(len(energies))
plt.plot(iterations, energies)
plt.xlabel('Iteration')
plt.ylabel('Energy (Ha)')
plt.title('Convergence of VQE for H2 Molecule')
plt.show()
8/21
9/21
Full Code Image
Importing Libraries
10/21
Importing libraries
pennylane: A library for quantum computing that provides tools for creating and
optimizing quantum circuits, and for running machine learning quantum based
algorithms.
numpy: A library for numerical operations in Python, used here for handling arrays and
mathematical computations.
matplotlib: A library for creating visualizations and plots in Python, used here to graph
the convergence of the VQE algorithm.
11/21
Defining the Molecule and generating the Hamiltonian
12/21
# Define the quantum device
dev = qml.device("default.qubit", wires=qubits)
def ansatz(params, wires): This defines a function named ansatz which describes
the variational quantum circuit. This circuit will be used to find the ground state energy
of the molecule.
13/21
qml.BasisState(np.array([0] * qubits), wires=wires): This initializes the qubits
in the state 0. The np.array([0] * qubits) creates an array with zeros, one for each
qubit.
for i in range(qubits): qml.RY(params[i], wires=wires[i]): This loop applies
a rotation around the Y-axis to each qubit. params[i] provides the angle for each
rotation.
for i in range(qubits - 1): qml.CNOT(wires=[wires[i], wires[i + 1]]): This
loop applies Controlled-NOT (CNOT) gates between consecutive qubits, entangling
them.
# Choose an optimizer
optimizer = qml.GradientDescentOptimizer(stepsize=0.4)
14/21
Defining the Cost Function, Setting Initial Parameters and Optimizer
@qml.qnode(dev): This line is a decorator that transforms the cost_fn function into a
quantum node, allowing it to run on the quantum device dev.
def cost_fn(params): This defines a function named cost_fn that takes some
parameters (params) as input.
ansatz(params, wires=range(qubits)): Inside this function, we call the previously
defined ansatz function, passing in the parameters and specifying that it should use all
the qubits.
return qml.expval(hamiltonian): This line returns the expected value of the
Hamiltonian, which represents the energy of the molecule. The cost function is what we
aim to minimize to find the ground state energy.
15/21
np.random.seed(42): This line sets a fixed seed for the random number generator.
This ensures that the random numbers generated will be the same each time the code
is run, making the results reproducible.
Choosing an Optimizer:
Optimization Loop
# Optimization loop
energies = []
for n in range(max_iterations):
params, prev_energy = optimizer.step_and_cost(cost_fn, params)
energy = cost_fn(params)
energies.append(energy)
if np.abs(energy - prev_energy) < conv_tol:
break
16/21
Optimization Loop
max_iterations = 100: This sets the maximum number of steps the optimization will
take. In this case, it is 100 steps.
conv_tol = 1e-06: This defines the convergence tolerance. If the change in energy
between steps is less than this value, the optimization will stop.
Optimization Loop:
energies = []: This initializes an empty list to store the energies calculated at each
step.
17/21
energy = cost_fn(params): This calculates the current energy using the updated
parameters.
energies.append(energy): This adds the current energy to the energies list.
if np.abs(energy - prev_energy) < conv_tol: break: This checks if the absolute
difference between the current energy and the previous energy is less than the
convergence tolerance. If it is, the loop stops early because the optimization has
converged.
print(f"Step = {n}, Energy = {energy:.8f} Ha"): This prints the current step
number and the energy in Hartree (Ha) to eight decimal places.
print(f"Final ground state energy = {energy:.8f} Ha"): After the loop, this
prints the final ground state energy.
plt.plot(iterations, energies)
plt.xlabel('Iteration')
plt.ylabel('Energy (Ha)')
plt.title('Convergence of VQE for H2 Molecule')
plt.show()
18/21
Setting Up the Data for Visualization:
plt.plot(iterations, energies): This line creates a plot with the iteration numbers
on the x-axis and the corresponding energy values on the y-axis.
plt.xlabel('Iteration'): This sets the label for the x-axis to "Iteration".
plt.ylabel('Energy (Ha)'): This sets the label for the y-axis to "Energy (Ha)", where
"Ha" stands for Hartree, a unit of energy.
plt.title('Convergence of VQE for H2 Molecule'): This sets the title of the plot to
"Convergence of VQE for H2 Molecule".
plt.show(): This displays the plot.
The graph titled "Convergence of VQE for H2 Molecule" shows the energy (in Hartree, Ha) of
the H2 molecule plotted against the number of iterations of the Variational Quantum
Eigensolver (VQE) algorithm.
19/21
X-Axis (Iteration): Number of VQE iterations.
Y-Axis (Energy (Ha)): Energy of the H2 molecule in Hartree.
Key Points:
Besides making AI algorithms far more computationally efficient, quantum computing can
revolutionize many fields like:
Drug discovery
Material science
Cryptography
Financial modeling
Optimization problems
20/21
Climate modeling
Machine learning
However, for all of us to use quantum computing, a way to physically represent qubits small
enough to fit on our laptops is needed. That will take years.
tiagomonteiro0715GitHub
Tiago Monteiro
3º year electrical and computer engineering student at Nova School of Science
and Technology in Portugal | Vice Chair of IEEE NOVA SB | IEEE NOVA SB
represents IEEE | https://www.ieee.org/
Learn to code for free. freeCodeCamp's open source curriculum has helped more than
40,000 people get jobs as developers. Get started
21/21