Quantum Machine Learning: An Overview

0
54
QML

There are quite a few open source libraries and frameworks available for quantum machine learning, and most of them are compatible with Python programming.

Quantum computing is based on the concept of superposition, in which 0 and 1 can both occur at the same time — something not possible in classical computers. Its high-performance supercomputing capabilities can solve problems in multiple domains including healthcare, finance, cyber security and education.

Realising the importance of quantum computing, the National Quantum Mission (NQM) of India is focusing on quantum communications, quantum sensing, quantum metrology, quantum materials, and quantum devices. It has set up four Thematic Hubs (T-Hubs) at leading institutions in the country for this purpose.

Table 1: Implementation of quantum computing in different domains

Domain Implementation areas
Defence and strategic operations Cryptanalysis operations, Simulation, Battle modelling, Communication security, Resource allocation, Strategy testing, Threat analysis and modelling, Radar enhancement, Secure communications, Simulation training
Materials science and chemistry Material design, Nanostructures study, Crystal analysis, Magnetic properties, Molecule simulation, Drug design, Protein folding, Reaction prediction, Catalyst discovery, Thermal conductivity
Artificial intelligence, Machine learning, Deep learning Quantum classifiers, Pattern recognition, Feature extraction, Data clustering, Neural networks, Object recognition, Natural language processing (NLP)
Energy, oil and gas Battery optimisation, Grid management, Solar simulation, Oil exploration, Fuel efficiency, Reservoir simulation, Risk assessment, Pipeline monitoring, Drilling optimisation, Refinery control
Space exploration and aerospace Flight simulation, Materials testing, Satellite routing, Trajectory optimisation, Sensor fusion, Orbit simulation, Resource analysis, Rover navigation, Planet mapping, Asteroid tracking
Sensors and climatic analysis Quantum imaging, Weather modelling, Energy forecasting, Ocean simulation, Emission tracking, Disaster prediction, Temperature measurement, Chemical detection, Magnetic sensing, Pressure monitoring
Healthcare and pharmaceuticals Drug discovery, Disease simulation, Protein modelling, Genome analysis, Diagnostic tools, Molecular docking, Disease modelling, Drug testing, Trial simulation, Compound screening
Manufacturing Process optimisation, Quality assurance, Robotics control, Defect detection, Materials testing
Automotive Traffic optimisation, Crash simulation, System testing, Path planning, Sensor fusion, Emission analysis, Sensor analysis, EV battery, Autonomous navigation, Vehicle design
Telecommunications Signal processing, Quantum repeaters, Error correction, Network routing, Spectrum allocation
Agriculture and food Crop prediction, Yield optimisation, Pest management, Soil analysis, Irrigation planning, Recipe optimisation, Nutrition analysis, Quality control, Supply prediction, Preservation modelling
Quantum internet Entanglement distribution, Network scaling, Node routing, Secure channels, Error correction
Education Quantum teaching, Student assessment, Algorithm training, Lab simulations, Curriculum design
Smart cities and environment Traffic modelling, Pollution monitoring, Climate modelling, Water quality, Habitat simulation, Resource management, Sensor networks, Waste management, Energy optimisation, Public safety
Entertainment
and gaming
Level optimisation, Multiplayer synchronisation, Physics simulation, AI opponents, Movie rendering, Content generation, Virtual reality (VR) simulation, Game physics, Sound optimisation, Procedural generation
Key applications of quantum computing
Figure 1: Key applications of quantum computing

Quantum machine learning: Application areas

Quantum machine learning (QML) replaces classical machine learning applications with quantum implementations, helping optimise mammoth computations in fields like fintech (integration of finance and technology), blockchain, cryptography, logistics, and supply chain management. Here are some examples of how QML helps in different domains.

Fintech and blockchain

Transaction validation, banking token generation, smart contracts, consensus optimisation, security auditing

Finance

Portfolio optimisation, fraud detection, asset allocation, risk analysis, option pricing

