classification_cnn_keras_svd.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. '''This script goes along the blog post
  2. "Building powerful image classification models using very little data"
  3. from blog.keras.io.
  4. ```
  5. data/
  6. train/
  7. final/
  8. final001.png
  9. final002.png
  10. ...
  11. noisy/
  12. noisy001.png
  13. noisy002.png
  14. ...
  15. validation/
  16. final/
  17. final001.png
  18. final002.png
  19. ...
  20. noisy/
  21. noisy001.png
  22. noisy002.png
  23. ...
  24. ```
  25. '''
  26. import sys, os, getopt
  27. from keras.preprocessing.image import ImageDataGenerator
  28. from keras.models import Sequential
  29. from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
  30. from keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization
  31. from keras.optimizers import Adam
  32. from keras.regularizers import l2
  33. from keras import backend as K
  34. from keras.utils import plot_model
  35. import matplotlib.pyplot as plt
  36. import tensorflow as tf
  37. import numpy as np
  38. from modules.model_helper import plot_info
  39. from modules.image_metrics import svd_metric
  40. # configuration
  41. # dimensions of our images.
  42. img_width, img_height = 100, 1
  43. train_data_dir = 'data/train'
  44. validation_data_dir = 'data/validation'
  45. nb_train_samples = 7200
  46. nb_validation_samples = 3600
  47. epochs = 200
  48. batch_size = 30
  49. if K.image_data_format() == 'channels_first':
  50. input_shape = (3, img_width, img_height)
  51. else:
  52. input_shape = (img_width, img_height, 3)
  53. '''
  54. Method which returns model to train
  55. @return : DirectoryIterator
  56. '''
  57. def generate_model():
  58. model = Sequential()
  59. model.add(Conv2D(100, (2, 1), input_shape=input_shape))
  60. model.add(Activation('relu'))
  61. model.add(MaxPooling2D(pool_size=(2, 1)))
  62. model.add(Conv2D(80, (2, 1)))
  63. model.add(Activation('relu'))
  64. model.add(AveragePooling2D(pool_size=(2, 1)))
  65. model.add(Conv2D(50, (2, 1)))
  66. model.add(Activation('relu'))
  67. model.add(MaxPooling2D(pool_size=(2, 1)))
  68. model.add(Flatten())
  69. model.add(BatchNormalization())
  70. model.add(Dense(300, kernel_regularizer=l2(0.01)))
  71. model.add(Activation('relu'))
  72. model.add(Dropout(0.4))
  73. model.add(Dense(30, kernel_regularizer=l2(0.01)))
  74. model.add(BatchNormalization())
  75. model.add(Activation('relu'))
  76. model.add(Dropout(0.3))
  77. model.add(Dense(100, kernel_regularizer=l2(0.01)))
  78. model.add(BatchNormalization())
  79. model.add(Activation('relu'))
  80. model.add(Dropout(0.2))
  81. model.add(Dense(20, kernel_regularizer=l2(0.01)))
  82. model.add(BatchNormalization())
  83. model.add(Activation('relu'))
  84. model.add(Dropout(0.1))
  85. model.add(Dense(1))
  86. model.add(Activation('sigmoid'))
  87. model.compile(loss='binary_crossentropy',
  88. optimizer='rmsprop',
  89. metrics=['accuracy'])
  90. return model
  91. '''
  92. Method which loads train data
  93. @return : DirectoryIterator
  94. '''
  95. def load_train_data():
  96. # this is the augmentation configuration we will use for training
  97. train_datagen = ImageDataGenerator(
  98. rescale=1. / 255,
  99. #shear_range=0.2,
  100. #zoom_range=0.2,
  101. #horizontal_flip=True,
  102. preprocessing_function=svd_metric.get_s_model_data)
  103. train_generator = train_datagen.flow_from_directory(
  104. train_data_dir,
  105. target_size=(img_width, img_height),
  106. batch_size=batch_size,
  107. class_mode='binary')
  108. return train_generator
  109. '''
  110. Method which loads validation data
  111. @return : DirectoryIterator
  112. '''
  113. def load_validation_data():
  114. # this is the augmentation configuration we will use for testing:
  115. # only rescaling
  116. test_datagen = ImageDataGenerator(
  117. rescale=1. / 255,
  118. preprocessing_function=svd_metric.get_s_model_data)
  119. validation_generator = test_datagen.flow_from_directory(
  120. validation_data_dir,
  121. target_size=(img_width, img_height),
  122. batch_size=batch_size,
  123. class_mode='binary')
  124. return validation_generator
  125. def main():
  126. global batch_size
  127. global epochs
  128. if len(sys.argv) <= 1:
  129. print('No output file defined...')
  130. print('classification_cnn_keras_svd.py --output xxxxx')
  131. sys.exit(2)
  132. try:
  133. opts, args = getopt.getopt(sys.argv[1:], "ho:b:e:d", ["help", "directory=", "output=", "batch_size=", "epochs="])
  134. except getopt.GetoptError:
  135. # print help information and exit:
  136. print('classification_cnn_keras_svd.py --output xxxxx')
  137. sys.exit(2)
  138. for o, a in opts:
  139. if o == "-h":
  140. print('classification_cnn_keras_svd.py --output xxxxx')
  141. sys.exit()
  142. elif o in ("-o", "--output"):
  143. filename = a
  144. elif o in ("-b", "--batch_size"):
  145. batch_size = int(a)
  146. elif o in ("-e", "--epochs"):
  147. epochs = int(a)
  148. elif o in ("-d", "--directory"):
  149. directory = a
  150. else:
  151. assert False, "unhandled option"
  152. # load of model
  153. model = generate_model()
  154. model.summary()
  155. if(directory):
  156. print('Your model information will be saved into %s...' % directory)
  157. history = model.fit_generator(
  158. load_train_data(),
  159. steps_per_epoch=nb_train_samples // batch_size,
  160. epochs=epochs,
  161. validation_data=load_validation_data(),
  162. validation_steps=nb_validation_samples // batch_size)
  163. # if user needs output files
  164. if(filename):
  165. # update filename by folder
  166. if(directory):
  167. # create folder if necessary
  168. if not os.path.exists(directory):
  169. os.makedirs(directory)
  170. filename = directory + "/" + filename
  171. # save plot file history
  172. plot_info.save(history, filename)
  173. plot_model(model, to_file=str(('%s.png' % filename)))
  174. model.save_weights(str('%s.h5' % filename))
  175. if __name__ == "__main__":
  176. main()