Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. '''Trains a simple ConvNet on the MNIST dataset. It gets more than 99% test accuracy after 12 epochs
  2. (but there is still a lot of margin for parameter tuning). Training can take a few minutes!'''
  3.  
  4. # Import libraries
  5. from __future__ import print_function
  6. import keras
  7. from keras.datasets import mnist
  8. from keras.models import Sequential
  9. from keras.layers import Dense, Dropout, Flatten
  10. from keras.layers import Conv2D, MaxPooling2D
  11. from keras import backend as K
  12.  
  13. # Define hyperparameters
  14. batch_size = 128
  15. num_classes = 10
  16. epochs = 12
  17.  
  18. # Input image dimensions
  19. img_rows, img_cols = 28, 28
  20.  
  21. # Split the data between train and test sets
  22. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  23.  
  24. if K.image_data_format() == 'channels_first':
  25. x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
  26. x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
  27. input_shape = (1, img_rows, img_cols)
  28. else:
  29. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
  30. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
  31. input_shape = (img_rows, img_cols, 1)
  32.  
  33. x_train = x_train.astype('float32')
  34. x_test = x_test.astype('float32')
  35. x_train /= 255
  36. x_test /= 255
  37. print('x_train shape:', x_train.shape)
  38. print(x_train.shape[0], 'train samples')
  39. print(x_test.shape[0], 'test samples')
  40.  
  41. # Convert class vectors to binary class matrices
  42. y_train = keras.utils.to_categorical(y_train, num_classes)
  43. y_test = keras.utils.to_categorical(y_test, num_classes)
  44.  
  45. # Define the sequential Keras model composed of a few layers
  46. model = Sequential()
  47. model.add(Conv2D(64, kernel_size=(4, 3),activation='relu', input_shape=input_shape))
  48. model.add(Conv2D(64, (5, 5), activation='relu'))
  49. model.add(MaxPooling2D(pool_size=(4, 4)))
  50. model.add(Dropout(0.10))
  51. model.add(Flatten())
  52. model.add(Dense(128, activation='relu'))
  53. model.add(Dropout(0.15))
  54. model.add(Dense(num_classes, activation='softmax'))
  55.  
  56. # Compile the model using optimizer
  57. model.compile(loss=keras.losses.categorical_crossentropy,
  58. optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])
  59.  
  60. # Train the model, validate, evaluate, and present scores
  61. model.fit(x_train, y_train,batch_size=batch_size, epochs=epochs,
  62. verbose=1, validation_data=(x_test, y_test))
  63. score = model.evaluate(x_test, y_test, verbose=0)
  64. print('Test loss:', score[0])
  65. print('Test accuracy:', score[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement