classification_cnn_keras_svd_img.py 8.1 KB

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