classification_cnn_keras.py 6.6 KB

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