classification_cnn_keras_cross_validation.py 6.9 KB

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