cnn_keras.py 4.63 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
"""
    Generic classifier with multiple models
    Models -> (Xception, VGG16, VGG19, ResNet50, InceptionV3, MobileNet)
    Name: cnn_keras.py
    Author: Gabriel Kirsten Menezes (gabriel.kirsten@hotmail.com)

"""

import time
import os
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.models import Model
from keras.layers import Dropout, Flatten, Dense
from keras.callbacks import ModelCheckpoint
from sklearn.metrics import confusion_matrix

from classifier import Classifier

from collections import OrderedDict

from util.config import Config
from util.file_utils import File
from util.utils import TimeUtils

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # Suppress warnings
START_TIME = time.time()

# =========================================================
# Constants
# =========================================================

IMG_WIDTH, IMG_HEIGHT = 256, 256
TRAIN_DATA_DIR = "../data/train"
VALIDATION_DATA_DIR = "../data/validation"
BATCH_SIZE = 16
EPOCHS = 50
CLASS_NAMES = ['ferrugemAsiatica', 'folhaSaudavel',
               'fundo', 'manchaAlvo', 'mildio', 'oidio']

class CNNKeras(Classifier):

    def __init__(self):
        model = applications.VGG16(
            weights="imagenet", include_top=False, input_shape=(IMG_WIDTH, IMG_HEIGHT, 3))

        for layer in model.layers:
            layer.trainable = True

        # Adding custom Layers
        new_custom_layers = model.output
        new_custom_layers = Flatten()(new_custom_layers)
        new_custom_layers = Dense(1024, activation="relu")(new_custom_layers)
        new_custom_layers = Dropout(0.5)(new_custom_layers)
        new_custom_layers = Dense(1024, activation="relu")(new_custom_layers)
        predictions = Dense(6, activation="softmax")(new_custom_layers)

        # creating the final model
        model_final = Model(inputs=model.input, outputs=predictions)

        # compile the model
        model_final.compile(loss="categorical_crossentropy",
                            optimizer=optimizers.SGD(lr=0.0001, momentum=0.9),
                            metrics=["accuracy"])

    def get_config(self):
        """Return configuration of classifier. 
        
        Returns
        -------
        config : OrderedDict
            Current configs of classifier.
        """
        pass

    def set_config(self, configs):
        """Update configuration of classifier. 
        
        Parameters
        ----------
        configs : OrderedDict
            New configs of classifier.
        """
        pass

    def get_summary_config(self):
        """Return fomatted summary of configuration. 
        
        Returns
        -------
        summary : string
            Formatted string with summary of configuration.
        """
        pass 

    def classify(self, dataset, test_dir, test_data):
        pass

    def train(self, model_final):
        
        # Initiate the train and test generators with data Augumentation
        train_datagen = ImageDataGenerator(
            rescale=1. / 255,
            horizontal_flip=True,
            fill_mode="nearest",
            zoom_range=0.3,
            width_shift_range=0.3,
            height_shift_range=0.3,
            rotation_range=30)

        train_generator = train_datagen.flow_from_directory(
            TRAIN_DATA_DIR,
            target_size=(IMG_HEIGHT, IMG_WIDTH),
            batch_size=BATCH_SIZE,
            shuffle=True,
            class_mode="categorical")

        test_datagen = ImageDataGenerator(
            rescale=1. / 255,
            horizontal_flip=True,
            fill_mode="nearest",
            zoom_range=0.3,
            width_shift_range=0.3,
            height_shift_range=0.3,
            rotation_range=30)

        validation_generator = test_datagen.flow_from_directory(
            VALIDATION_DATA_DIR,
            target_size=(IMG_HEIGHT, IMG_WIDTH),
            batch_size=BATCH_SIZE,
            shuffle=True,
            class_mode="categorical")

        # Save the model according to the conditions
        checkpoint = ModelCheckpoint("../models_checkpoints/" + file_name + ".h5", monitor='val_acc',
                                    verbose=1, save_best_only=True, save_weights_only=False,
                                    mode='auto', period=1)

        # Train the model
        model_final.fit_generator(
            train_generator,
            steps_per_epoch=train_generator.samples // BATCH_SIZE,
            epochs=EPOCHS,
            callbacks=[checkpoint],
            validation_data=validation_generator,
            validation_steps=validation_generator.samples // BATCH_SIZE)