|
| 1 | +import numpy as np |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +import tensorflow as tf |
| 4 | + |
| 5 | + |
| 6 | +def hist_dist(title, distribution_tensor, hist_range=(-4, 4)): |
| 7 | + """ |
| 8 | + Display histogram of a TF distribution |
| 9 | + """ |
| 10 | + with tf.Session() as sess: |
| 11 | + values = sess.run(distribution_tensor) |
| 12 | + |
| 13 | + plt.title(title) |
| 14 | + plt.hist(values, np.linspace(*hist_range, num=len(values)/2)) |
| 15 | + plt.show() |
| 16 | + |
| 17 | + |
| 18 | +def _get_loss_acc(dataset, weights): |
| 19 | + """ |
| 20 | + Get losses and validation accuracy of example neural network |
| 21 | + """ |
| 22 | + batch_size = 128 |
| 23 | + epochs = 2 |
| 24 | + learning_rate = 0.001 |
| 25 | + |
| 26 | + features = tf.placeholder(tf.float32) |
| 27 | + labels = tf.placeholder(tf.float32) |
| 28 | + learn_rate = tf.placeholder(tf.float32) |
| 29 | + |
| 30 | + biases = [ |
| 31 | + tf.Variable(tf.zeros([256])), |
| 32 | + tf.Variable(tf.zeros([128])), |
| 33 | + tf.Variable(tf.zeros([dataset.train.labels.shape[1]])) |
| 34 | + ] |
| 35 | + |
| 36 | + # Layers |
| 37 | + layer_1 = tf.nn.relu(tf.matmul(features, weights[0]) + biases[0]) |
| 38 | + layer_2 = tf.nn.relu(tf.matmul(layer_1, weights[1]) + biases[1]) |
| 39 | + logits = tf.matmul(layer_2, weights[2]) + biases[2] |
| 40 | + |
| 41 | + # Training loss |
| 42 | + loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels)) |
| 43 | + |
| 44 | + # Optimizer |
| 45 | + optimizer = tf.train.AdamOptimizer(learn_rate).minimize(loss) |
| 46 | + |
| 47 | + # Accuracy |
| 48 | + correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) |
| 49 | + accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) |
| 50 | + |
| 51 | + # Measurements use for graphing loss |
| 52 | + loss_batch = [] |
| 53 | + |
| 54 | + with tf.Session() as session: |
| 55 | + session.run(tf.global_variables_initializer()) |
| 56 | + batch_count = int((dataset.train.num_examples / batch_size)) |
| 57 | + |
| 58 | + # The training cycle |
| 59 | + for epoch_i in range(epochs): |
| 60 | + for batch_i in range(batch_count): |
| 61 | + batch_features, batch_labels = dataset.train.next_batch(batch_size) |
| 62 | + |
| 63 | + # Run optimizer and get loss |
| 64 | + session.run( |
| 65 | + optimizer, |
| 66 | + feed_dict={features: batch_features, labels: batch_labels, learn_rate: learning_rate}) |
| 67 | + l = session.run( |
| 68 | + loss, |
| 69 | + feed_dict={features: batch_features, labels: batch_labels, learn_rate: learning_rate}) |
| 70 | + loss_batch.append(l) |
| 71 | + |
| 72 | + valid_acc = session.run( |
| 73 | + accuracy, |
| 74 | + feed_dict={features: dataset.validation.images, labels: dataset.validation.labels, learn_rate: 1.0}) |
| 75 | + |
| 76 | + # Hack to Reset batches |
| 77 | + dataset.train._index_in_epoch = 0 |
| 78 | + dataset.train._epochs_completed = 0 |
| 79 | + |
| 80 | + return loss_batch, valid_acc |
| 81 | + |
| 82 | + |
| 83 | +def compare_init_weights( |
| 84 | + dataset, |
| 85 | + title, |
| 86 | + weight_init_list, |
| 87 | + plot_n_batches=100): |
| 88 | + """ |
| 89 | + Plot loss and print stats of weights using an example neural network |
| 90 | + """ |
| 91 | + colors = ['r', 'b', 'g', 'c', 'y', 'k'] |
| 92 | + label_accs = [] |
| 93 | + label_loss = [] |
| 94 | + |
| 95 | + assert len(weight_init_list) <= len(colors), 'Too many inital weights to plot' |
| 96 | + |
| 97 | + for i, (weights, label) in enumerate(weight_init_list): |
| 98 | + loss, val_acc = _get_loss_acc(dataset, weights) |
| 99 | + |
| 100 | + plt.plot(loss[:plot_n_batches], colors[i], label=label) |
| 101 | + label_accs.append((label, val_acc)) |
| 102 | + label_loss.append((label, loss[-1])) |
| 103 | + |
| 104 | + plt.title(title) |
| 105 | + plt.xlabel('Batches') |
| 106 | + plt.ylabel('Loss') |
| 107 | + plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) |
| 108 | + plt.show() |
| 109 | + |
| 110 | + print('After 858 Batches (2 Epochs):') |
| 111 | + print('Validation Accuracy') |
| 112 | + for label, val_acc in label_accs: |
| 113 | + print(' {:7.3f}% -- {}'.format(val_acc*100, label)) |
| 114 | + print('Loss') |
| 115 | + for label, loss in label_loss: |
| 116 | + print(' {:7.3f} -- {}'.format(loss, label)) |
0 commit comments