Supply chain management

Demand forecasting, inventory optimisation, supplier evaluation, shipment tracking, route planning

Cryptography

Secured key generation, encryption analysis, quantum hashing, code breaking, secure protocols

Insurance

Customer analysis, risk evaluation, claim prediction, fraud detection, policy pricing

Logistics

Route optimisation, traffic modelling, inventory management, fleet scheduling, supply prediction

Retail

Demand forecasting, customer segmentation, inventory planning, pricing analysis, recommendation systems

A number of free and open source libraries and frameworks are available for implementing the algorithms and circuits of quantum machine learning. Most of these are compatible with Python programming. Table 2 lists some of these.

Table 2: Free and open source libraries for QML

Library Programming
language
URL
PennyLane Python pennylane.ai
Qiskit Machine Learning Python qiskit.org/ecosystem/machine-learning
TensorFlow Quantum Python tensorflow.org/quantum
TorchQuantum Python github.com/mit-han-lab/torchquantum
Cirq Python quantumai.google/cirq
MindQuantum Python github.com/mindspore-ai/mindquantum
Yao.jl Julia github.com/QuantumBFS/Yao.jl
QuTiP Python qutip.org
lambeq Python github.com/CQCL/lambeq
QuCumber Python github.com/PIQuIL/QuCumber
NetKet Python netket.org
OpenFermion Python github.com/quantumlib/OpenFermion
QGOpt Python github.com/LuchnikovI/QGOpt
Tequila Python github.com/tequilahub/tequila
Qibo Python qibo.science
D-Wave Ocean (dimod, dwave-networkx) Python docs.ocean.dwavesys.com
Strawberry Fields Python strawberryfields.ai
ProjectQ Python projectq.ch
PennyLane for quantum programming
Figure 2: PennyLane for quantum programming

Variational quantum classification using PennyLane on a fintech application

The following example uses a sample dataset of cryptocurrencies. Using QML, the aim is to predict if the closing value of the cryptocurrency the next day will be higher than its price today. The quantum circuit of 1 qubit is taken with a small variational block.

To install PennyLane, type:

$ pip install pennylane

The quantum machine learning-based binary classification is as follows:

import pandas as pd

from pennylane import numpy as np

import pennylane as qmllib

from sklearn.preprocessing import StandardScaler

from sklearn.model_selection import train_test_split

# 1. Upload dataset

from google.colab import files

files.upload()

# Example: cryptoprices.csv should have columns: Date, Close

cryptodataframe = pd.read_csv(“cryptoprices.csv”)

# Create a simple “up or down” label

cryptodataframe[“Target”] = (cryptodataframe[“Close”].shift(-1) > cryptodataframe[“Close”]).astype(int)

cryptodataframe = cryptodataframe.dropna()

X = cryptodataframe[[“Close”]].values # using only ‘Close’ for simplicity

y = cryptodataframe[“Target”].values

# Normalize features

scaler = StandardScaler()

X = scaler.fit_transform(X)

# Train-test split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=9)

# ---------------------------

# 2. Formation of Quantum circuit

# ---------------------------

n_qubits = 1

cdev = qmllib.cdevice(“default.qubit”, wires=n_qubits)

def myfeature_encoding(x):

“””Encode classical data into qubit rotation.”””

qmllib.RX(x[0], wires=0)





def myvariational_block(weights):

“””Simple variational layer.”””

qmllib.RY(weights[0], wires=0)

qmllib.RZ(weights[1], wires=0)

@qmllib.qnode(cdev)

def myquantum_circuit(x, weights):

feature_encoding(x)

variational_block(weights)

return qmllib.expval(qmllib.PauliZ(0))

# --------------------------

# 3. Model + Training loop

# --------------------------

def myquantum_model(x, weights):

return myquantum_circuit(x, weights)

def cost(weights, X, y):

pred = [myquantum_model(x, weights) for x in X]

