classification_cnn_keras_svd.py 7.1 KB

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