SlideShare une entreprise Scribd logo
1  sur  11
Télécharger pour lire hors ligne
In [10]: import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
#from qiskit import QuantumCircuit, transpile, Aer, IBMQ
import qiskit
from qiskit import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# For Pytorch
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
ibmqfactory.load_account:WARNING:2021-07-11 06:46:28,261: Credentials
are already in use. The existing account in the session will be repla
ced.
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
1 of 11 7/11/2021, 1:05 PM
In [11]: class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for thet
a in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
2 of 11 7/11/2021, 1:05 PM
In [12]: #import qiskit
#from qiskit import QuantumCircuit, transpile, Aer
simulator = qiskit.Aer.get_backend('aer_simulator')
circuit = QuantumCircuit(1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.p
i])[0]))
circuit._circuit.draw()
Expected value for rotation pi 0.58
Out[12]:
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
3 of 11 7/11/2021, 1:05 PM
In [13]: class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shif
t
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor
([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(),
None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.s
hift)
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
4 of 11 7/11/2021, 1:05 PM
In [14]: # Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTen
sor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuff
le=True)
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.
gz to ./data/MNIST/raw/train-images-idx3-ubyte.gz
Extracting ./data/MNIST/raw/train-images-idx3-ubyte.gz to ./data/MNIS
T/raw
Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.
gz to ./data/MNIST/raw/train-labels-idx1-ubyte.gz
Extracting ./data/MNIST/raw/train-labels-idx1-ubyte.gz to ./data/MNIS
T/raw
Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.g
z to ./data/MNIST/raw/t10k-images-idx3-ubyte.gz
Extracting ./data/MNIST/raw/t10k-images-idx3-ubyte.gz to ./data/MNIST
/raw
Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.g
z to ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz
Extracting ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ./data/MNIST
/raw
Processing...
/opt/conda/lib/python3.8/site-packages/torchvision/datasets/mnist.py:
479: UserWarning: The given NumPy array is not writeable, and PyTorch
does not support non-writeable tensors. This means you can write to t
he underlying (supposedly non-writeable) NumPy array using the tenso
r. You may want to copy the array to protect its data or make it writ
eable before converting it to a tensor. This type of warning will be
suppressed for the rest of this program. (Triggered internally at /p
ytorch/torch/csrc/utils/tensor_numpy.cpp:143.)
return torch.from_numpy(parsed.astype(m[2], copy=False)).view(*s)
Done!
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
5 of 11 7/11/2021, 1:05 PM
In [15]: n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10,
3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='
gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.ite
m()))
n_samples_show -= 1
In [16]: n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTens
or()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle
=True)
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
6 of 11 7/11/2021, 1:05 PM
In [17]: class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('aer_simulator'), 1
00, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
7 of 11 7/11/2021, 1:05 PM
In [18]: model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
8 of 11 7/11/2021, 1:05 PM
In [19]: plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
<ipython-input-13-625640256c98>:32: FutureWarning: The input object o
f type 'Tensor' is an array-like implementing one of the correspondin
g protocols (`__array__`, `__array_interface__` or `__array_struct__
`); but not a sequence (or 0-D). In the future, this object will be c
oerced as if it was first converted using `np.array(obj)`. To retain
the old behaviour, you have to either modify the type 'Tensor', or as
sign to an empty array created with `np.empty(correct_shape, dtype=ob
ject)`.
gradients = np.array([gradients]).T
Training [5%] Loss: -0.8143
Training [10%] Loss: -0.9220
Training [15%] Loss: -0.9286
Training [20%] Loss: -0.9489
Training [25%] Loss: -0.9479
Training [30%] Loss: -0.9516
Training [35%] Loss: -0.9703
Training [40%] Loss: -0.9635
Training [45%] Loss: -0.9707
Training [50%] Loss: -0.9702
Training [55%] Loss: -0.9769
Training [60%] Loss: -0.9757
Training [65%] Loss: -0.9823
Training [70%] Loss: -0.9897
Training [75%] Loss: -0.9850
Training [80%] Loss: -0.9866
Training [85%] Loss: -0.9905
Training [90%] Loss: -0.9908
Training [95%] Loss: -0.9921
Training [100%] Loss: -0.9889
Out[19]: Text(0, 0.5, 'Neg Log Likelihood Loss')
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
9 of 11 7/11/2021, 1:05 PM
In [20]: model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:ntLoss: {:.4f}ntAccuracy: {:.1
f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
In [21]: n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10,
3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
Performance on test data:
Loss: -0.9862
Accuracy: 100.0%
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
10 of 11 7/11/2021, 1:05 PM
In [ ]: #Hybrid quantum-classical Neural Networks with PyTorch and Qiskit,execu
ted by Bhadale IT
QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d...
11 of 11 7/11/2021, 1:05 PM

Contenu connexe

Tendances

JAISTサマースクール2016「脳を知るための理論」講義01 Single neuron models
JAISTサマースクール2016「脳を知るための理論」講義01 Single neuron modelsJAISTサマースクール2016「脳を知るための理論」講義01 Single neuron models
JAISTサマースクール2016「脳を知るための理論」講義01 Single neuron modelshirokazutanaka
 
Quantum computing
Quantum computingQuantum computing
Quantum computingEmrah Semiz
 
BLUE BRAIN PERFECT WITH ANIMATION FINAL
BLUE BRAIN PERFECT WITH ANIMATION FINALBLUE BRAIN PERFECT WITH ANIMATION FINAL
BLUE BRAIN PERFECT WITH ANIMATION FINALAjith Kumar Ravi
 
Taking Quantum Computing for a Spin: What is Imaginary and What is Real?
Taking Quantum Computing for a Spin: What is Imaginary and What is Real?Taking Quantum Computing for a Spin: What is Imaginary and What is Real?
Taking Quantum Computing for a Spin: What is Imaginary and What is Real?Mike Hogarth, MD, FACMI, FACP
 
Quantum Computing, Quantum Machine Learning, and Recommendation Systems
Quantum Computing, Quantum Machine Learning, and Recommendation SystemsQuantum Computing, Quantum Machine Learning, and Recommendation Systems
Quantum Computing, Quantum Machine Learning, and Recommendation SystemsSyed Falahuddin Quadri
 
Quantum computing in machine learning
Quantum computing in machine learningQuantum computing in machine learning
Quantum computing in machine learningkhalidhassan105
 
Quantum Internet By Professor Lili Saghafi
Quantum Internet By Professor Lili SaghafiQuantum Internet By Professor Lili Saghafi
Quantum Internet By Professor Lili SaghafiProfessor Lili Saghafi
 
Quantum computing
Quantum computingQuantum computing
Quantum computingRitwik MG
 
Presentation quantum computers
Presentation quantum computersPresentation quantum computers
Presentation quantum computersAzeemAhmed55
 
052516 week11 quantum computers
052516 week11 quantum computers052516 week11 quantum computers
052516 week11 quantum computersSubas Nandy
 
Quantum Computing and AI
Quantum Computing and AIQuantum Computing and AI
Quantum Computing and AIAhmed Banafa
 
ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )
ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )
ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )Kenji Urai
 