pred = np.sign(pred) # convert to {-1,1}

y_mod = 2*y - 1 # convert labels {0,1} -> {-1,1}

return np.mean(pred != y_mod)

# ----------------------------

# Initialize weights

# ----------------------------

myweights = np.random.randn(2, requires_grad=True)

myopt = qmllib.GradientDescentOptimizer(stepsize=0.1)

# ----------------------------

# Training

# ----------------------------

for epoch in range(15):

myweights, _ = myopt.step_and_cost(lambda w: cost(w, X_train, y_train), weights)

train_loss = cost(weights, X_train, y_train)

test_loss = cost(weights, X_test, y_test)

print(f”Epoch {epoch+1:2d}: Train Error={train_loss:.3f}, Test Error={test_loss:.3f}”)

# ----------------------------

# 4. Analytics and Inference

# ----------------------------

pred = [myquantum_model(x, myweights) for x in X_test]

pred_labels = (np.sign(pred) + 1)//2

print(“\n Outcome Predictions:”, pred_labels[:10])

print(“Outcome True labels: “, y_test[:10])

The output is:

Sample predictions: [0. 1. 1. 1. 1. 1. 1. 1. 1. 0.]

True labels: [1 0 1 1 1 1 1 1 0 1]

In sample predictions, the output depicts either 1 or 0, where 1 predicts the price will go up and 0 predicts it will fall. ‘True labels’ gives the actual price increase and fall. This value is used to verify the accuracy of the model.

Student assessments using QML

The quantum machine learning code given below helps assess the knowledge of students in three different subjects. It uses quantum classifiers to predict whether they will pass or fail tests in these subjects.

from pennylane import numpy as np

import pennylane as qml

# QML Device Circuit Formation: 3 qubits for 3 subjects

mydev = qml.device(“default.qubit”, wires=3)

@qml.qnode(dev)

def studentcircuit(sscores, sweights):

# Encoding of score of subject in a qubit

for i, sscore in enumerate(sscores):

qml.RX(sscore, swires=i)

# Variational layer

for i in range(3):

qml.RY(sweights[i], wires=i)

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

# Student Data

sscores = np.array([0.7, 0.6, 0.9])

sweights = np.array([0.2, 0.4, 0.7], requires_grad=True)

sprediction = studentcircuit(sscores, sweights)

print(“Prediction:”, “Pass” if sprediction > 0 else “Fail”)

This QML-based approach helps assess teaching and learning processes with a higher degree of performance and accuracy.

A few key use cases of QML-based quantum computing for academics are:

  • Optimisation of grading rubrics
  • Weighing of questions
  • Personalised feedbacks
  • Hidden patterns analysis in attendance, grades and participation
  • Performance predictions
Quantum circuit for student assessments
Figure 3: Quantum circuit for student assessments

There is huge scope for research in quantum data science, quantum machine learning and quantum deep learning. Traditional implementations of classification, regression, and clustering can be improved using quantum circuits. Quantum computing enables multi-dimensional analytics in minimum time with maximum accuracy. Researchers can develop and simulate novel quantum circuits for solving real world problems including portfolio optimisation in investments (banking and finance), prediction of protein folding (disease research), quantum key distribution (secured communications), traffic management (smart cities), and climate modelling (disaster prediction).

Previous articlePyTorch Is Ready, But Is Embedded AI?
Next articleGoogle and VeriSilicon Launch Open Source Coral NPU IP
The author is the managing director of Magma Research and Consultancy Pvt Ltd, Ambala Cantonment, Haryana. He has 16 years experience in teaching, in industry and in research. He is a projects contributor for the Web-based source code repository SourceForge.net. He is associated with various central, state and deemed universities in India as a research guide and consultant. He is also an author and consultant reviewer/member of advisory panels for various journals, magazines and periodicals. The author can be reached at kumargaurav.in@gmail.com.

LEAVE A REPLY

Please enter your comment!
Please enter your name here