daily pastebin goal
87%
SHARE
TWEET

Untitled

a guest Jan 17th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import keras
  2. from keras.datasets import mnist
  3. import matplotlib.pyplot as plt
  4.  
  5. from keras.models import Sequential
  6. from keras.layers import Dense, Dropout, Activation, Flatten
  7. from keras.layers import Conv2D, MaxPooling2D
  8.  
  9.  
  10. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  11.  
  12. img_rows = x_train.shape[1]
  13. img_cols = x_train.shape[2]
  14. channels = 1 # since images are in greyscale
  15.  
  16. print('Training data oryginal shape', x_train.shape)
  17. print('Testing data oryginal shape', x_test.shape)
  18.  
  19. # reshape data to be in form (num,row,col,chanel)
  20. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, channels)
  21. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, channels)
  22.  
  23.  
  24. target_train = keras.utils.to_categorical(y_train, 10)
  25.  
  26. target_test = keras.utils.to_categorical(y_test, 10)
  27.  
  28.  
  29. data_train = x_train.astype('float32')
  30. data_test = x_test.astype('float32')
  31.  
  32.  
  33. convNN = Sequential()
  34.  
  35. convNN.add(Conv2D(5, (5, 5), strides = (1, 1), padding='same', input_shape=(28, 28, 1), \
  36.                   activation='relu'))
  37. convNN.add(Conv2D(5, (3, 3), strides = (3, 3)))
  38. convNN.add(Activation('relu'))
  39. convNN.add(MaxPooling2D(pool_size=(3, 3)))
  40.  
  41. convNN.add(Flatten())
  42. convNN.add(Dense(50))
  43. convNN.add(Activation('relu'))
  44. convNN.add(Dense(10))
  45. convNN.add(Activation('softmax'))
  46.  
  47. convNN.summary()
  48.  
  49.  
  50. #hyberparameters parameters
  51. batch_size = 500
  52. epochs = 10
  53.  
  54. # select and initiate optimizer
  55. opt_sgd = keras.optimizers.sgd(lr=0.05)
  56.  
  57.  
  58. convNN.compile(loss='categorical_crossentropy', optimizer=opt_sgd, metrics=['accuracy'])
  59.  
  60.  
  61. run_hist_sgd = convNN.fit(data_train, target_train, batch_size=batch_size, epochs=epochs,
  62.                           validation_data=(data_test, target_test), shuffle=True,
  63.                           verbose=1) #verbose = 0: no verbose; 1: progress barr; 2: summary afer epch
  64.  
  65. #model accuracy
  66. scores = convNN.evaluate(data_test, target_test, verbose=True)
  67. print('Test accuracy:', scores[1])
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top