Quantum Internet Explained
Quantum Internet ExplainedQuantum Internet Explained
Quantum Internet ExplainedAhmed Banafa
 
DockerでAlmaLinux(web, php, pukiwiki)環境構築
DockerでAlmaLinux(web, php, pukiwiki)環境構築DockerでAlmaLinux(web, php, pukiwiki)環境構築
DockerでAlmaLinux(web, php, pukiwiki)環境構築Yoshihiro Mizoguchi
 
Literature Survey on Detection of Brain Tumor from MRI Images
Literature Survey on Detection of Brain Tumor from MRI Images Literature Survey on Detection of Brain Tumor from MRI Images
Literature Survey on Detection of Brain Tumor from MRI Images IOSR Journals
 
論文紹介 Amortized bayesian meta learning
論文紹介 Amortized bayesian meta learning論文紹介 Amortized bayesian meta learning
論文紹介 Amortized bayesian meta learningXiangze
 

Tendances (20)

JAISTサマースクール2016「脳を知るための理論」講義01 Single neuron models
JAISTサマースクール2016「脳を知るための理論」講義01 Single neuron modelsJAISTサマースクール2016「脳を知るための理論」講義01 Single neuron models
JAISTサマースクール2016「脳を知るための理論」講義01 Single neuron models
 
