|
| 1 | +import copy |
| 2 | +import gzip |
| 3 | +import pickle |
| 4 | +from matplotlib import pyplot |
| 5 | +import numpy |
| 6 | +import time |
| 7 | + |
| 8 | + |
| 9 | +def get_datasets(file_name): |
| 10 | + file = gzip.open(file_name, "rb") |
| 11 | + _training_set, _validation_set, _testing_set = pickle.load(file, encoding="latin") |
| 12 | + file.close() |
| 13 | + return _training_set, _validation_set, _testing_set |
| 14 | + |
| 15 | + |
| 16 | +def add_ones(samples): |
| 17 | + samples_number, _ = numpy.shape(samples) |
| 18 | + ones = numpy.ones((samples_number, 1)) |
| 19 | + return numpy.hstack((samples, ones)) |
| 20 | + |
| 21 | + |
| 22 | +def one_hot_encode(labels): |
| 23 | + return numpy.eye(numpy.max(labels) + 1)[labels] |
| 24 | + |
| 25 | + |
| 26 | +def create_weights(samples, labels, hidden_neurons=100): |
| 27 | + pixels = numpy.shape(samples)[1] |
| 28 | + digits = numpy.shape(labels)[1] |
| 29 | + hidden_weights = numpy.random.randn(pixels, hidden_neurons) / numpy.sqrt(pixels) |
| 30 | + output_weights = numpy.random.randn(hidden_neurons + 1, digits) / numpy.sqrt(hidden_neurons + 1) |
| 31 | + return {"hidden": hidden_weights, "output": output_weights} |
| 32 | + |
| 33 | + |
| 34 | +def create_batches(samples, labels, batch_size=10): |
| 35 | + sample_number = numpy.shape(samples)[0] |
| 36 | + batch_number = sample_number / batch_size |
| 37 | + permutation = numpy.random.permutation(sample_number) |
| 38 | + shuffled_samples = samples[permutation, :] |
| 39 | + shuffled_labels = labels[permutation, :] |
| 40 | + return zip(numpy.vsplit(shuffled_samples, batch_number), numpy.vsplit(shuffled_labels, batch_number)) |
| 41 | + |
| 42 | + |
| 43 | +def initialize_gradients(weights): |
| 44 | + return {"hidden": numpy.zeros(numpy.shape(weights["hidden"])), |
| 45 | + "output": numpy.zeros(numpy.shape(weights["output"]))} |
| 46 | + |
| 47 | + |
| 48 | +def activate(values): |
| 49 | + return 1 / (1 + numpy.exp(-values)) |
| 50 | + |
| 51 | + |
| 52 | +def derive(values): |
| 53 | + return values * (1 - values) |
| 54 | + |
| 55 | + |
| 56 | +def softmax(values): |
| 57 | + exponentials = numpy.exp(values) |
| 58 | + return exponentials / numpy.sum(exponentials, axis=1, keepdims=True) |
| 59 | + |
| 60 | + |
| 61 | +def feed_forward(samples, weights): |
| 62 | + hidden_activations = activate(numpy.dot(samples, weights["hidden"])) |
| 63 | + output_activations = softmax(numpy.dot(add_ones(hidden_activations), weights["output"])) |
| 64 | + return {"hidden": hidden_activations, "output": output_activations} |
| 65 | + |
| 66 | + |
| 67 | +def back_propagate(samples, labels, weights, activations): |
| 68 | + output_errors = activations["output"] - labels |
| 69 | + output_gradients = numpy.dot(numpy.transpose(add_ones(activations["hidden"])), output_errors) |
| 70 | + hidden_errors = derive(activations["hidden"]) * numpy.dot(output_errors, numpy.transpose(weights["output"][:-1, :])) |
| 71 | + hidden_gradients = numpy.dot(numpy.transpose(samples), hidden_errors) |
| 72 | + return {"hidden": hidden_gradients, "output": output_gradients} |
| 73 | + |
| 74 | + |
| 75 | +def train(samples, labels, iterations, batch_size, learning_rate, momentum, regularization): |
| 76 | + sample_number = numpy.shape(samples)[0] |
| 77 | + weights = create_weights(samples, labels) |
| 78 | + iterations_weights = list() |
| 79 | + start_time = time.time() |
| 80 | + for iteration in range(iterations): |
| 81 | + for sample_batch, label_batch in create_batches(samples, labels, batch_size): |
| 82 | + added_gradients = initialize_gradients(weights) |
| 83 | + for batch in range(batch_size): |
| 84 | + sample = sample_batch[batch:batch + 1, :] |
| 85 | + label = label_batch[batch:batch + 1, :] |
| 86 | + activations = feed_forward(sample, weights) |
| 87 | + gradients = back_propagate(sample, label, weights, activations) |
| 88 | + for layer in ["hidden", "output"]: |
| 89 | + added_gradients[layer] = momentum * added_gradients[layer] - learning_rate * gradients[layer] |
| 90 | + for layer in ["hidden", "output"]: |
| 91 | + weights[layer] = (1 - learning_rate * regularization / sample_number) * weights[layer] + \ |
| 92 | + added_gradients[layer] / batch_size |
| 93 | + iterations_weights.append(copy.deepcopy(weights)) |
| 94 | + # end_time = time.time() |
| 95 | + # print("Iteration {}: {} cost ({} seconds)" |
| 96 | + # .format(iteration + 1, compute_cost(labels, feed_forward(samples, weights)["output"]), |
| 97 | + # end_time - start_time)) |
| 98 | + # start_time = end_time |
| 99 | + return iterations_weights |
| 100 | + |
| 101 | + |
| 102 | +def compute_cost(labels, activations): |
| 103 | + return -numpy.mean(labels * numpy.log(activations) + (1 - labels) * numpy.log(1 - activations)) |
| 104 | + |
| 105 | + |
| 106 | +def classify(samples, weights): |
| 107 | + digits = feed_forward(samples, weights)["output"] |
| 108 | + return numpy.argmax(digits, axis=1) |
| 109 | + |
| 110 | + |
| 111 | +def compute_accuracy(samples, labels, weights): |
| 112 | + samples_number, = numpy.shape(labels) |
| 113 | + predictions = classify(samples, weights) |
| 114 | + correct = predictions == labels |
| 115 | + return numpy.sum(correct) / float(samples_number) |
| 116 | + |
| 117 | + |
| 118 | +def show_accuracies(accuracies): |
| 119 | + pyplot.figure() |
| 120 | + training, = pyplot.plot(accuracies["training"], color="blue", label="training") |
| 121 | + validation, = pyplot.plot(accuracies["validation"], color="green", label="validation") |
| 122 | + testing, = pyplot.plot(accuracies["testing"], color="violet", label="testing") |
| 123 | + pyplot.legend(handles=[training, validation, testing]) |
| 124 | + pyplot.xlabel("Iterations") |
| 125 | + pyplot.ylabel("Accuracies") |
| 126 | + pyplot.show() |
| 127 | + |
| 128 | + |
| 129 | +def test(file_name="mnist.pkl.gz", iterations=30, batch_size=10, learning_rate=0.01, momentum=0.9, regularization=0.1): |
| 130 | + training_set, validation_set, testing_set = get_datasets(file_name) |
| 131 | + training_samples = add_ones(training_set[0]) |
| 132 | + training_labels = training_set[1] |
| 133 | + validation_samples = add_ones(validation_set[0]) |
| 134 | + validation_labels = validation_set[1] |
| 135 | + testing_samples = add_ones(testing_set[0]) |
| 136 | + testing_labels = testing_set[1] |
| 137 | + iterations_weights = train(training_samples, one_hot_encode(training_labels), iterations, batch_size, learning_rate, |
| 138 | + momentum, regularization) |
| 139 | + accuracies = {"training": [], "validation": [], "testing": []} |
| 140 | + for iteration_weights in iterations_weights: |
| 141 | + accuracies["training"].append(compute_accuracy(training_samples, training_labels, iteration_weights)) |
| 142 | + accuracies["validation"].append(compute_accuracy(validation_samples, validation_labels, iteration_weights)) |
| 143 | + accuracies["testing"].append(compute_accuracy(testing_samples, testing_labels, iteration_weights)) |
| 144 | + print("{} iterations, {} batch size, {} learning rate, {} momentum, {} regularization:" |
| 145 | + .format(iterations, batch_size, learning_rate, momentum, regularization)) |
| 146 | + print("{} training accuracy".format(max(accuracies["training"]))) |
| 147 | + print("{} validation accuracy".format(max(accuracies["validation"]))) |
| 148 | + print("{} testing accuracy".format(max(accuracies["testing"]))) |
| 149 | + show_accuracies(accuracies) |
| 150 | + |
| 151 | + |
| 152 | +def main(): |
| 153 | + """ |
| 154 | + 30 iterations, 10 batch size, 0.01 learning rate, 0.9 momentum, 0.1 regularization: |
| 155 | + 0.9488 training accuracy |
| 156 | + 0.952 validation accuracy |
| 157 | + 0.9478 testing accuracy |
| 158 | + """ |
| 159 | + test() |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == '__main__': |
| 163 | + main() |
0 commit comments