classification_cnn_keras.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. from keras.preprocessing.image import ImageDataGenerator
  28. from keras.models import Sequential
  29. from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
  30. from keras.layers import Activation, Dropout, Flatten, Dense
  31. from keras import backend as K
  32. from keras.utils import plot_model
  33. from modules.model_helper import plot_info
  34. # dimensions of our images.
  35. img_width, img_height = 100, 100
  36. train_data_dir = 'data/train'
  37. validation_data_dir = 'data/validation'
  38. nb_train_samples = 7200
  39. nb_validation_samples = 3600
  40. epochs = 50
  41. batch_size = 30
  42. if K.image_data_format() == 'channels_first':
  43. input_shape = (3, img_width, img_height)
  44. else:
  45. input_shape = (img_width, img_height, 3)
  46. '''
  47. Method which returns model to train
  48. @return : DirectoryIterator
  49. '''
  50. def generate_model():
  51. model = Sequential()
  52. model.add(Conv2D(60, (2, 2), input_shape=input_shape))
  53. model.add(Activation('relu'))
  54. model.add(MaxPooling2D(pool_size=(2, 2)))
  55. model.add(Conv2D(40, (2, 2)))
  56. model.add(Activation('relu'))
  57. model.add(MaxPooling2D(pool_size=(2, 2)))
  58. model.add(Conv2D(20, (2, 2)))
  59. model.add(Activation('relu'))
  60. model.add(MaxPooling2D(pool_size=(2, 2)))
  61. model.add(Conv2D(10, (2, 2)))
  62. model.add(Activation('relu'))
  63. model.add(MaxPooling2D(pool_size=(2, 2)))
  64. model.add(Flatten())
  65. model.add(Dense(60))
  66. model.add(Activation('relu'))
  67. model.add(Dropout(0.4))
  68. model.add(Dense(30))
  69. model.add(Activation('relu'))
  70. model.add(Dropout(0.2))
  71. model.add(Dense(1))
  72. model.add(Activation('sigmoid'))
  73. model.compile(loss='binary_crossentropy',
  74. optimizer='rmsprop',
  75. metrics=['accuracy'])
  76. return model
  77. '''
  78. Method which loads train data
  79. @return : DirectoryIterator
  80. '''
  81. def load_train_data():
  82. # this is the augmentation configuration we will use for training
  83. train_datagen = ImageDataGenerator(
  84. rescale=1. / 255,
  85. shear_range=0.2,
  86. zoom_range=0.2,
  87. horizontal_flip=True)
  88. train_generator = train_datagen.flow_from_directory(
  89. train_data_dir,
  90. target_size=(img_width, img_height),
  91. batch_size=batch_size,
  92. class_mode='binary')
  93. return train_generator
  94. '''
  95. Method which loads validation data
  96. @return : DirectoryIterator
  97. '''
  98. def load_validation_data():
  99. # this is the augmentation configuration we will use for testing:
  100. # only rescaling
  101. test_datagen = ImageDataGenerator(rescale=1. / 255)
  102. validation_generator = test_datagen.flow_from_directory(
  103. validation_data_dir,
  104. target_size=(img_width, img_height),
  105. batch_size=batch_size,
  106. class_mode='binary')
  107. return validation_generator
  108. def main():
  109. global batch_size
  110. global epochs
  111. if len(sys.argv) <= 1:
  112. print('No output file defined...')
  113. print('classification_cnn_keras_svd.py --output xxxxx')
  114. sys.exit(2)
  115. try:
  116. opts, args = getopt.getopt(sys.argv[1:], "ho:b:e:d", ["help", "directory=", "output=", "batch_size=", "epochs="])
  117. except getopt.GetoptError:
  118. # print help information and exit:
  119. print('classification_cnn_keras_svd.py --output xxxxx')
  120. sys.exit(2)
  121. for o, a in opts:
  122. if o == "-h":
  123. print('classification_cnn_keras_svd.py --output xxxxx')
  124. sys.exit()
  125. elif o in ("-o", "--output"):
  126. filename = a
  127. elif o in ("-b", "--batch_size"):
  128. batch_size = int(a)
  129. elif o in ("-e", "--epochs"):
  130. epochs = int(a)
  131. elif o in ("-d", "--directory"):
  132. directory = a
  133. else:
  134. assert False, "unhandled option"
  135. # load of model
  136. model = generate_model()
  137. model.summary()
  138. if(directory):
  139. print('Your model information will be saved into %s...' % directory)
  140. history = model.fit_generator(
  141. load_train_data(),
  142. steps_per_epoch=nb_train_samples // batch_size,
  143. epochs=epochs,
  144. validation_data=load_validation_data(),
  145. validation_steps=nb_validation_samples // batch_size)
  146. # if user needs output files
  147. if(filename):
  148. # update filename by folder
  149. if(directory):
  150. # create folder if necessary
  151. if not os.path.exists(directory):
  152. os.makedirs(directory)
  153. filename = directory + "/" + filename
  154. # save plot file history
  155. plot_info.save(history, filename)
  156. plot_model(model, to_file=str(('%s.png' % filename)))
  157. model.save_weights(str('%s.h5' % filename))
  158. if __name__ == "__main__":
  159. main()