1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| '''Trains a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). 16 seconds per epoch on a GRID K520 GPU. '''
from __future__ import print_function
import requests import bs4
import numpy as np import scipy, sympy import pandas as pd
import matplotlib as mpl, matplotlib.pyplot as plt mpl.style.use("solarized-light")
import keras from keras import backend as T
class Constants(object): BATCH_SIZE = 128 NUM_CLASSES = 10 NUM_EPOCHES = 12 INPUT_IMG = { "DIM_ROWS": 28, "DIM_COLS": 28, "SHAPE": (1, 28, 28) if T.image_data_format() == "channels_first" else (28, 28, 1) } pass
class ImgData(object):
def __init__(self, src):
self.__xtrain = src[0][0] self.__ytrain = keras.utils.to_categorical(src[0][1], Constants.NUM_CLASSES) self.__xtest = src[1][0] self.__ytest = keras.utils.to_categorical(src[1][1], Constants.NUM_CLASSES)
if T.image_data_format() == "channels_first": self.__xtrain = self.__xtrain.reshape( self.__xtrain.shape[0], 1, Constants.INPUT_IMG["DIM_ROWS"], Constants.INPUT_IMG["DIM_COLS"], ).astype("float32") / 255 self.__xtest = self.__xtest.reshape( self.__xtest.shape[0], 1, Constants.INPUT_IMG["DIM_ROWS"], Constants.INPUT_IMG["DIM_COLS"], ).astype("float32") / 255
else: self.__xtrain = self.__xtrain.reshape( self.__xtrain.shape[0], Constants.INPUT_IMG["DIM_ROWS"], Constants.INPUT_IMG["DIM_COLS"], 1, ).astype("float32") / 255 self.__xtest = self.__xtest.reshape( self.__xtest.shape[0], Constants.INPUT_IMG["DIM_ROWS"], Constants.INPUT_IMG["DIM_COLS"], 1, ).astype("float32") / 255
return
def log_datashape(self): print("X Shape: %s" % self.__xtrain.shape[ 1 : ]) print("Training on %s Data, Validating on %s." % (self.__xtrain.shape[0], self.__xtest.shape[0])) return
@property def xtrain(self): return self.__xtrain
@property def ytrain(self): return self.__ytrain
@property def xtest(self): return self.__xtest
@property def ytest(self): return self.__ytest
pass
if __name__ == "__main__":
data = ImgData(keras.datasets.mnist.load_data())
seq = keras.models.Sequential(layers = [ keras.layers.convolutional.Conv2D( 32, kernel_size = (3, 3), activation = "relu", input_shape = Constants.INPUT_IMG["SHAPE"] ), keras.layers.convolutional.Conv2D(64, (3, 3), activation="relu"), keras.layers.pooling.MaxPooling2D(pool_size=(2, 2)), keras.layers.core.Dropout(rate=0.25), keras.layers.core.Flatten(), keras.layers.core.Dense(units=128, activation="relu"), keras.layers.core.Dropout(rate=0.5), keras.layers.core.Dense(units=Constants.NUM_CLASSES, activation="softmax") ])
seq.compile( loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=["accuracy"] )
history = seq.fit( x = data.xtrain, y = data.ytrain, batch_size = Constants.BATCH_SIZE, epochs = Constants.NUM_EPOCHES, verbose = 1, validation_data = (data.xtest, data.ytest) )
_eval = seq.evaluate(x=data.xtest, y=data.ytest, verbose=0) print("Test Loss: %s" % _eval[0]) print("Test Accuracy: %s" % _eval[1])
pass
|