mnist.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # from https://keras.io/examples/mnist_cnn/
  2. import tensorflow as tf
  3. import tensorflow.keras as keras
  4. from tensorflow.keras import layers
  5. from tensorflow.keras.layers import Input, Embedding, LSTM, Dense, Dropout, Flatten, MaxPooling2D, Conv2D
  6. from tensorflow.keras.models import Model, Sequential
  7. from tensorflow.keras.datasets import mnist
  8. from tensorflow.keras.utils import plot_model, to_categorical
  9. import numpy as np
  10. from IPython import embed
  11. import sys
  12. sys.path.append('../hostLib/')
  13. from hostLib.layers.conv2d import Conv2D as Conv2DFPGA
  14. batch_size = 128
  15. num_classes = 10
  16. epochs = 1200
  17. # input image dimensions
  18. img_rows, img_cols = 28, 28
  19. # the data, split between train and test sets
  20. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  21. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
  22. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
  23. x_train = x_train.astype('float')
  24. x_test = x_test.astype('float')
  25. #x_train /= 255
  26. #x_test /= 255
  27. print('x_train shape:', x_train.shape)
  28. print(x_train.shape[0], 'train samples')
  29. print(x_test.shape[0], 'test samples')
  30. # convert class vectors to binary class matrices
  31. y_train = to_categorical(y_train, num_classes)
  32. y_test = to_categorical(y_test, num_classes)
  33. model = Sequential()
  34. model.add(layers.Lambda(lambda x: tf.image.resize(x, (228,228)))) #to-do: implement 2 stage 28x28_3x3 conv2d with relu
  35. model.add(Conv2DFPGA(1))#32
  36. model.add(layers.Activation('relu'))
  37. model.add(layers.Lambda(lambda x: tf.image.resize(x, (228,228))))
  38. model.add(Conv2DFPGA(1))#64
  39. model.add(layers.Activation('relu'))
  40. model.add(MaxPooling2D(pool_size=(int(228/28*2), int(228/28*2))))
  41. model.add(Dropout(0.25))
  42. model.add(Flatten())
  43. model.add(Dense(128, activation='relu'))
  44. model.add(Dropout(0.5))
  45. model.add(Dense(num_classes, activation='softmax'))
  46. model.compile(loss=keras.losses.categorical_crossentropy,
  47. optimizer=keras.optimizers.Adadelta(),
  48. metrics=['accuracy'])
  49. plot_model(model, to_file='model.png', expand_nested=True, show_shapes=True)
  50. model.fit(x_train, y_train,
  51. batch_size=batch_size,
  52. epochs=epochs,
  53. verbose=1,
  54. validation_data=(x_test, y_test))
  55. score = model.evaluate(x_test, y_test, verbose=0)
  56. print('Test loss:', score[0])
  57. print('Test accuracy:', score[1])