classification_cnn_keras.py 6.2 KB

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