| 289 | # calculate accuracy before training |
| 290 | # since the dataset is imbalanced, we'll report tp, tn, fp, fn |
| 291 | def get_train_accuracy(threshold=0.85): |
| 292 | positive_distances = [] |
| 293 | negative_distances = [] |
| 294 | |
| 295 | tp = 0 |
| 296 | tn = 0 |
| 297 | fp = 0 |
| 298 | fn = 0 |
| 299 | |
| 300 | batch_size = 64 |
| 301 | x_batch_1 = np.zeros([batch_size] + list(img.shape)) |
| 302 | x_batch_2 = np.zeros([batch_size] + list(img.shape)) |
| 303 | n_batches = int(np.ceil(len(train_positives) / batch_size)) |
| 304 | for i in range(n_batches): |
| 305 | print(f"pos batch: {i+1}/{n_batches}") |
| 306 | pos_batch_indices = train_positives[i * batch_size: (i + 1) * batch_size] |
| 307 | |
| 308 | # fill up x_batch and y_batch |
| 309 | j = 0 |
| 310 | for idx1, idx2 in pos_batch_indices: |
| 311 | x_batch_1[j] = train_images[idx1] |
| 312 | x_batch_2[j] = train_images[idx2] |
| 313 | j += 1 |
| 314 | |
| 315 | x1 = x_batch_1[:j] |
| 316 | x2 = x_batch_2[:j] |
| 317 | distances = model.predict([x1, x2]).flatten() |
| 318 | positive_distances += distances.tolist() |
| 319 | |
| 320 | # update tp, tn, fp, fn |
| 321 | tp += (distances < threshold).sum() |
| 322 | fn += (distances > threshold).sum() |
| 323 | |
| 324 | n_batches = int(np.ceil(len(train_negatives) / batch_size)) |
| 325 | for i in range(n_batches): |
| 326 | print(f"neg batch: {i+1}/{n_batches}") |
| 327 | neg_batch_indices = train_negatives[i * batch_size: (i + 1) * batch_size] |
| 328 | |
| 329 | # fill up x_batch and y_batch |
| 330 | j = 0 |
| 331 | for idx1, idx2 in neg_batch_indices: |
| 332 | x_batch_1[j] = train_images[idx1] |
| 333 | x_batch_2[j] = train_images[idx2] |
| 334 | j += 1 |
| 335 | |
| 336 | x1 = x_batch_1[:j] |
| 337 | x2 = x_batch_2[:j] |
| 338 | distances = model.predict([x1, x2]).flatten() |
| 339 | negative_distances += distances.tolist() |
| 340 | |
| 341 | # update tp, tn, fp, fn |
| 342 | fp += (distances < threshold).sum() |
| 343 | tn += (distances > threshold).sum() |
| 344 | |
| 345 | tpr = tp / (tp + fn) |
| 346 | tnr = tn / (tn + fp) |
| 347 | print(f"sensitivity (tpr): {tpr}, specificity (tnr): {tnr}") |
| 348 | |