| 153 | |
| 154 | batch_size = 64 |
| 155 | def train_generator(): |
| 156 | # for each batch, we will send 1 pair of each subject |
| 157 | # and the same number of non-matching pairs |
| 158 | n_batches = int(np.ceil(len(train_positives) / batch_size)) |
| 159 | |
| 160 | while True: |
| 161 | np.random.shuffle(train_positives) |
| 162 | |
| 163 | n_samples = batch_size * 2 |
| 164 | shape = [n_samples] + list(img.shape) |
| 165 | x_batch_1 = np.zeros(shape) |
| 166 | x_batch_2 = np.zeros(shape) |
| 167 | y_batch = np.zeros(n_samples) |
| 168 | |
| 169 | for i in range(n_batches): |
| 170 | pos_batch_indices = train_positives[i * batch_size: (i + 1) * batch_size] |
| 171 | |
| 172 | # fill up x_batch and y_batch |
| 173 | j = 0 |
| 174 | for idx1, idx2 in pos_batch_indices: |
| 175 | x_batch_1[j] = train_images[idx1] |
| 176 | x_batch_2[j] = train_images[idx2] |
| 177 | y_batch[j] = 1 # match |
| 178 | j += 1 |
| 179 | |
| 180 | # get negative samples |
| 181 | neg_indices = np.random.choice(len(train_negatives), size=len(pos_batch_indices), replace=False) |
| 182 | for neg in neg_indices: |
| 183 | idx1, idx2 = train_negatives[neg] |
| 184 | x_batch_1[j] = train_images[idx1] |
| 185 | x_batch_2[j] = train_images[idx2] |
| 186 | y_batch[j] = 0 # non-match |
| 187 | j += 1 |
| 188 | |
| 189 | x1 = x_batch_1[:j] |
| 190 | x2 = x_batch_2[:j] |
| 191 | y = y_batch[:j] |
| 192 | yield [x1, x2], y |
| 193 | |
| 194 | |
| 195 | # same thing as the train generator except no shuffling and it uses the test set |