classification_cnn_keras_svd_img.py 8.3 KB

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