-
Notifications
You must be signed in to change notification settings - Fork 1
/
tfquantum_starter.py
133 lines (89 loc) · 3.8 KB
/
tfquantum_starter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# -*- coding: utf-8 -*-
"""TFQuantum_starter.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1aq8jWy1AEpNqn1xb_ojhRTpiePNe5ebZ
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Rishit-dagli/TFUG-Mysuru-2020/blob/master/TFQuantum_starter.ipynb)
# Getting started with [TensorFlow Quantum](https://www.tensorflow.org/quantum)
In this notebook you will build your first hybrid quantum classical model with
[Cirq](https://cirq.readthedocs.io/en/stable/) and TensorFlow Quantum (TFQ). We will build a very simple model to do
binary classification in this notebook. You will then use Keras to create a wrapper for the model and simulate it to
train and evluate the model.
> Note: This notebook is designed to be run in Google Colab if you want to run it locally or on a Jupyter notebook you
would skip the code cells with the `Colab only` comment.
## Setup
### Install TensorFlow 2.x (Colab only)
"""
# Colab only
pip install -q tensorflow==2.1.0
"""### Install TensorFlow Quantum (Colab only)"""
# Colab only
pip install -q tensorflow-quantum
"""### Imports
Now import TensorFlow and the module dependencies:
"""
import cirq
import random
import numpy as np
import sympy
import tensorflow as tf
import tensorflow_quantum as tfq
from matplotlib import pyplot as plt
from cirq.contrib.svg import SVGCircuit
"""### Place a qubit on the grid
You will then place a qubit on thee grid
"""
qubit = cirq.GridQubit(0, 0)
"""## Prepare quantum data
The first thing you would do is set up the labels and parameters for preparation of the quantum data. For simplicity
here we have included just 2 data points `a` and `b`.
"""
expected_labels = np.array([[1, 0], [0, 1]])
"""Randonly rotate `x` and `z` axis"""
angle = np.random.uniform(0, 2 * np.pi)
"""## Building the quantum Circuit
You will now build the quantum circuit and also convert it into a tensor
"""
a = cirq.Circuit(cirq.ry(angle)(qubit))
b = cirq.Circuit(cirq.ry(angle + np.pi / 2)(qubit))
quantum_data = tfq.convert_to_tensor([a, b])
SVGCircuit(a)
SVGCircuit(b)
"""## Building the hybrid model
This section also shows the interoperatability between TensorFlow and Cirq. With the TFQ PQC layer you can easily
embed your quantum part of the model within a standard classical Keras model.
"""
q_data_input = tf.keras.Input(shape = (), dtype = tf.dtypes.string)
theta = sympy.Symbol("theta")
q_model = cirq.Circuit(cirq.ry(theta)(qubit))
expectation = tfq.layers.PQC(q_model, cirq.Z(qubit))
expectation_output = expectation(q_data_input)
classifier = tf.keras.layers.Dense(2, activation = tf.keras.activations.softmax)
classifier_output = classifier(expectation_output)
"""You will now define the optimizer and loss functions for your model"""
model = tf.keras.Model(inputs = q_data_input,
outputs = classifier_output)
model.compile(optimizer = tf.keras.optimizers.Adam(learning_rate = 0.1),
loss = tf.keras.losses.CategoricalCrossentropy())
"""## Traaining the model
Training the model is just like training any other Keras model and is made easy.
"""
history = model.fit(x = quantum_data,
y = expected_labels,
epochs = 250)
"""## Evaluating the model"""
plt.plot(history.history['loss'])
plt.title('model loss')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train'], loc='upper left')
plt.show()
"""## Performing inference"""
noise = np.random.uniform(-0.25, 0.25, 2)
test_data = tfq.convert_to_tensor([
cirq.Circuit(cirq.ry(noise[0])(qubit)),
cirq.Circuit(cirq.ry(noise[1] + np.pi/2)(qubit)),
])
"""You can see in the below cell that our model does a good job with this data though it was very easy."""
predictions = model.predict(test_data)
predictions