Cognitive Computing
Cognitive ComputingCognitive Computing
Cognitive Computing
 
Quantum computing
Quantum computingQuantum computing
Quantum computing
 
BLUE BRAIN PERFECT WITH ANIMATION FINAL
BLUE BRAIN PERFECT WITH ANIMATION FINALBLUE BRAIN PERFECT WITH ANIMATION FINAL
BLUE BRAIN PERFECT WITH ANIMATION FINAL
 
Taking Quantum Computing for a Spin: What is Imaginary and What is Real?
Taking Quantum Computing for a Spin: What is Imaginary and What is Real?Taking Quantum Computing for a Spin: What is Imaginary and What is Real?
Taking Quantum Computing for a Spin: What is Imaginary and What is Real?
 
Quantum Computing, Quantum Machine Learning, and Recommendation Systems
Quantum Computing, Quantum Machine Learning, and Recommendation SystemsQuantum Computing, Quantum Machine Learning, and Recommendation Systems
Quantum Computing, Quantum Machine Learning, and Recommendation Systems
 
Quantum computing in machine learning
Quantum computing in machine learningQuantum computing in machine learning
Quantum computing in machine learning
 
Quantum Internet By Professor Lili Saghafi
Quantum Internet By Professor Lili SaghafiQuantum Internet By Professor Lili Saghafi
Quantum Internet By Professor Lili Saghafi
 
Quantum computing
Quantum computingQuantum computing
Quantum computing
 
What is the point of Boson sampling?
What is the point of Boson sampling?What is the point of Boson sampling?
What is the point of Boson sampling?
 
Presentation quantum computers
Presentation quantum computersPresentation quantum computers
Presentation quantum computers
 
052516 week11 quantum computers
052516 week11 quantum computers052516 week11 quantum computers
052516 week11 quantum computers
 
Blue Brain
Blue BrainBlue Brain
Blue Brain
 
Quantum Computing and AI
Quantum Computing and AIQuantum Computing and AI
Quantum Computing and AI
 
ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )
ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )
ガウス過程回帰の導出 ( GPR : Gaussian Process Regression )
 
Quantum Internet Explained
Quantum Internet ExplainedQuantum Internet Explained
Quantum Internet Explained
 
DockerでAlmaLinux(web, php, pukiwiki)環境構築
DockerでAlmaLinux(web, php, pukiwiki)環境構築DockerでAlmaLinux(web, php, pukiwiki)環境構築
DockerでAlmaLinux(web, php, pukiwiki)環境構築
 
Literature Survey on Detection of Brain Tumor from MRI Images
Literature Survey on Detection of Brain Tumor from MRI Images Literature Survey on Detection of Brain Tumor from MRI Images
Literature Survey on Detection of Brain Tumor from MRI Images
 
論文紹介 Amortized bayesian meta learning
論文紹介 Amortized bayesian meta learning論文紹介 Amortized bayesian meta learning
論文紹介 Amortized bayesian meta learning
 
BLUE_BRAIN
BLUE_BRAINBLUE_BRAIN
BLUE_BRAIN
 

Similaire à Hybrid quantum classical neural networks with pytorch and qiskit

6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demo6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demoNAP Events
 
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Thomas Fan
 
Machine Learning - Introduction
Machine Learning - IntroductionMachine Learning - Introduction
Machine Learning - IntroductionEmpatika
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortStefan Marr
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3San Kim
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Ganesan Narayanasamy
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialJin-Hwa Kim
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3Max Kleiner
 
maxbox starter60 machine learning
maxbox starter60 machine learningmaxbox starter60 machine learning
maxbox starter60 machine learningMax Kleiner
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 

Similaire à Hybrid quantum classical neural networks with pytorch and qiskit (20)

alexnet.pdf
alexnet.pdfalexnet.pdf
alexnet.pdf
 
6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demo6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demo
 
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
 
Grover's Algorithm
Grover's AlgorithmGrover's Algorithm
Grover's Algorithm
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
SCIPY-SYMPY.pdf
SCIPY-SYMPY.pdfSCIPY-SYMPY.pdf
SCIPY-SYMPY.pdf
 
