text_plain_output_1.png
from keras import layers

from keras.applications import DenseNet121

from keras.callbacks import Callback, ModelCheckpoint

from keras.models import Sequential

from keras.optimizers import Adam

from keras.preprocessing.image import ImageDataGenerator

from sklearn.metrics import cohen_kappa_score, accuracy_score

BATCH_SIZE = 32
def create_datagen():
    return ImageDataGenerator(zoom_range=0.15, fill_mode='constant', cval=0.0, horizontal_flip=True, vertical_flip=True)

class Metrics(Callback):
    def on_train_begin(self, logs={}):
        self.val_kappas = []
    def on_epoch_end(self, epoch, logs={}):
        X_val, y_val = self.validation_data[:2]
        y_val = y_val.sum(axis=1) - 1
        y_pred = self.model.predict(X_val) > 0.5
        y_pred = y_pred.astype(int).sum(axis=1) - 1
        _val_kappa = cohen_kappa_score(y_val, y_pred, weights='quadratic')
        self.val_kappas.append(_val_kappa)
        if _val_kappa == max(self.val_kappas):
            self.model.save('model.h5')
        return

densenet = DenseNet121(weights='imagenet', include_top=False, input_shape=(224, 224, 3))

def build_model():
    model = Sequential()
    model.add(densenet)
    model.add(layers.GlobalAveragePooling2D())
    model.add(layers.Dropout(0.5))
    model.add(layers.Dense(10, activation='sigmoid'))
    model.compile(loss='binary_crossentropy', optimizer=Adam(lr=5e-05), metrics=['accuracy'])
    return model

model = build_model()
model.summary()

kappa_metrics = Metrics()
history = model.fit_generator(data_generator, steps_per_epoch=x_train.shape[0] / BATCH_SIZE, epochs=15, validation_data=(x_val, y_val), callbacks=[kappa_metrics])