(model_path, model, algo_name)
| 360 | |
| 361 | |
| 362 | def visualize(model_path, model, algo_name): |
| 363 | if not MATPLOTLIB_AVAIBLABLE: |
| 364 | logger.error("visualize requires matplotlib package ...") |
| 365 | return |
| 366 | pred = OfflinePredictor(PredictConfig( |
| 367 | session_init=SmartInit(model_path), |
| 368 | model=model(), |
| 369 | input_names=['input'], |
| 370 | output_names=['emb'])) |
| 371 | |
| 372 | NUM_BATCHES = 6 |
| 373 | BATCH_SIZE = 128 |
| 374 | images = np.zeros((BATCH_SIZE * NUM_BATCHES, 28, 28)) # the used digits |
| 375 | embed = np.zeros((BATCH_SIZE * NUM_BATCHES, 2)) # the actual embeddings in 2-d |
| 376 | |
| 377 | # get only the embedding model data (MNIST test) |
| 378 | ds = get_test_data() |
| 379 | ds.reset_state() |
| 380 | |
| 381 | for offset, dp in enumerate(ds): |
| 382 | digit, label = dp |
| 383 | prediction = pred(digit)[0] |
| 384 | embed[offset * BATCH_SIZE:offset * BATCH_SIZE + BATCH_SIZE, ...] = prediction |
| 385 | images[offset * BATCH_SIZE:offset * BATCH_SIZE + BATCH_SIZE, ...] = digit |
| 386 | offset += 1 |
| 387 | if offset == NUM_BATCHES: |
| 388 | break |
| 389 | |
| 390 | plt.figure() |
| 391 | ax = plt.subplot(111) |
| 392 | ax_min = np.min(embed, 0) |
| 393 | ax_max = np.max(embed, 0) |
| 394 | |
| 395 | ax_dist_sq = np.sum((ax_max - ax_min)**2) |
| 396 | ax.axis('off') |
| 397 | shown_images = np.array([[1., 1.]]) |
| 398 | for i in range(embed.shape[0]): |
| 399 | dist = np.sum((embed[i] - shown_images)**2, 1) |
| 400 | if np.min(dist) < 3e-4 * ax_dist_sq: # don't show points that are too close |
| 401 | continue |
| 402 | shown_images = np.r_[shown_images, [embed[i]]] |
| 403 | imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(np.reshape(images[i, ...], [28, 28]), |
| 404 | zoom=0.6, cmap=plt.cm.gray_r), xy=embed[i], frameon=False) |
| 405 | ax.add_artist(imagebox) |
| 406 | |
| 407 | plt.axis([ax_min[0], ax_max[0], ax_min[1], ax_max[1]]) |
| 408 | plt.xticks([]), plt.yticks([]) |
| 409 | plt.title('Embedding using %s-loss' % algo_name) |
| 410 | plt.savefig('%s.jpg' % algo_name) |
| 411 | |
| 412 | |
| 413 | if __name__ == '__main__': |
no test coverage detected