Machine Learning - Introduction
Machine Learning - IntroductionMachine Learning - Introduction
Machine Learning - Introduction
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
 
Multi qubit entanglement
Multi qubit entanglementMulti qubit entanglement
Multi qubit entanglement
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorial
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
Dive Into PyTorch
Dive Into PyTorchDive Into PyTorch
Dive Into PyTorch
 
maxbox starter60 machine learning
maxbox starter60 machine learningmaxbox starter60 machine learning
maxbox starter60 machine learning
 
svm classification
svm classificationsvm classification
svm classification
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Python Software Testing in Kytos.io
Python Software Testing in Kytos.ioPython Software Testing in Kytos.io
Python Software Testing in Kytos.io
 

Plus de Vijayananda Mohire

NexGen Solutions for cloud platforms, powered by GenQAI
NexGen Solutions for cloud platforms, powered by GenQAINexGen Solutions for cloud platforms, powered by GenQAI
NexGen Solutions for cloud platforms, powered by GenQAIVijayananda Mohire
 
Certificate- Peer Review of Book Chapter on ML
Certificate- Peer Review of Book Chapter on MLCertificate- Peer Review of Book Chapter on ML
Certificate- Peer Review of Book Chapter on MLVijayananda Mohire
 
Key projects Data Science and Engineering
Key projects Data Science and EngineeringKey projects Data Science and Engineering
Key projects Data Science and EngineeringVijayananda Mohire
 
Key projects Data Science and Engineering
Key projects Data Science and EngineeringKey projects Data Science and Engineering
Key projects Data Science and EngineeringVijayananda Mohire
 
Bhadale IT Hub-Multi Cloud and Multi QAI
Bhadale IT Hub-Multi Cloud and Multi QAIBhadale IT Hub-Multi Cloud and Multi QAI
Bhadale IT Hub-Multi Cloud and Multi QAIVijayananda Mohire
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 
Azure Quantum Workspace for developing Q# based quantum circuits
Azure Quantum Workspace for developing Q# based quantum circuitsAzure Quantum Workspace for developing Q# based quantum circuits
Azure Quantum Workspace for developing Q# based quantum circuitsVijayananda Mohire
 
Key projects in AI, ML and Generative AI
Key projects in AI, ML and Generative AIKey projects in AI, ML and Generative AI
Key projects in AI, ML and Generative AIVijayananda Mohire
 
My Journey towards Artificial Intelligence
My Journey towards Artificial IntelligenceMy Journey towards Artificial Intelligence
My Journey towards Artificial IntelligenceVijayananda Mohire
 
Bhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for AgricultureBhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for AgricultureVijayananda Mohire
 
Bhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for AgricultureBhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for AgricultureVijayananda Mohire
 
Bhadale IT Intel and Azure Cloud Offerings
Bhadale IT Intel and Azure Cloud OfferingsBhadale IT Intel and Azure Cloud Offerings
Bhadale IT Intel and Azure Cloud OfferingsVijayananda Mohire
 
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical ImplicationsPractical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical ImplicationsVijayananda Mohire
 
Cloud Infrastructure - Partner Delivery Accelerator (APAC)
Cloud Infrastructure - Partner Delivery Accelerator (APAC)Cloud Infrastructure - Partner Delivery Accelerator (APAC)
Cloud Infrastructure - Partner Delivery Accelerator (APAC)Vijayananda Mohire
 
Red Hat Sales Specialist - Red Hat Enterprise Linux
Red Hat Sales Specialist - Red Hat Enterprise LinuxRed Hat Sales Specialist - Red Hat Enterprise Linux
Red Hat Sales Specialist - Red Hat Enterprise LinuxVijayananda Mohire
 
Generative AI Business Transformation
Generative AI Business TransformationGenerative AI Business Transformation
Generative AI Business TransformationVijayananda Mohire
 
Microsoft Learn Transcript Jan 2024- vijaymohire
Microsoft Learn Transcript Jan 2024- vijaymohireMicrosoft Learn Transcript Jan 2024- vijaymohire
Microsoft Learn Transcript Jan 2024- vijaymohireVijayananda Mohire
 
Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0
Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0
Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0Vijayananda Mohire
 

