classification_cnn_keras_svd.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. import json
  28. from keras.preprocessing.image import ImageDataGenerator
  29. from keras.models import Sequential
  30. from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
  31. from keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization
  32. from keras.optimizers import Adam
  33. from keras.regularizers import l2
  34. from keras import backend as K
  35. from keras.utils import plot_model
  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. ##########################################
  41. # Global parameters (with default value) #
  42. ##########################################
  43. img_width, img_height = 100, 100
  44. train_data_dir = 'data/train'
  45. validation_data_dir = 'data/validation'
  46. nb_train_samples = 7200
  47. nb_validation_samples = 3600
  48. epochs = 50
  49. batch_size = 16
  50. input_shape = (3, img_width, img_height)
  51. ###########################################
  52. '''
  53. Method which returns model to train
  54. @return : DirectoryIterator
  55. '''
  56. def generate_model():
  57. model = Sequential()
  58. model.add(Conv2D(60, (2, 1), input_shape=input_shape))
  59. model.add(Activation('relu'))
  60. model.add(BatchNormalization())
  61. model.add(MaxPooling2D(pool_size=(2, 1)))
  62. model.add(Conv2D(40, (2, 1)))
  63. model.add(Activation('relu'))
  64. model.add(MaxPooling2D(pool_size=(2, 1)))
  65. model.add(Conv2D(30, (2, 1)))
  66. model.add(Activation('relu'))
  67. model.add(MaxPooling2D(pool_size=(2, 1)))
  68. model.add(Flatten())
  69. model.add(Dense(150, kernel_regularizer=l2(0.01)))
  70. model.add(BatchNormalization())
  71. model.add(Activation('relu'))
  72. model.add(Dropout(0.2))
  73. model.add(Dense(120, kernel_regularizer=l2(0.01)))
  74. model.add(BatchNormalization())
  75. model.add(Activation('relu'))
  76. model.add(Dropout(0.2))
  77. model.add(Dense(80, kernel_regularizer=l2(0.01)))
  78. model.add(BatchNormalization())
  79. model.add(Activation('relu'))
  80. model.add(Dropout(0.2))
  81. model.add(Dense(40, kernel_regularizer=l2(0.01)))
  82. model.add(BatchNormalization())
  83. model.add(Activation('relu'))
  84. model.add(Dropout(0.2))
  85. model.add(Dense(20, kernel_regularizer=l2(0.01)))
  86. model.add(BatchNormalization())
  87. model.add(Activation('relu'))
  88. model.add(Dropout(0.1))
  89. model.add(Dense(1))
  90. model.add(Activation('sigmoid'))
  91. model.compile(loss='binary_crossentropy',
  92. optimizer='rmsprop',
  93. metrics=['accuracy'])
  94. return model
  95. '''
  96. Method which loads train data
  97. @return : DirectoryIterator
  98. '''
  99. def load_train_data():
  100. # this is the augmentation configuration we will use for training
  101. train_datagen = ImageDataGenerator(
  102. #rescale=1. / 255,
  103. #shear_range=0.2,
  104. #zoom_range=0.2,
  105. #horizontal_flip=True,
  106. preprocessing_function=svd_metric.get_s_model_data)
  107. train_generator = train_datagen.flow_from_directory(
  108. train_data_dir,
  109. target_size=(img_width, img_height),
  110. batch_size=batch_size,
  111. class_mode='binary')
  112. return train_generator
  113. '''
  114. Method which loads validation data
  115. @return : DirectoryIterator
  116. '''
  117. def load_validation_data():
  118. # this is the augmentation configuration we will use for testing:
  119. # only rescaling
  120. test_datagen = ImageDataGenerator(
  121. #rescale=1. / 255,
  122. preprocessing_function=svd_metric.get_s_model_data)
  123. validation_generator = test_datagen.flow_from_directory(
  124. validation_data_dir,
  125. target_size=(img_width, img_height),
  126. batch_size=batch_size,
  127. class_mode='binary')
  128. return validation_generator
  129. def main():
  130. # update global variable and not local
  131. global batch_size
  132. global epochs
  133. global img_width
  134. global img_height
  135. global input_shape
  136. global train_data_dir
  137. global validation_data_dir
  138. global nb_train_samples
  139. global nb_validation_samples
  140. if len(sys.argv) <= 1:
  141. print('Run with default parameters...')
  142. print('classification_cnn_keras_svd.py --directory xxxx --output xxxxx --batch_size xx --epochs xx --img xx')
  143. sys.exit(2)
  144. try:
  145. opts, args = getopt.getopt(sys.argv[1:], "ho:d:b:e:i", ["help", "output=", "directory=", "batch_size=", "epochs=", "img="])
  146. except getopt.GetoptError:
  147. # print help information and exit:
  148. print('classification_cnn_keras_svd.py --directory xxxx --output xxxxx --batch_size xx --epochs xx --img xx')
  149. sys.exit(2)
  150. for o, a in opts:
  151. if o == "-h":
  152. print('classification_cnn_keras_svd.py --directory xxxx --output xxxxx --batch_size xx --epochs xx --img xx')
  153. sys.exit()
  154. elif o in ("-o", "--output"):
  155. filename = a
  156. elif o in ("-b", "--batch_size"):
  157. batch_size = int(a)
  158. elif o in ("-e", "--epochs"):
  159. epochs = int(a)
  160. elif o in ("-d", "--directory"):
  161. directory = a
  162. elif o in ("-i", "--img"):
  163. img_height = int(a)
  164. img_width = int(a)
  165. else:
  166. assert False, "unhandled option"
  167. # 3 because we have 3 color canals
  168. if K.image_data_format() == 'channels_first':
  169. input_shape = (3, img_width, img_height)
  170. else:
  171. input_shape = (img_width, img_height, 3)
  172. # configuration
  173. with open('config.json') as json_data:
  174. d = json.load(json_data)
  175. train_data_dir = d['train_data_dir']
  176. validation_data_dir = d['train_validation_dir']
  177. try:
  178. nb_train_samples = d[str(img_width)]['nb_train_samples']
  179. nb_validation_samples = d[str(img_width)]['nb_validation_samples']
  180. except:
  181. print("--img parameter missing of invalid (--image_width xx --img_height xx)")
  182. sys.exit(2)
  183. # load of model
  184. model = generate_model()
  185. model.summary()
  186. if(directory):
  187. print('Your model information will be saved into %s...' % directory)
  188. history = model.fit_generator(
  189. load_train_data(),
  190. steps_per_epoch=nb_train_samples // batch_size,
  191. epochs=epochs,
  192. validation_data=load_validation_data(),
  193. validation_steps=nb_validation_samples // batch_size)
  194. # if user needs output files
  195. if(filename):
  196. # update filename by folder
  197. if(directory):
  198. # create folder if necessary
  199. if not os.path.exists(directory):
  200. os.makedirs(directory)
  201. filename = directory + "/" + filename
  202. # save plot file history
  203. plot_info.save(history, filename)
  204. plot_model(model, to_file=str(('%s.png' % filename)), show_shapes=True)
  205. model.save_weights(str('%s.h5' % filename))
  206. if __name__ == "__main__":
  207. main()