forked from BenediktRiegel/quantum-no-free-lunch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualisation.py
231 lines (183 loc) · 8.32 KB
/
visualisation.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from typing import List
import numpy as np
import json
from metrics import *
from numpy.polynomial.polynomial import polyfit
# create plot analogous average risk vs. training pairs
def set_fontsize(text=10, title=10, labels=10, xtick=10, ytick=10, legend=10):
plt.rc('font', size=text) # controls default text size
plt.rc('axes', titlesize=title) # fontsize of the title
plt.rc('axes', labelsize=labels) # fontsize of the x and y labels
plt.rc('xtick', labelsize=xtick) # fontsize of the x tick labels
plt.rc('ytick', labelsize=ytick) # fontsize of the y tick labels
plt.rc('legend', fontsize=legend) # fontsize of the legend
def generate_markers():
return [".", ",", "o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s",
"p", "P", "*", "h", "H", "+", "x", "X", "D", "d", "|", "_"]
def generate_pairs(max_rank):
# construct pairs on which to evaluate experiment
ranks = [i for i in range(0, max_rank + 1)]
num_train_pairs = [i for i in range(1, 2 ** max_rank + 1)]
return ranks, num_train_pairs
def get_result(ranks, num_train_pairs):
data_points = get_test_results(ranks, num_train_pairs)
return data_points
def plot_fig2():
results = np.load('./experimental_results/exp1/result.npy')
for i in range(len(results)):
plt.plot(range(1, 3), results[i, :], label=f"r={2**i}")
plt.xlabel('Number of Training pairs t')
plt.ylabel('Average Risk')
plt.title('Average Riks vs. Number of Training pairs')
plt.legend()
plt.savefig('./experimental_results/exp1/result.png')
plt.cla()
def plot_fig3():
with open('./experimental_results/exp2/result.json', 'r') as f:
result = json.load(f)
f.close()
# color_palette = generate_color_palette(num_ranks)
num_qbits = 6
color = cm.rainbow(np.linspace(0, 10, num_qbits + 1))
markers = generate_markers()
ranks, num_train_pairs = generate_pairs(num_qbits + 1)
for rank, color in zip(ranks, color):
plt.plot(num_train_pairs, result[rank], color=color, marker=markers[rank], label='r=' + str(2 ** rank))
# create deterministic line
def f(t):
return (1 - 1 / (2 ** num_qbits)) * (1 - t / (2 ** num_qbits))
xvals = np.linspace(0, 2 ** num_qbits, 200)
yvals = list(map(f, xvals))
plt.plot(xvals, yvals, color='k', marker='--', label='Deterministic')
plt.xlabel('Number of Training pairs t')
plt.ylabel('Average Risk')
plt.title('Average Riks vs. Number of Training pairs')
plt.legend()
plt.show()
def plot_simple_mean_std(upper_std):
with open('./experimental_results/exp_std_mean/result.json', 'r') as f:
result = json.load(f)
f.close()
# color_palette = generate_color_palette(num_ranks)
with open('./experimental_results/exp_std_mean/result.json' + 'config.json', 'r') as f:
config = json.load(f)
num_qbits = config['num_qbits']
color = cm.rainbow(np.linspace(0, 10, upper_std))
std_values = [i for i in range(0,upper_std)]
for std, color in zip(std_values, color):
plt.plot(std, result[std], color=color, label='std=' + str(std))
# create deterministic line
def f(t):
return (1 - 1 / (2 ** num_qbits)) * (1 - t / (2 ** num_qbits))
#xvals = np.linspace(0, 2 ** num_qbits, 200)
#yvals = list(map(f, xvals))
#plt.plot(xvals, yvals, color='k', marker='--', label='Deterministic')
plt.xlabel('Standard deviation')
plt.ylabel('Average Risk')
plt.title('Average Riks vs. Std')
plt.legend()
plt.show()
def plot_mean_std():
with open('./experimental_results/exp_std_mean/result.json', 'r') as f:
result = json.load(f)
f.close()
# color_palette = generate_color_palette(num_ranks)
with open('./experimental_results/exp_std_mean/result.json' + 'config.json', 'r') as f:
config = json.load(f)
num_qbits = config['num_qbits']
# color_palette = generate_color_palette(num_ranks)
max_rank = 2**config['num_qbits']
color = cm.rainbow(np.linspace(0, 10, max_rank- config['rank']))
markers = generate_markers()
num_train_pairs = [i for i in range(1, 2 ** max_rank + 1)]
for std, color in zip(ranks, color):
plt.plot(num_train_pairs, result[std], color=color, marker=markers[ra], label='std=' + str(std))
# create deterministic line
def f(t):
return (1 - 1 / (2 ** num_qbits)) * (1 - t / (2 ** num_qbits))
#xvals = np.linspace(0, 2 ** num_qbits, 200)
#yvals = list(map(f, xvals))
#plt.plot(xvals, yvals, color='k', marker='--', label='Deterministic')
plt.xlabel('Number of Training pairs t')
plt.ylabel('Average Risk')
plt.title('Average Riks vs. Number of Training pairs')
plt.legend()
plt.show()
def plot_loss(losses, num_qbits, num_layers, num_points, r_list, name_addition=''):
if isinstance(losses[0], list):
losses = np.array(losses)
# losses shape is r x layer x epochs
for j in range(len(num_layers)):
num_layer = num_layers[j]
for i in range(len(r_list)):
r = r_list[i]
loss = losses[i, j]
plt.plot(list(range(len(loss))), loss, label=f"r={r}")
plt.legend()
plt.title(f"Loss for net with {num_qbits} qbits, {num_layer} layers, {num_points} data points")
plt.xlabel("epochs")
plt.ylabel("loss")
plt.savefig(f"./plots/loss_{num_qbits}_qbits_{num_layer}_layers_{num_points}_datapoints{name_addition}.png")
plt.cla()
else:
plt.plot(list(range(len(losses))), losses)
plt.title(f"Loss for net with {num_qbits} qbits, {num_layers} layers, {num_points} data points, {2**r_list} schmidt rank")
plt.xlabel("epochs")
plt.ylabel("loss")
plt.savefig(f"./plots/loss_{num_qbits}_qbits_{num_layers}_layers_{num_points}_datapoints_{2**r_list}_schmidtrank{name_addition}.png")
plt.cla()
# r=Schmidt rank, t=num points, d=dimensionality
def calc_lower_bound(r, t, d):
numerator = ((r*t)**2) + d + 1 # r^2 * t^2 + d + 1
denominator = d*(d+1) # d*(d+1)
return max(0, 1-(numerator/denominator))
def generate_fluctuation_plot(results, num_datapoints, x_qbits, r_list):
"""
Generate fluctuation plot from paper Sharma in appendix
"""
tableau_palette = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:gray',
'tab:pink', 'tab:olive', 'tab:cyan']
markers = generate_markers()[2:]
for r_idx in range(len(r_list)):
r = r_list[r_idx]
rank = 2 ** r
result_std = [el.std() for el in results[r]]
plt.scatter(num_datapoints, result_std, label=f"r={rank}", marker=markers[r_idx], c=tableau_palette[r_idx])
# do linear regression
num_datapoints_float = np.arange(2 ** x_qbits + 1)
b, m = polyfit(num_datapoints,result_std, 1)
plt.plot(num_datapoints, b + m * num_datapoints_float, '-', c=tableau_palette[r_idx])
plt.xlabel('No. of Datapoints')
plt.ylabel('Fluctuation in Risk')
plt.legend()
plt.title(f'Fluctuation in Risk for {x_qbits} Qubit Unitary')
plt.tight_layout()
plt.savefig(f'./plots/{x_qbits}_qubit_exp_fluct.png')
plt.cla()
def generate_risk_plot(results, num_datapoints, x_qbits, r_list):
"""
"""
tableau_palette = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:gray', 'tab:pink', 'tab:olive', 'tab:cyan']
markers = generate_markers()[2:]
for r_idx in range(len(r_list)):
r = r_list[r_idx]
rank = 2**r
d = 2**x_qbits
quantum_bound = [calc_lower_bound(rank, num_points, d) for num_points in num_datapoints]
plt.plot(num_datapoints, quantum_bound, label=f"r={rank} bound", marker='.', c=tableau_palette[r_idx], linestyle='dashed')
for r_idx in range(len(r_list)):
r = r_list[r_idx]
rank = 2**r
result_mean = [el.mean() for el in results[r]]
plt.scatter(num_datapoints, result_mean, label=f"r={rank}", marker=markers[r_idx], c=tableau_palette[r_idx])
plt.xlabel('No. of Datapoints')
plt.ylabel('Average Risk')
plt.legend()
plt.title(f'Average Risk for {x_qbits} Qubit Unitary')
plt.tight_layout()
plt.savefig(f'./plots/{x_qbits}_qubit_exp.png')
plt.cla()
if __name__ == '__main__':
pass