Plus de Vijayananda Mohire (20)

NexGen Solutions for cloud platforms, powered by GenQAI
NexGen Solutions for cloud platforms, powered by GenQAINexGen Solutions for cloud platforms, powered by GenQAI
NexGen Solutions for cloud platforms, powered by GenQAI
 
Certificate- Peer Review of Book Chapter on ML
Certificate- Peer Review of Book Chapter on MLCertificate- Peer Review of Book Chapter on ML
Certificate- Peer Review of Book Chapter on ML
 
Key projects Data Science and Engineering
Key projects Data Science and EngineeringKey projects Data Science and Engineering
Key projects Data Science and Engineering
 
Key projects Data Science and Engineering
Key projects Data Science and EngineeringKey projects Data Science and Engineering
Key projects Data Science and Engineering
 
Bhadale IT Hub-Multi Cloud and Multi QAI
Bhadale IT Hub-Multi Cloud and Multi QAIBhadale IT Hub-Multi Cloud and Multi QAI
Bhadale IT Hub-Multi Cloud and Multi QAI
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 
Azure Quantum Workspace for developing Q# based quantum circuits
Azure Quantum Workspace for developing Q# based quantum circuitsAzure Quantum Workspace for developing Q# based quantum circuits
Azure Quantum Workspace for developing Q# based quantum circuits
 
Key projects in AI, ML and Generative AI
Key projects in AI, ML and Generative AIKey projects in AI, ML and Generative AI
Key projects in AI, ML and Generative AI
 
My Journey towards Artificial Intelligence
My Journey towards Artificial IntelligenceMy Journey towards Artificial Intelligence
My Journey towards Artificial Intelligence
 
Bhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for AgricultureBhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for Agriculture
 
Bhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for AgricultureBhadale IT Cloud Solutions for Agriculture
Bhadale IT Cloud Solutions for Agriculture
 
Bhadale IT Intel and Azure Cloud Offerings
Bhadale IT Intel and Azure Cloud OfferingsBhadale IT Intel and Azure Cloud Offerings
Bhadale IT Intel and Azure Cloud Offerings
 
GitHub Copilot-vijaymohire
GitHub Copilot-vijaymohireGitHub Copilot-vijaymohire
GitHub Copilot-vijaymohire
 
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical ImplicationsPractical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
 
Cloud Infrastructure - Partner Delivery Accelerator (APAC)
Cloud Infrastructure - Partner Delivery Accelerator (APAC)Cloud Infrastructure - Partner Delivery Accelerator (APAC)
Cloud Infrastructure - Partner Delivery Accelerator (APAC)
 
Red Hat Sales Specialist - Red Hat Enterprise Linux
Red Hat Sales Specialist - Red Hat Enterprise LinuxRed Hat Sales Specialist - Red Hat Enterprise Linux
Red Hat Sales Specialist - Red Hat Enterprise Linux
 
RedHat_Transcript_Jan_2024
RedHat_Transcript_Jan_2024RedHat_Transcript_Jan_2024
RedHat_Transcript_Jan_2024
 
Generative AI Business Transformation
Generative AI Business TransformationGenerative AI Business Transformation
Generative AI Business Transformation
 
Microsoft Learn Transcript Jan 2024- vijaymohire
Microsoft Learn Transcript Jan 2024- vijaymohireMicrosoft Learn Transcript Jan 2024- vijaymohire
Microsoft Learn Transcript Jan 2024- vijaymohire
 
Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0
Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0
Bhadale Group of Companies -Futuristic Products Brief-Ver 1.0
 

