-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpopulation.py
234 lines (169 loc) · 9.31 KB
/
population.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
232
233
234
""" Copyright (c) 2020, Daniela Szwarcman and IBM Research
* Licensed under The MIT License [see LICENSE for details]
- Quantum population classes.
"""
import numpy as np
from chromosome import QChromosomeParams, QChromosomeNetwork
class QPopulation(object):
""" QNAS Population to be evolved. """
def __init__(self, num_quantum_ind, repetition, update_quantum_rate):
""" Initialize QPopulation.
Args:
num_quantum_ind: (int) number of quantum individuals.
repetition: (int) ratio between the number of classic individuals in the classic
population and the quantum individuals in the quantum population.
update_quantum_rate: (float) probability that a quantum gene will be updated.
"""
self.dtype = np.float64 # Type of quantum population arrays.
self.chromosome = None
self.current_pop = None
self.num_ind = num_quantum_ind
self.repetition = repetition
self.update_quantum_rate = update_quantum_rate
def initialize_qpop(self):
raise NotImplementedError('initialize_qpop() must be implemented in sub classes')
def generate_classical(self):
raise NotImplementedError('generate_classical() must be implemented in sub classes')
def update_quantum(self, intensity):
raise NotImplementedError('update_quantum() must be implemented in sub classes')
class QPopulationParams(QPopulation):
""" QNAS Chromosomes for the hyperparameters to be evolved. """
def __init__(self, num_quantum_ind, params_ranges, repetition, crossover_rate,
update_quantum_rate):
""" Initialize QPopulationParams.
Args:
num_quantum_ind: (int) number of quantum individuals.
params_ranges: {'parameter_name': [parameter_lower_limit, parameter_upper_limit]}.
repetition: (int) ratio between the number of classic individuals in the classic
population and the quantum individuals in the quantum population.
crossover_rate: (float) crossover rate.
update_quantum_rate: (float) probability that a quantum gene will be updated.
"""
super(QPopulationParams, self).__init__(num_quantum_ind, repetition,
update_quantum_rate)
self.tolerance = 1.e-15 # Tolerance to compare floating point
self.lower = None
self.upper = None
self.crossover = crossover_rate
self.chromosome = QChromosomeParams(params_ranges, self.dtype)
self.initial_lower, self.initial_upper = self.chromosome.initialize_qgenes()
self.initialize_qpop()
def initialize_qpop(self):
""" Initialize quantum population with *self.num_ind* individuals. """
self.lower = np.tile(self.initial_lower, (self.num_ind, 1))
self.upper = np.tile(self.initial_upper, (self.num_ind, 1))
def classic_crossover(self, new_pop, distance):
""" Perform arithmetic crossover of the old classic population with the new one.
Args:
new_pop: float numpy array representing the new classical population.
distance: (float) random distance for arithmetic crossover (range = [0, 1]).
"""
mask = np.random.rand(self.num_ind * self.repetition, self.chromosome.num_genes)
idx = np.where(mask <= self.crossover)
new_pop[idx] = new_pop[idx] + (self.current_pop[idx] - new_pop[idx]) * distance
return new_pop
def generate_classical(self):
""" Generate a specific number of classical individuals from the observation of quantum
individuals. This number is equal to (*num_ind* x *repetition*).
"""
random_numbers = np.random.rand(self.num_ind * self.repetition,
self.chromosome.num_genes).astype(self.dtype)
new_pop = random_numbers * np.tile(self.upper - self.lower, (self.repetition, 1)) \
+ np.tile(self.lower, (self.repetition, 1))
return new_pop
def update_quantum(self, intensity):
""" Update self.lower and self.upper.
Args:
intensity: (float) value defining the maximum intensity of the update.
"""
random = np.random.rand(self.num_ind, self.chromosome.num_genes)
mask = np.where(random <= self.update_quantum_rate)
max_genes = np.max(self.current_pop, axis=0)
min_genes = np.min(self.current_pop, axis=0)
diff = np.tile(max_genes - min_genes, (self.num_ind, 1))
update = self.current_pop[mask] - self.lower[mask] - (diff[mask] / 2)
self.lower[mask] += intensity * update
update = self.current_pop[mask] - self.upper[mask] + (diff[mask] / 2)
self.upper[mask] += intensity * update
# Correct limits (truncate) if they get out of the initial boundaries
for i in range(self.num_ind):
idx = np.where(self.lower[i] - self.initial_lower < -self.tolerance)
self.lower[i][idx] = self.initial_lower[idx]
idx = np.where(self.upper[i] - self.initial_upper > self.tolerance)
self.upper[i][idx] = self.initial_upper[idx]
class QPopulationNetwork(QPopulation):
""" QNAS Chromosomes for the networks to be evolved. """
def __init__(self, num_quantum_ind, max_num_nodes, repetition, update_quantum_rate,
fn_list, initial_probs):
""" Initialize QPopulationNetwork.
Args:
num_quantum_ind: (int) number of quantum individuals.
max_num_nodes: (int) maximum number of nodes of the network, which will be the
number of genes in a individual.
repetition: (int) ratio between the number of classic individuals in the classic
population and the quantum individuals in the quantum population.
update_quantum_rate: (float) probability that a quantum gene will be updated.
fn_list: list of possible functions.
initial_probs: list defining the initial probabilities for each function; if empty,
the algorithm will give the same probability for each function.
"""
super(QPopulationNetwork, self).__init__(num_quantum_ind, repetition,
update_quantum_rate)
self.probabilities = None
self.max_update = 0.05
self.max_prob = 0.99
self.chromosome = QChromosomeNetwork(max_num_nodes, fn_list, self.dtype)
self.initial_probs = self.chromosome.initialize_qgenes(initial_probs=initial_probs)
self.initialize_qpop()
def initialize_qpop(self):
""" Initialize quantum population with *self.num_ind* individuals. """
# Shape = (num_ind, num_nodes, num_functions)
self.probabilities = np.tile(self.initial_probs, (self.num_ind,
self.chromosome.num_genes, 1))
def generate_classical(self):
""" Generate a specific number of classical individuals from the observation of quantum
individuals. This number is equal to (*num_ind* x *repetition*).
"""
def sample(idx0, idx1):
return np.random.choice(size, p=temp_prob[idx0, idx1, :])
size = self.chromosome.num_functions
new_pop = np.zeros(shape=(self.num_ind * self.repetition, self.chromosome.num_genes),
dtype=np.int32)
temp_prob = np.tile(self.probabilities, (self.repetition, 1, 1))
for ind in range(self.num_ind * self.repetition):
for node in range(self.chromosome.num_genes):
new_pop[ind, node] = sample(ind, node)
return new_pop
def _update(self, chromosomes, idx, update_value):
""" Modify *chromosomes* by adding *update_value* to the genes indicated by *idx* and
subtracting *update_value* from the other genes proportional to the size of each
probability.
Args:
chromosomes: 2D float numpy array representing the chromosomes to be updated.
idx: (int) index of the genes to have their value increased.
update_value: (float) value that will be added to the selected functions in
*chromosomes* by *idx*.
Returns:
modified chromosome
"""
idx0 = np.arange(chromosomes.shape[0])
update_array = np.where(chromosomes[idx0, idx] + update_value > self.max_prob,
0, update_value)
sum_values = chromosomes[idx0, idx] + update_array
chromosomes[idx0, idx] = 0
decrease = (update_array / np.sum(chromosomes, axis=1)).reshape(-1, 1)
decrease = decrease * chromosomes
chromosomes = chromosomes - decrease
chromosomes[idx0, idx] = sum_values
return chromosomes
def update_quantum(self, intensity):
""" Update self.probabilities.
Args:
intensity: (float) value defining the intensity of the update.
"""
random = np.random.rand(self.num_ind, self.chromosome.num_genes)
mask = np.where(random <= self.update_quantum_rate)
update_value = intensity * self.max_update
best_classic = self.current_pop[:self.num_ind]
self.probabilities[mask] = self._update(self.probabilities[mask], best_classic[mask],
update_value)