utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import keras
  2. from keras.datasets import mnist
  3. from keras.models import Sequential
  4. from keras.layers import Dense, Dropout, Flatten
  5. from keras.layers import Conv2D, MaxPooling2D
  6. from keras import backend as K
  7. import matplotlib.pyplot as plt
  8. def plot_history(history):
  9. """Plot Results of Keras training"""
  10. plt.style.use('fivethirtyeight')
  11. epochs = list(range(1, len(history['loss']) + 1))
  12. plt.figure(figsize = (18, 6))
  13. # Losses
  14. plt.subplot(1, 2, 1)
  15. plt.plot(epochs, history['loss'], '-o', ms = 10, label = "Training Loss")
  16. plt.plot(epochs, history['val_loss'], '-*', ms = 10, label = "Validation Loss")
  17. plt.legend();
  18. plt.xlabel('Epoch'); plt.ylabel('Loss')
  19. plt.title('Losses');
  20. # Accuracy
  21. plt.subplot(1, 2, 2)
  22. plt.plot(epochs, history['acc'], '-o', ms = 10, label = 'Training Acc')
  23. plt.plot(epochs, history['val_acc'], '-*', ms = 10, label = "Validation Acc")
  24. plt.legend()
  25. plt.xlabel('Epoch'); plt.ylabel('Acc')
  26. plt.title('Accuracy');
  27. plt.suptitle('Training Curves', y= 1.05)
  28. def get_options(slack):
  29. command_dict = {'functions': {},
  30. 'attributes': {}}
  31. # Modules
  32. for d in dir(slack):
  33. if not d.startswith('_'):
  34. command_dict['functions'][d] = []
  35. command_dict['attributes'][d] = []
  36. # Iterate through methods and attributes
  37. for dd in dir(getattr(slack, d)):
  38. if not dd.startswith('_'):
  39. # List of methods and attributes
  40. l = dir(getattr(getattr(slack, d), dd))
  41. # Method (function)
  42. if '__call__' in l:
  43. command_dict['functions'][d].append(dd)
  44. # Attributes
  45. else:
  46. command_dict['attributes'][d].append(dd)
  47. return command_dict
  48. def get_data_and_model():
  49. batch_size = 128
  50. num_classes = 10
  51. epochs = 12
  52. # input image dimensions
  53. img_rows, img_cols = 28, 28
  54. # the data, split between train and test sets
  55. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  56. if K.image_data_format() == 'channels_first':
  57. x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
  58. x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
  59. input_shape = (1, img_rows, img_cols)
  60. else:
  61. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
  62. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
  63. input_shape = (img_rows, img_cols, 1)
  64. x_train = x_train.astype('float32')
  65. x_test = x_test.astype('float32')
  66. x_train /= 255
  67. x_test /= 255
  68. print('x_train shape:', x_train.shape)
  69. print(x_train.shape[0], 'train samples')
  70. print(x_test.shape[0], 'test samples')
  71. # convert class vectors to binary class matrices
  72. y_train = keras.utils.to_categorical(y_train, num_classes)
  73. y_test = keras.utils.to_categorical(y_test, num_classes)
  74. model = Sequential()
  75. model.add(Conv2D(32, kernel_size=(3, 3),
  76. activation='relu',
  77. input_shape=input_shape))
  78. model.add(Conv2D(64, (3, 3), activation='relu'))
  79. model.add(MaxPooling2D(pool_size=(2, 2)))
  80. model.add(Dropout(0.25))
  81. model.add(Flatten())
  82. model.add(Dense(128, activation='relu'))
  83. model.add(Dropout(0.5))
  84. model.add(Dense(num_classes, activation='softmax'))
  85. model.compile(loss=keras.losses.categorical_crossentropy,
  86. optimizer=keras.optimizers.Adadelta(),
  87. metrics=['accuracy'])
  88. return x_train, x_test, y_train, y_test, model