|
| 1 | +# save the final model to file |
| 2 | +from tensorflow.keras.datasets import fashion_mnist |
| 3 | +from keras.utils import to_categorical |
| 4 | +from keras.models import Sequential |
| 5 | +from keras.layers import Conv2D |
| 6 | +from keras.layers import MaxPooling2D |
| 7 | +from keras.layers import Dense |
| 8 | +from keras.layers import Flatten |
| 9 | +from keras.optimizers import SGD |
| 10 | + |
| 11 | + |
| 12 | +# load train and test dataset |
| 13 | +def load_dataset(): |
| 14 | + # load dataset |
| 15 | + (trainX, trainY), (testX, testY) = fashion_mnist.load_data() |
| 16 | + # reshape dataset to have a single channel |
| 17 | + trainX = trainX.reshape((trainX.shape[0], 28, 28, 1)) |
| 18 | + testX = testX.reshape((testX.shape[0], 28, 28, 1)) |
| 19 | + # one hot encode target values |
| 20 | + trainY = to_categorical(trainY) |
| 21 | + testY = to_categorical(testY) |
| 22 | + return trainX, trainY, testX, testY |
| 23 | + |
| 24 | + |
| 25 | +# scale pixels |
| 26 | +def prep_pixels(train, test): |
| 27 | + # convert from integers to floats |
| 28 | + train_norm = train.astype('float32') |
| 29 | + test_norm = test.astype('float32') |
| 30 | + # normalize to range 0-1 |
| 31 | + train_norm = train_norm / 255.0 |
| 32 | + test_norm = test_norm / 255.0 |
| 33 | + # return normalized images |
| 34 | + return train_norm, test_norm |
| 35 | + |
| 36 | + |
| 37 | +# define cnn model |
| 38 | +def define_model(): |
| 39 | + model = Sequential() |
| 40 | + model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1))) |
| 41 | + model.add(MaxPooling2D((2, 2))) |
| 42 | + model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform')) |
| 43 | + model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform')) |
| 44 | + model.add(MaxPooling2D((2, 2))) |
| 45 | + model.add(Flatten()) |
| 46 | + model.add(Dense(100, activation='relu', kernel_initializer='he_uniform')) |
| 47 | + model.add(Dense(10, activation='softmax')) |
| 48 | + # compile model |
| 49 | + # opt = SGD(lr=0.01, momentum=0.9) |
| 50 | + model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) |
| 51 | + return model |
| 52 | + |
| 53 | + |
| 54 | +# run the test harness for evaluating a model |
| 55 | +def run_test_harness(): |
| 56 | + # load dataset |
| 57 | + trainX, trainY, testX, testY = load_dataset() |
| 58 | + # prepare pixel data |
| 59 | + trainX, testX = prep_pixels(trainX, testX) |
| 60 | + # define model |
| 61 | + model = define_model() |
| 62 | + # fit model |
| 63 | + model.fit(trainX, trainY, epochs=10, batch_size=100) |
| 64 | + # evaluate model on test dataset |
| 65 | + _, acc = model.evaluate(testX, testY) |
| 66 | + print('> %.3f' % (acc * 100.0)) |
| 67 | + |
| 68 | + |
| 69 | +# entry point, run the test harness |
| 70 | +run_test_harness() |
0 commit comments