train.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import tensorflow as tf
  2. import tensorflow.keras as keras
  3. from tensorflow.keras import layers
  4. from tensorflow.keras.layers import Input, Embedding, LSTM, Dense, Dropout, Flatten, MaxPooling2D, Conv2D
  5. from tensorflow.keras.models import Model, Sequential
  6. from tensorflow.keras.datasets import mnist
  7. from tensorflow.keras.utils import plot_model, to_categorical
  8. import numpy as np
  9. from IPython import embed
  10. import sys
  11. sys.path.append('..')
  12. from hostLib.layers.conv2D import Conv2D as Conv2DFPGA
  13. batch_size = 128
  14. num_classes = 10
  15. epochs = 1200
  16. # input image dimensions
  17. img_rows, img_cols = 28, 28
  18. # the data, split between train and test sets
  19. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  20. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
  21. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
  22. input_shape = (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. a = layers.Input(shape=(28, 28, 1))
  34. b = Conv2DFPGA(2)(a)
  35. c = Conv2DFPGA(1)(a)
  36. d = Conv2DFPGA(1)(b)
  37. e = Conv2DFPGA(2)(c)
  38. print(a)
  39. print(b)
  40. print(c)
  41. print(d)
  42. print(e)
  43. x = layers.Add()([d,e])
  44. y = layers.Flatten()(x)
  45. z = layers.Dense(num_classes, activation='softmax')(y)
  46. model = Model(inputs=a, outputs=z)
  47. print(model.output_shape)
  48. """
  49. model = Sequential()
  50. model.add(Conv2DFPGA([0,0]))
  51. model.add(Conv2DFPGA([0,0]))
  52. model.add(Conv2DFPGA([0,0]))
  53. model.add(Flatten())
  54. model.add(Dense(128, activation='relu'))
  55. model.add(Dropout(0.5))
  56. model.add(Dense(num_classes, activation='softmax'))
  57. """
  58. model.compile(loss=keras.losses.categorical_crossentropy,
  59. optimizer=keras.optimizers.Adadelta(),
  60. metrics=['accuracy'])
  61. plot_model(model, to_file='model.png', expand_nested=True, show_shapes=True)
  62. model.fit(x_train, y_train,
  63. batch_size=batch_size,
  64. epochs=epochs,
  65. verbose=1,
  66. validation_data=(x_test, y_test))
  67. score = model.evaluate(x_test, y_test, verbose=0)
  68. print('Test loss:', score[0])
  69. print('Test accuracy:', score[1])