Dernier

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Dernier (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Hybrid quantum classical neural networks with pytorch and qiskit

  • 1. In [10]: import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries #from qiskit import QuantumCircuit, transpile, Aer, IBMQ import qiskit from qiskit import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # For Pytorch import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ibmqfactory.load_account:WARNING:2021-07-11 06:46:28,261: Credentials are already in use. The existing account in the session will be repla ced. QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 1 of 11 7/11/2021, 1:05 PM
  • 2. In [11]: class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for thet a in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 2 of 11 7/11/2021, 1:05 PM
  • 3. In [12]: #import qiskit #from qiskit import QuantumCircuit, transpile, Aer simulator = qiskit.Aer.get_backend('aer_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.p i])[0])) circuit._circuit.draw() Expected value for rotation pi 0.58 Out[12]: QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 3 of 11 7/11/2021, 1:05 PM
  • 4. In [13]: class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shif t shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor ([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.s hift) QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 4 of 11 7/11/2021, 1:05 PM
  • 5. In [14]: # Concentrating on the first 100 samples n_samples = 100 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTen sor()])) # Leaving only labels 0 and 1 idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuff le=True) Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte. gz to ./data/MNIST/raw/train-images-idx3-ubyte.gz Extracting ./data/MNIST/raw/train-images-idx3-ubyte.gz to ./data/MNIS T/raw Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte. gz to ./data/MNIST/raw/train-labels-idx1-ubyte.gz Extracting ./data/MNIST/raw/train-labels-idx1-ubyte.gz to ./data/MNIS T/raw Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.g z to ./data/MNIST/raw/t10k-images-idx3-ubyte.gz Extracting ./data/MNIST/raw/t10k-images-idx3-ubyte.gz to ./data/MNIST /raw Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.g z to ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz Extracting ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ./data/MNIST /raw Processing... /opt/conda/lib/python3.8/site-packages/torchvision/datasets/mnist.py: 479: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to t he underlying (supposedly non-writeable) NumPy array using the tenso r. You may want to copy the array to protect its data or make it writ eable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /p ytorch/torch/csrc/utils/tensor_numpy.cpp:143.) return torch.from_numpy(parsed.astype(m[2], copy=False)).view(*s) Done! QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 5 of 11 7/11/2021, 1:05 PM
  • 6. In [15]: n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap=' gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.ite m())) n_samples_show -= 1 In [16]: n_samples = 50 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTens or()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle =True) QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 6 of 11 7/11/2021, 1:05 PM
  • 7. In [17]: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('aer_simulator'), 1 00, np.pi / 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 7 of 11 7/11/2021, 1:05 PM
  • 8. In [18]: model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 8 of 11 7/11/2021, 1:05 PM
  • 9. In [19]: plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') <ipython-input-13-625640256c98>:32: FutureWarning: The input object o f type 'Tensor' is an array-like implementing one of the correspondin g protocols (`__array__`, `__array_interface__` or `__array_struct__ `); but not a sequence (or 0-D). In the future, this object will be c oerced as if it was first converted using `np.array(obj)`. To retain the old behaviour, you have to either modify the type 'Tensor', or as sign to an empty array created with `np.empty(correct_shape, dtype=ob ject)`. gradients = np.array([gradients]).T Training [5%] Loss: -0.8143 Training [10%] Loss: -0.9220 Training [15%] Loss: -0.9286 Training [20%] Loss: -0.9489 Training [25%] Loss: -0.9479 Training [30%] Loss: -0.9516 Training [35%] Loss: -0.9703 Training [40%] Loss: -0.9635 Training [45%] Loss: -0.9707 Training [50%] Loss: -0.9702 Training [55%] Loss: -0.9769 Training [60%] Loss: -0.9757 Training [65%] Loss: -0.9823 Training [70%] Loss: -0.9897 Training [75%] Loss: -0.9850 Training [80%] Loss: -0.9866 Training [85%] Loss: -0.9905 Training [90%] Loss: -0.9908 Training [95%] Loss: -0.9921 Training [100%] Loss: -0.9889 Out[19]: Text(0, 0.5, 'Neg Log Likelihood Loss') QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 9 of 11 7/11/2021, 1:05 PM
  • 10. In [20]: model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:ntLoss: {:.4f}ntAccuracy: {:.1 f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) In [21]: n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model(data) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 Performance on test data: Loss: -0.9862 Accuracy: 100.0% QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 10 of 11 7/11/2021, 1:05 PM
  • 11. In [ ]: #Hybrid quantum-classical Neural Networks with PyTorch and Qiskit,execu ted by Bhadale IT QuantumML https://notebooks.quantum-computing.ibm.com/user/60e12d043ea3ef2d... 11 of 11 7/11/2021, 1:05 PM