test.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import tensorflow as tf
  2. import tensorflow.keras as keras
  3. from keras import layers
  4. from keras.layers import Input, Embedding, LSTM, Dense, Dropout, Flatten, MaxPooling2D, Conv2D
  5. from keras.models import Model, Sequential
  6. from keras.datasets import mnist
  7. from keras.utils import plot_model, to_categorical
  8. import numpy as np
  9. from IPython import embed
  10. batch_size = 128
  11. num_classes = 10
  12. epochs = 1 # 12
  13. # input image dimensions
  14. img_rows, img_cols = 28, 28
  15. # the data, split between train and test sets
  16. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  17. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
  18. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
  19. input_shape = (img_rows, img_cols, 1)
  20. x_train = x_train.astype('float32')
  21. x_test = x_test.astype('float32')
  22. x_train /= 255
  23. x_test /= 255
  24. print('x_train shape:', x_train.shape)
  25. print(x_train.shape[0], 'train samples')
  26. print(x_test.shape[0], 'test samples')
  27. # convert class vectors to binary class matrices
  28. y_train = to_categorical(y_train, num_classes)
  29. y_test = to_categorical(y_test, num_classes)
  30. class Linear(layers.Layer):
  31. def __init__(self, units=32, input_dim=32):
  32. super(Linear, self).__init__()
  33. w_init = tf.random_normal_initializer()
  34. self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units),
  35. dtype='float32'),
  36. trainable=True)
  37. b_init = tf.zeros_initializer()
  38. self.b = tf.Variable(initial_value=b_init(shape=(units,),
  39. dtype='float32'),
  40. trainable=True)
  41. def call(self, inputs):
  42. print(inputs)
  43. embed()
  44. return tf.matmul(inputs, self.w) + self.b
  45. model = Sequential()
  46. model.add(Conv2D(32, kernel_size=(3, 3),
  47. activation='relu',
  48. input_shape=input_shape))
  49. model.add(Conv2D(64, (3, 3), activation='relu'))
  50. model.add(MaxPooling2D(pool_size=(2, 2)))
  51. model.add(Dropout(0.25))
  52. model.add(Flatten())
  53. model.add(Dense(128, activation='relu'))
  54. model.add(Dropout(0.5))
  55. model.add(Dense(num_classes, activation='softmax'))
  56. model.add(Linear(10,10))
  57. model.compile(loss=keras.losses.categorical_crossentropy,
  58. optimizer=keras.optimizers.Adadelta(),
  59. metrics=['accuracy'])
  60. model.fit(x_train, y_train,
  61. batch_size=batch_size,
  62. epochs=epochs,
  63. verbose=1,
  64. validation_data=(x_test, y_test))
  65. score = model.evaluate(x_test, y_test, verbose=0)
  66. print('Test loss:', score[0])
  67. print('Test accuracy:', score[1])
  68. plot_model(model, to_file='model.png', expand_nested=True, show_shapes=True)