exact repeat of Classifier weights.082-0.0924.hdf5 loss: 0.1184 - acc: 0.9887 - val_loss: 0.0924 - val_acc: 0.9788 valid loss: 0.0936035634052 valid fish loss: 0.213601306756 class ALB 0.202928 BET 0.423660 DOL 0.661419 LAG 0.002563 NoF 0.058878 OTHER 0.201856 SHARK 0.005478 YFT 0.178296 Name: logloss, dtype: float64 train loss: 0.0401916851351 train fish loss: 0.0417360296024 class ALB 0.060663 BET 0.027422 DOL 0.001574 LAG 0.000586 NoF 0.039745 OTHER 0.012223 SHARK 0.001352 YFT 0.021237 Name: logloss, dtype: float64

In [1]:
import os, random, glob, pickle, collections, math, json, time
import numpy as np
import pandas as pd
from __future__ import division
from __future__ import print_function
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
from sklearn.preprocessing import LabelEncoder

import matplotlib.pyplot as plt
%matplotlib inline 

from keras.models import Sequential, Model, load_model
from keras.layers import GlobalAveragePooling2D, Flatten, Dropout, Dense, LeakyReLU
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, TensorBoard
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
from keras.preprocessing import image
from keras import backend as K
K.set_image_dim_ordering('tf')


Using TensorFlow backend.

In [2]:
TRAIN_DIR = '../data/train/'
TEST_DIR = '../RFCN/JPEGImages/'
TRAIN_CROP_DIR = '../data/train_crop/'
TEST_CROP_DIR = '../data/test_stg1_crop/'
RFCN_MODEL = 'resnet101_rfcn_ohem_iter_30000'
CROP_MODEL = 'resnet50_FT38_Classifier_Rep4'
if not os.path.exists('./' + CROP_MODEL):
    os.mkdir('./' + CROP_MODEL)
CHECKPOINT_DIR = './' + CROP_MODEL + '/checkpoint/'
if not os.path.exists(CHECKPOINT_DIR):
    os.mkdir(CHECKPOINT_DIR)
LOG_DIR = './' + CROP_MODEL + '/log/'
if not os.path.exists(LOG_DIR):
    os.mkdir(LOG_DIR)
OUTPUT_DIR = './' + CROP_MODEL + '/output/'
if not os.path.exists(OUTPUT_DIR):
    os.mkdir(OUTPUT_DIR)
FISH_CLASSES = ['NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']
# CROP_CLASSES=FISH_CLASSES[:]
# CROP_CLASSES.remove('NoF')
CONF_THRESH = 0.8
ROWS = 224
COLS = 224
BATCHSIZE = 128
LEARNINGRATE = 1e-4
def featurewise_center(x):
    mean = np.mean(x, axis=0, keepdims=True)
#     mean = np.mean(mean, axis=(1,2), keepdims=True)
    x_centered = x - mean
    return x_centered

def mean(x):
    mean = np.mean(x, axis=0)
    mean = np.mean(mean, axis=(0,1))
    return mean

def load_img(path, bbox, target_size=None):
    img = Image.open(path)
#     img = img.convert('RGB')
    cropped = img.crop((bbox[0],bbox[1],bbox[2],bbox[3]))
    width_cropped, height_cropped = cropped.size
    if height_cropped > width_cropped: cropped = cropped.transpose(method=2)
    image_name = 'temp_{:f}.jpg'.format(time.time())
    cropped.save(image_name)
    cropped = Image.open(image_name)   
    if target_size:
        cropped = cropped.resize((target_size[1], target_size[0]), Image.BILINEAR)
    return cropped

def preprocess_input(x, mean):
    #resnet50 image preprocessing
#     'RGB'->'BGR'
#     x = x[:, :, ::-1]
#     x /= 255.
    x[:, :, 0] -= mean[0]
    x[:, :, 1] -= mean[1]
    x[:, :, 2] -= mean[2]
    return x

def get_best_model(checkpoint_dir = CHECKPOINT_DIR):
    files = glob.glob(checkpoint_dir+'*')
    val_losses = [float(f.split('-')[-1][:-5]) for f in files]
    index = val_losses.index(min(val_losses))
    print('Loading model from checkpoint file ' + files[index])
    model = load_model(files[index])
    model_name = files[index].split('/')[-1]
    print('Loading model Done!')
    return (model, model_name)

In [3]:
# GTbbox_df = ['image_file','crop_index','crop_class','xmin',''ymin','xmax','ymax','split']

file_name = 'GTbbox_df.pickle'
if os.path.exists(OUTPUT_DIR+file_name):
    print ('Loading from file '+file_name)
    GTbbox_df = pd.read_pickle(OUTPUT_DIR+file_name)
else:
    print ('Generating file '+file_name)       
    GTbbox_df = pd.DataFrame(columns=['image_file','crop_index','crop_class','xmin','ymin','xmax','ymax'])  

    crop_classes=FISH_CLASSES[:]
    crop_classes.remove('NoF')
    
    for c in crop_classes:
        print(c)
        j = json.load(open('../data/BBannotations/{}.json'.format(c), 'r'))
        for l in j: 
            filename = l["filename"]
            head, image_file = os.path.split(filename)
            basename, file_extension = os.path.splitext(image_file) 
            image = Image.open(TEST_DIR+'/'+image_file)
            width_image, height_image = image.size
            for i in range(len(l["annotations"])):
                a = l["annotations"][i]
                xmin = (a["x"])
                ymin = (a["y"])
                width = (a["width"])
                height = (a["height"])
                xmax = xmin + width
                ymax = ymin + height
                assert max(xmin,0)<min(xmax,width_image)
                assert max(ymin,0)<min(ymax,height_image)
                GTbbox_df.loc[len(GTbbox_df)]=[image_file,i,a["class"],max(xmin,0),max(ymin,0),min(xmax,width_image),min(ymax,height_image)]
                if a["class"] != c: print(GTbbox_df.tail(1))  
        
        
    num_NoF = GTbbox_df.shape[0]*3
    RFCN_MODEL = 'resnet101_rfcn_ohem_iter_30000'
    with open('../data/RFCN_detections/detections_full_AGNOSTICnms_'+RFCN_MODEL+'.pkl','rb') as f:
        detections_full_AGNOSTICnms = pickle.load(f) 
    train_detections_full_AGNOSTICnms = detections_full_AGNOSTICnms[1000:]
#     with open("../RFCN/ImageSets/Main/test.txt","r") as f:
#         test_files = f.readlines()
#     train_files = test_files[1000:]
    with open("../RFCN/ImageSets/Main/train_test.txt","r") as f:
        train_files = f.readlines()
    num_NoF_perIm = int(math.ceil(num_NoF / len(train_detections_full_AGNOSTICnms)))

    for im in range(len(train_files)):
        image_file = train_files[im][:9]+'.jpg'
        image = Image.open(TEST_DIR+image_file)
#         width_image, height_image = image.size
        detects_im = train_detections_full_AGNOSTICnms[im]
        detects_im = detects_im[np.where(detects_im[:,4] >= 0.999)]
        np.random.seed(1986)
        bboxes = detects_im[np.random.choice(detects_im.shape[0], num_NoF_perIm, replace=False), :]
        for j in range(bboxes.shape[0]):    
            bbox = bboxes[j]
            xmin = bbox[0]
            ymin = bbox[1]
            xmax = bbox[2]
            ymax = bbox[3]
#             assert max(xmin,0)<min(xmax,width_image)
#             assert max(ymin,0)<min(ymax,height_image)
            GTbbox_df.loc[len(GTbbox_df)]=[image_file,j,'NoF',xmin,ymin,xmax,ymax]

    test_size = GTbbox_df.shape[0]-int(math.ceil(GTbbox_df.shape[0]*0.8/128)*128)
    train_ind, valid_ind = train_test_split(range(GTbbox_df.shape[0]), test_size=test_size, random_state=1986, stratify=GTbbox_df['crop_class'])
    GTbbox_df['split'] = ['train' if i in train_ind else 'valid' for i in range(GTbbox_df.shape[0])]
    GTbbox_df.to_pickle(OUTPUT_DIR+file_name)


Loading from file GTbbox_df.pickle

In [4]:
#Load data

def data_from_df(df):
    X = np.ndarray((df.shape[0], ROWS, COLS, 3), dtype=np.uint8)
    y = np.zeros((df.shape[0], len(FISH_CLASSES)), dtype=K.floatx())
    i = 0
    for index,row in df.iterrows():
        image_file = row['image_file']
        fish = row['crop_class']
        bbox = [row['xmin'],row['ymin'],row['xmax'],row['ymax']]
        cropped = load_img(TEST_DIR+image_file,bbox,target_size=(ROWS,COLS))
        X[i] = np.asarray(cropped)
        y[i,FISH_CLASSES.index(fish)] = 1
        i += 1
    return (X, y)

def data_load(name):
    file_name = 'data_'+name+'_{}_{}.pickle'.format(ROWS, COLS)
    if os.path.exists(OUTPUT_DIR+file_name):
        print ('Loading from file '+file_name)
        with open(OUTPUT_DIR+file_name, 'rb') as f:
            data = pickle.load(f)
        X = data['X']
        y = data['y']
    else:
        print ('Generating file '+file_name)
        
        if name=='train' or name=='valid': 
            df = GTbbox_df[GTbbox_df['split']==name]
        elif name=='all':
            df = GTbbox_df
        else:
            print('Invalid name '+name)
    
        X, y = data_from_df(df)

        data = {'X': X,'y': y}
        with open(OUTPUT_DIR+file_name, 'wb') as f:
            pickle.dump(data, f)
    return (X, y)
X_train, y_train = data_load('train')
X_valid, y_valid = data_load('valid')
       
print('Loading data done.')
print('train sample', X_train.shape[0])
print('valid sample', X_valid.shape[0])
X_train = X_train.astype(np.float32)
X_valid = X_valid.astype(np.float32)
print('Convert to float32 done.')
X_train /= 255.
X_valid /= 255.
print('Rescale by 255 done.')
X_train_centered = featurewise_center(X_train)
print('mean of X_train is', mean(X_train))
X_valid_centered = featurewise_center(X_valid)
print('mean of X_valid is', mean(X_valid))
print('Featurewise centered done.')


Loading from file data_train_224_224.pickle
Loading from file data_valid_224_224.pickle
Loading data done.
train sample 15616
valid sample 3863
Convert to float32 done.
Rescale by 255 done.
mean of X_train is [ 0.37469816  0.41190609  0.38363659]
mean of X_valid is [ 0.37204069  0.41050309  0.38143238]
Featurewise centered done.

In [5]:
# #class weight = n_samples / (n_classes * np.bincount(y))
# class_weight_fish = dict(GTbbox_df.groupby('crop_class').size())
# class_weight = {}
# n_samples = GTbbox_df.shape[0]
# for key,value in class_weight_fish.items():
#         class_weight[CROP_CLASSES.index(key)] = n_samples / (len(CROP_CLASSES)*value)
# class_weight

class_weight_fish = dict(GTbbox_df.groupby('crop_class').size())
class_weight = {}
ref = max(class_weight_fish.values())
for key,value in class_weight_fish.items():
    class_weight[FISH_CLASSES.index(key)] = ref/value
class_weight


Out[5]:
{0: 1.0,
 1: 6.0119379228014322,
 2: 49.372549019607845,
 3: 119.9047619047619,
 4: 143.88571428571427,
 5: 45.369369369369366,
 6: 79.936507936507937,
 7: 18.908635794743429}

In [6]:
#data augmentation

train_datagen = ImageDataGenerator(
    rotation_range=180,
    shear_range=0.2,
    zoom_range=0.1,
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True,
    vertical_flip=True)
train_generator = train_datagen.flow(X_train_centered, y_train, batch_size=BATCHSIZE, shuffle=True, seed=None)
assert X_train_centered.shape[0]%BATCHSIZE==0
steps_per_epoch = int(X_train_centered.shape[0]/BATCHSIZE)

In [7]:
#callbacks

early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1, mode='auto')        

model_checkpoint = ModelCheckpoint(filepath=CHECKPOINT_DIR+'weights.{epoch:03d}-{val_loss:.4f}.hdf5', monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='auto')
        
learningrate_schedule = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1, mode='auto', epsilon=0.001, cooldown=0, min_lr=0)

tensorboard = TensorBoard(log_dir=LOG_DIR, histogram_freq=0, write_graph=False, write_images=True)

In [ ]:
#Resnet50
#top layer training

from keras.applications.resnet50 import ResNet50

base_model = ResNet50(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
# x = Flatten()(x)
# x = Dense(256)(x)
# x = LeakyReLU(alpha=0.33)(x)
# x = Dropout(0.5)(x)
predictions = Dense(len(FISH_CLASSES), kernel_initializer='glorot_normal', activation='softmax')(x)

model = Model(inputs=base_model.input, outputs=predictions)

# first: train only the top layers (which were randomly initialized)
for layer in base_model.layers:
    layer.trainable = False

# compile the model (should be done *after* setting layers to non-trainable)
optimizer = Adam(lr=LEARNINGRATE)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

# train the model on the new data for a few epochs
model.fit_generator(train_generator, steps_per_epoch=steps_per_epoch, epochs=30, verbose=1, 
                    callbacks=[early_stopping, model_checkpoint, learningrate_schedule, tensorboard], 
                    validation_data=(X_valid_centered,y_valid), class_weight=class_weight, 
                    workers=3, pickle_safe=True, initial_epoch=0)


Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
Epoch 1/30
121/122 [============================>.] - ETA: 1s - loss: 13.0508 - acc: 0.2874   Epoch 00000: val_loss improved from inf to 1.22633, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.000-1.2263.hdf5
122/122 [==============================] - 256s - loss: 13.0274 - acc: 0.2888 - val_loss: 1.2263 - val_acc: 0.7756
Epoch 2/30
121/122 [============================>.] - ETA: 1s - loss: 10.1605 - acc: 0.5475  Epoch 00001: val_loss improved from 1.22633 to 1.06892, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.001-1.0689.hdf5
122/122 [==============================] - 217s - loss: 10.1649 - acc: 0.5481 - val_loss: 1.0689 - val_acc: 0.7756
Epoch 3/30
121/122 [============================>.] - ETA: 1s - loss: 8.8884 - acc: 0.6486  Epoch 00002: val_loss did not improve
122/122 [==============================] - 216s - loss: 8.8638 - acc: 0.6487 - val_loss: 1.1177 - val_acc: 0.7756
Epoch 4/30
121/122 [============================>.] - ETA: 1s - loss: 7.9009 - acc: 0.6828  Epoch 00003: val_loss did not improve
122/122 [==============================] - 217s - loss: 7.8801 - acc: 0.6828 - val_loss: 1.1923 - val_acc: 0.7756
Epoch 5/30
121/122 [============================>.] - ETA: 1s - loss: 7.4798 - acc: 0.7029  Epoch 00004: val_loss did not improve
122/122 [==============================] - 216s - loss: 7.4994 - acc: 0.7034 - val_loss: 1.2286 - val_acc: 0.7756
Epoch 6/30
121/122 [============================>.] - ETA: 1s - loss: 6.8463 - acc: 0.7193  Epoch 00005: val_loss did not improve
122/122 [==============================] - 216s - loss: 6.9059 - acc: 0.7189 - val_loss: 1.0767 - val_acc: 0.7763
Epoch 7/30
121/122 [============================>.] - ETA: 1s - loss: 6.6616 - acc: 0.7261  Epoch 00006: val_loss improved from 1.06892 to 0.88085, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.006-0.8808.hdf5
122/122 [==============================] - 217s - loss: 6.6645 - acc: 0.7262 - val_loss: 0.8808 - val_acc: 0.7771
Epoch 8/30
121/122 [============================>.] - ETA: 1s - loss: 6.2960 - acc: 0.7375  Epoch 00007: val_loss improved from 0.88085 to 0.67305, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.007-0.6730.hdf5
122/122 [==============================] - 217s - loss: 6.3052 - acc: 0.7380 - val_loss: 0.6730 - val_acc: 0.7888
Epoch 9/30
121/122 [============================>.] - ETA: 1s - loss: 5.5945 - acc: 0.7707  Epoch 00008: val_loss improved from 0.67305 to 0.61448, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.008-0.6145.hdf5
122/122 [==============================] - 217s - loss: 5.5800 - acc: 0.7700 - val_loss: 0.6145 - val_acc: 0.8027
Epoch 10/30
121/122 [============================>.] - ETA: 1s - loss: 5.8458 - acc: 0.7696  Epoch 00009: val_loss improved from 0.61448 to 0.59234, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.009-0.5923.hdf5
122/122 [==============================] - 216s - loss: 5.8284 - acc: 0.7700 - val_loss: 0.5923 - val_acc: 0.8110
Epoch 11/30
121/122 [============================>.] - ETA: 1s - loss: 5.4834 - acc: 0.7663  Epoch 00010: val_loss did not improve
122/122 [==============================] - 216s - loss: 5.4930 - acc: 0.7665 - val_loss: 0.6238 - val_acc: 0.7921
Epoch 12/30
121/122 [============================>.] - ETA: 1s - loss: 5.3013 - acc: 0.7742  Epoch 00011: val_loss did not improve
122/122 [==============================] - 217s - loss: 5.3103 - acc: 0.7743 - val_loss: 0.6171 - val_acc: 0.8051
Epoch 13/30
121/122 [============================>.] - ETA: 1s - loss: 5.0349 - acc: 0.7767  Epoch 00012: val_loss did not improve
122/122 [==============================] - 217s - loss: 5.0791 - acc: 0.7769 - val_loss: 0.6083 - val_acc: 0.8017
Epoch 14/30
121/122 [============================>.] - ETA: 1s - loss: 5.1889 - acc: 0.7803  Epoch 00013: val_loss improved from 0.59234 to 0.57124, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.013-0.5712.hdf5
122/122 [==============================] - 217s - loss: 5.1903 - acc: 0.7805 - val_loss: 0.5712 - val_acc: 0.8185
Epoch 15/30
121/122 [============================>.] - ETA: 1s - loss: 5.0714 - acc: 0.7851  Epoch 00014: val_loss did not improve
122/122 [==============================] - 217s - loss: 5.0949 - acc: 0.7853 - val_loss: 0.5951 - val_acc: 0.8090
Epoch 16/30
121/122 [============================>.] - ETA: 1s - loss: 4.8736 - acc: 0.7817  Epoch 00015: val_loss did not improve
122/122 [==============================] - 217s - loss: 4.8603 - acc: 0.7812 - val_loss: 0.6252 - val_acc: 0.7970
Epoch 17/30
121/122 [============================>.] - ETA: 1s - loss: 4.6675 - acc: 0.7864  Epoch 00016: val_loss improved from 0.57124 to 0.53731, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.016-0.5373.hdf5
122/122 [==============================] - 217s - loss: 4.6642 - acc: 0.7867 - val_loss: 0.5373 - val_acc: 0.8328
Epoch 18/30
121/122 [============================>.] - ETA: 1s - loss: 4.7035 - acc: 0.7995  Epoch 00017: val_loss did not improve
122/122 [==============================] - 216s - loss: 4.7086 - acc: 0.7991 - val_loss: 0.5688 - val_acc: 0.8092
Epoch 19/30
121/122 [============================>.] - ETA: 1s - loss: 4.5199 - acc: 0.7931  Epoch 00018: val_loss improved from 0.53731 to 0.49011, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.018-0.4901.hdf5
122/122 [==============================] - 217s - loss: 4.5152 - acc: 0.7928 - val_loss: 0.4901 - val_acc: 0.8434
Epoch 20/30
121/122 [============================>.] - ETA: 1s - loss: 4.5809 - acc: 0.7987  Epoch 00019: val_loss improved from 0.49011 to 0.48629, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.019-0.4863.hdf5
122/122 [==============================] - 217s - loss: 4.5732 - acc: 0.7994 - val_loss: 0.4863 - val_acc: 0.8452
Epoch 21/30
121/122 [============================>.] - ETA: 1s - loss: 4.3928 - acc: 0.8055  Epoch 00020: val_loss did not improve
122/122 [==============================] - 216s - loss: 4.3915 - acc: 0.8053 - val_loss: 0.5240 - val_acc: 0.8330
Epoch 22/30
121/122 [============================>.] - ETA: 1s - loss: 4.1466 - acc: 0.8069  Epoch 00021: val_loss did not improve
122/122 [==============================] - 217s - loss: 4.1407 - acc: 0.8071 - val_loss: 0.4883 - val_acc: 0.8382
Epoch 23/30
121/122 [============================>.] - ETA: 1s - loss: 4.2389 - acc: 0.8178  Epoch 00022: val_loss improved from 0.48629 to 0.48100, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.022-0.4810.hdf5
122/122 [==============================] - 217s - loss: 4.2261 - acc: 0.8178 - val_loss: 0.4810 - val_acc: 0.8478
Epoch 24/30
121/122 [============================>.] - ETA: 1s - loss: 4.4105 - acc: 0.8136  Epoch 00023: val_loss did not improve
122/122 [==============================] - 216s - loss: 4.4248 - acc: 0.8137 - val_loss: 0.4941 - val_acc: 0.8418
Epoch 25/30
121/122 [============================>.] - ETA: 1s - loss: 4.1065 - acc: 0.8130  Epoch 00024: val_loss did not improve
122/122 [==============================] - 216s - loss: 4.1073 - acc: 0.8128 - val_loss: 0.4889 - val_acc: 0.8418
Epoch 26/30
121/122 [============================>.] - ETA: 1s - loss: 4.0889 - acc: 0.8115  Epoch 00025: val_loss improved from 0.48100 to 0.47063, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.025-0.4706.hdf5
122/122 [==============================] - 217s - loss: 4.0863 - acc: 0.8113 - val_loss: 0.4706 - val_acc: 0.8468
Epoch 27/30
121/122 [============================>.] - ETA: 1s - loss: 4.1541 - acc: 0.8167  Epoch 00026: val_loss improved from 0.47063 to 0.45157, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.026-0.4516.hdf5
122/122 [==============================] - 217s - loss: 4.1421 - acc: 0.8167 - val_loss: 0.4516 - val_acc: 0.8548
Epoch 28/30
121/122 [============================>.] - ETA: 1s - loss: 3.9463 - acc: 0.8184  Epoch 00027: val_loss did not improve
122/122 [==============================] - 217s - loss: 3.9430 - acc: 0.8185 - val_loss: 0.4669 - val_acc: 0.8514
Epoch 29/30
121/122 [============================>.] - ETA: 1s - loss: 3.8361 - acc: 0.8243  Epoch 00028: val_loss did not improve
122/122 [==============================] - 216s - loss: 3.8502 - acc: 0.8241 - val_loss: 0.4787 - val_acc: 0.8475
Epoch 30/30
 17/122 [===>..........................] - ETA: 150s - loss: 3.9536 - acc: 0.8139

In [8]:
### Resnet50
# fine tuning
# 164 conv5c+top
# 142 conv5+top
# 80 conv4+conv5+top
# 38 conv3+conv4+conv5+top
start_layer = 38

model, model_name = get_best_model()
# print('Loading model from weights.004-0.0565.hdf5')
# model = load_model(CHECHPOINT_DIR+'weights.004-0.0565.hdf5')

for layer in model.layers[:start_layer]:
   layer.trainable = False
for layer in model.layers[start_layer:]:
   layer.trainable = True

# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
optimizer = Adam(lr=1e-5)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

model.fit_generator(train_generator, steps_per_epoch=steps_per_epoch, epochs=300, verbose=1, 
                    callbacks=[early_stopping, model_checkpoint, learningrate_schedule, tensorboard], 
                    validation_data=(X_valid_centered,y_valid), class_weight=class_weight, 
                    workers=3, pickle_safe=True, initial_epoch=27)


Loading model from checkpoint file ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.026-0.4516.hdf5
Loading model Done!
Epoch 28/300
121/122 [============================>.] - ETA: 2s - loss: 3.5502 - acc: 0.8343   Epoch 00027: val_loss improved from inf to 0.39096, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.027-0.3910.hdf5
122/122 [==============================] - 410s - loss: 3.5515 - acc: 0.8341 - val_loss: 0.3910 - val_acc: 0.8778
Epoch 29/300
121/122 [============================>.] - ETA: 2s - loss: 3.0541 - acc: 0.8549  Epoch 00028: val_loss improved from 0.39096 to 0.37518, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.028-0.3752.hdf5
122/122 [==============================] - 384s - loss: 3.0535 - acc: 0.8547 - val_loss: 0.3752 - val_acc: 0.8825
Epoch 30/300
121/122 [============================>.] - ETA: 2s - loss: 2.6174 - acc: 0.8709  Epoch 00029: val_loss improved from 0.37518 to 0.30905, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.029-0.3090.hdf5
122/122 [==============================] - 384s - loss: 2.6186 - acc: 0.8710 - val_loss: 0.3090 - val_acc: 0.9060
Epoch 31/300
121/122 [============================>.] - ETA: 2s - loss: 2.1383 - acc: 0.8869  Epoch 00030: val_loss improved from 0.30905 to 0.28281, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.030-0.2828.hdf5
122/122 [==============================] - 384s - loss: 2.1323 - acc: 0.8870 - val_loss: 0.2828 - val_acc: 0.9159
Epoch 32/300
121/122 [============================>.] - ETA: 2s - loss: 1.9832 - acc: 0.9013  Epoch 00031: val_loss improved from 0.28281 to 0.27505, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.031-0.2750.hdf5
122/122 [==============================] - 384s - loss: 1.9914 - acc: 0.9014 - val_loss: 0.2750 - val_acc: 0.9182
Epoch 33/300
121/122 [============================>.] - ETA: 2s - loss: 1.7805 - acc: 0.9102  Epoch 00032: val_loss improved from 0.27505 to 0.24489, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.032-0.2449.hdf5
122/122 [==============================] - 384s - loss: 1.7759 - acc: 0.9102 - val_loss: 0.2449 - val_acc: 0.9267
Epoch 34/300
121/122 [============================>.] - ETA: 2s - loss: 1.4995 - acc: 0.9218  Epoch 00033: val_loss improved from 0.24489 to 0.22827, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.033-0.2283.hdf5
122/122 [==============================] - 384s - loss: 1.5045 - acc: 0.9219 - val_loss: 0.2283 - val_acc: 0.9345
Epoch 35/300
121/122 [============================>.] - ETA: 2s - loss: 1.4344 - acc: 0.9247  Epoch 00034: val_loss improved from 0.22827 to 0.21597, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.034-0.2160.hdf5
122/122 [==============================] - 384s - loss: 1.4355 - acc: 0.9247 - val_loss: 0.2160 - val_acc: 0.9361
Epoch 36/300
121/122 [============================>.] - ETA: 2s - loss: 1.1946 - acc: 0.9293  Epoch 00035: val_loss improved from 0.21597 to 0.21079, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.035-0.2108.hdf5
122/122 [==============================] - 385s - loss: 1.1946 - acc: 0.9292 - val_loss: 0.2108 - val_acc: 0.9399
Epoch 37/300
121/122 [============================>.] - ETA: 2s - loss: 1.1048 - acc: 0.9381  Epoch 00036: val_loss improved from 0.21079 to 0.20848, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.036-0.2085.hdf5
122/122 [==============================] - 384s - loss: 1.1031 - acc: 0.9382 - val_loss: 0.2085 - val_acc: 0.9394
Epoch 38/300
121/122 [============================>.] - ETA: 2s - loss: 1.0024 - acc: 0.9432  Epoch 00037: val_loss improved from 0.20848 to 0.18959, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.037-0.1896.hdf5
122/122 [==============================] - 384s - loss: 0.9992 - acc: 0.9435 - val_loss: 0.1896 - val_acc: 0.9443
Epoch 39/300
121/122 [============================>.] - ETA: 2s - loss: 0.9140 - acc: 0.9474  Epoch 00038: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.9110 - acc: 0.9476 - val_loss: 0.1962 - val_acc: 0.9438
Epoch 40/300
121/122 [============================>.] - ETA: 2s - loss: 0.8229 - acc: 0.9507  Epoch 00039: val_loss improved from 0.18959 to 0.17687, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.039-0.1769.hdf5
122/122 [==============================] - 384s - loss: 0.8209 - acc: 0.9506 - val_loss: 0.1769 - val_acc: 0.9511
Epoch 41/300
121/122 [============================>.] - ETA: 2s - loss: 0.7302 - acc: 0.9575  Epoch 00040: val_loss improved from 0.17687 to 0.16637, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.040-0.1664.hdf5
122/122 [==============================] - 385s - loss: 0.7307 - acc: 0.9574 - val_loss: 0.1664 - val_acc: 0.9500
Epoch 42/300
121/122 [============================>.] - ETA: 2s - loss: 0.7400 - acc: 0.9547  Epoch 00041: val_loss improved from 0.16637 to 0.15808, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.041-0.1581.hdf5
122/122 [==============================] - 384s - loss: 0.7383 - acc: 0.9545 - val_loss: 0.1581 - val_acc: 0.9544
Epoch 43/300
121/122 [============================>.] - ETA: 2s - loss: 0.6074 - acc: 0.9606  Epoch 00042: val_loss improved from 0.15808 to 0.14529, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.042-0.1453.hdf5
122/122 [==============================] - 385s - loss: 0.6054 - acc: 0.9604 - val_loss: 0.1453 - val_acc: 0.9604
Epoch 44/300
121/122 [============================>.] - ETA: 2s - loss: 0.5908 - acc: 0.9629  Epoch 00043: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.5887 - acc: 0.9629 - val_loss: 0.1557 - val_acc: 0.9568
Epoch 45/300
121/122 [============================>.] - ETA: 2s - loss: 0.5782 - acc: 0.9598  Epoch 00044: val_loss improved from 0.14529 to 0.13903, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.044-0.1390.hdf5
122/122 [==============================] - 384s - loss: 0.5792 - acc: 0.9598 - val_loss: 0.1390 - val_acc: 0.9645
Epoch 46/300
121/122 [============================>.] - ETA: 2s - loss: 0.5502 - acc: 0.9638  Epoch 00045: val_loss improved from 0.13903 to 0.13577, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.045-0.1358.hdf5
122/122 [==============================] - 384s - loss: 0.5479 - acc: 0.9638 - val_loss: 0.1358 - val_acc: 0.9676
Epoch 47/300
121/122 [============================>.] - ETA: 2s - loss: 0.4451 - acc: 0.9698  Epoch 00046: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.4452 - acc: 0.9699 - val_loss: 0.1388 - val_acc: 0.9632
Epoch 48/300
121/122 [============================>.] - ETA: 2s - loss: 0.4745 - acc: 0.9681  Epoch 00047: val_loss improved from 0.13577 to 0.13111, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.047-0.1311.hdf5
122/122 [==============================] - 385s - loss: 0.4756 - acc: 0.9679 - val_loss: 0.1311 - val_acc: 0.9674
Epoch 49/300
121/122 [============================>.] - ETA: 2s - loss: 0.3806 - acc: 0.9704  Epoch 00048: val_loss improved from 0.13111 to 0.12449, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.048-0.1245.hdf5
122/122 [==============================] - 384s - loss: 0.3834 - acc: 0.9702 - val_loss: 0.1245 - val_acc: 0.9669
Epoch 50/300
121/122 [============================>.] - ETA: 2s - loss: 0.4111 - acc: 0.9717  Epoch 00049: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.4115 - acc: 0.9718 - val_loss: 0.1291 - val_acc: 0.9666
Epoch 51/300
121/122 [============================>.] - ETA: 2s - loss: 0.3890 - acc: 0.9715  Epoch 00050: val_loss improved from 0.12449 to 0.12071, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.050-0.1207.hdf5
122/122 [==============================] - 384s - loss: 0.3874 - acc: 0.9716 - val_loss: 0.1207 - val_acc: 0.9663
Epoch 52/300
121/122 [============================>.] - ETA: 2s - loss: 0.3509 - acc: 0.9744  Epoch 00051: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.3516 - acc: 0.9744 - val_loss: 0.1245 - val_acc: 0.9679
Epoch 53/300
121/122 [============================>.] - ETA: 2s - loss: 0.3310 - acc: 0.9740  Epoch 00052: val_loss improved from 0.12071 to 0.10958, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.052-0.1096.hdf5
122/122 [==============================] - 385s - loss: 0.3302 - acc: 0.9743 - val_loss: 0.1096 - val_acc: 0.9707
Epoch 54/300
121/122 [============================>.] - ETA: 2s - loss: 0.2871 - acc: 0.9778  Epoch 00053: val_loss improved from 0.10958 to 0.10592, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.053-0.1059.hdf5
122/122 [==============================] - 384s - loss: 0.2861 - acc: 0.9779 - val_loss: 0.1059 - val_acc: 0.9726
Epoch 55/300
121/122 [============================>.] - ETA: 2s - loss: 0.2729 - acc: 0.9776  Epoch 00054: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.2727 - acc: 0.9776 - val_loss: 0.1078 - val_acc: 0.9726
Epoch 56/300
121/122 [============================>.] - ETA: 2s - loss: 0.2521 - acc: 0.9809  Epoch 00055: val_loss improved from 0.10592 to 0.10067, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.055-0.1007.hdf5
122/122 [==============================] - 385s - loss: 0.2524 - acc: 0.9809 - val_loss: 0.1007 - val_acc: 0.9746
Epoch 57/300
121/122 [============================>.] - ETA: 2s - loss: 0.2355 - acc: 0.9797  Epoch 00056: val_loss improved from 0.10067 to 0.09888, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.056-0.0989.hdf5
122/122 [==============================] - 384s - loss: 0.2351 - acc: 0.9796 - val_loss: 0.0989 - val_acc: 0.9736
Epoch 58/300
121/122 [============================>.] - ETA: 2s - loss: 0.2967 - acc: 0.9777  Epoch 00057: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.2962 - acc: 0.9775 - val_loss: 0.1018 - val_acc: 0.9736
Epoch 59/300
121/122 [============================>.] - ETA: 2s - loss: 0.2679 - acc: 0.9799  Epoch 00058: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.2705 - acc: 0.9798 - val_loss: 0.1094 - val_acc: 0.9741
Epoch 60/300
121/122 [============================>.] - ETA: 2s - loss: 0.2196 - acc: 0.9810  Epoch 00059: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.2208 - acc: 0.9811 - val_loss: 0.0990 - val_acc: 0.9762
Epoch 61/300
121/122 [============================>.] - ETA: 2s - loss: 0.2314 - acc: 0.9815  Epoch 00060: val_loss improved from 0.09888 to 0.09849, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.060-0.0985.hdf5
122/122 [==============================] - 385s - loss: 0.2303 - acc: 0.9816 - val_loss: 0.0985 - val_acc: 0.9757
Epoch 62/300
121/122 [============================>.] - ETA: 2s - loss: 0.1930 - acc: 0.9842  Epoch 00061: val_loss did not improve
122/122 [==============================] - 384s - loss: 0.1952 - acc: 0.9841 - val_loss: 0.1020 - val_acc: 0.9739
Epoch 63/300
121/122 [============================>.] - ETA: 2s - loss: 0.2116 - acc: 0.9809  Epoch 00062: val_loss did not improve

Epoch 00062: reducing learning rate to 9.99999974738e-07.
122/122 [==============================] - 385s - loss: 0.2152 - acc: 0.9809 - val_loss: 0.0994 - val_acc: 0.9767
Epoch 64/300
121/122 [============================>.] - ETA: 2s - loss: 0.1612 - acc: 0.9835  Epoch 00063: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1610 - acc: 0.9835 - val_loss: 0.0995 - val_acc: 0.9767
Epoch 65/300
121/122 [============================>.] - ETA: 2s - loss: 0.1520 - acc: 0.9863  Epoch 00064: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1516 - acc: 0.9863 - val_loss: 0.0987 - val_acc: 0.9759
Epoch 66/300
121/122 [============================>.] - ETA: 2s - loss: 0.1731 - acc: 0.9844  Epoch 00065: val_loss improved from 0.09849 to 0.09737, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.065-0.0974.hdf5
122/122 [==============================] - 392s - loss: 0.1721 - acc: 0.9845 - val_loss: 0.0974 - val_acc: 0.9785
Epoch 67/300
121/122 [============================>.] - ETA: 2s - loss: 0.1431 - acc: 0.9846  Epoch 00066: val_loss improved from 0.09737 to 0.09665, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.066-0.0966.hdf5
122/122 [==============================] - 392s - loss: 0.1421 - acc: 0.9847 - val_loss: 0.0966 - val_acc: 0.9790
Epoch 68/300
121/122 [============================>.] - ETA: 2s - loss: 0.1448 - acc: 0.9852  Epoch 00067: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1443 - acc: 0.9853 - val_loss: 0.0968 - val_acc: 0.9783
Epoch 69/300
121/122 [============================>.] - ETA: 2s - loss: 0.1608 - acc: 0.9849  Epoch 00068: val_loss improved from 0.09665 to 0.09623, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.068-0.0962.hdf5
122/122 [==============================] - 392s - loss: 0.1597 - acc: 0.9850 - val_loss: 0.0962 - val_acc: 0.9783
Epoch 70/300
121/122 [============================>.] - ETA: 2s - loss: 0.1340 - acc: 0.9860  Epoch 00069: val_loss improved from 0.09623 to 0.09595, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.069-0.0960.hdf5
122/122 [==============================] - 391s - loss: 0.1354 - acc: 0.9860 - val_loss: 0.0960 - val_acc: 0.9780
Epoch 71/300
121/122 [============================>.] - ETA: 2s - loss: 0.1590 - acc: 0.9861  Epoch 00070: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1584 - acc: 0.9860 - val_loss: 0.0963 - val_acc: 0.9780
Epoch 72/300
121/122 [============================>.] - ETA: 2s - loss: 0.1378 - acc: 0.9873  Epoch 00071: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1370 - acc: 0.9874 - val_loss: 0.0962 - val_acc: 0.9780
Epoch 73/300
121/122 [============================>.] - ETA: 2s - loss: 0.1388 - acc: 0.9859  Epoch 00072: val_loss improved from 0.09595 to 0.09575, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.072-0.0957.hdf5
122/122 [==============================] - 392s - loss: 0.1387 - acc: 0.9857 - val_loss: 0.0957 - val_acc: 0.9783
Epoch 74/300
121/122 [============================>.] - ETA: 2s - loss: 0.1287 - acc: 0.9868  Epoch 00073: val_loss improved from 0.09575 to 0.09525, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.073-0.0952.hdf5
122/122 [==============================] - 392s - loss: 0.1280 - acc: 0.9869 - val_loss: 0.0952 - val_acc: 0.9780
Epoch 75/300
121/122 [============================>.] - ETA: 2s - loss: 0.1484 - acc: 0.9859  Epoch 00074: val_loss improved from 0.09525 to 0.09456, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.074-0.0946.hdf5
122/122 [==============================] - 392s - loss: 0.1479 - acc: 0.9859 - val_loss: 0.0946 - val_acc: 0.9780
Epoch 76/300
121/122 [============================>.] - ETA: 2s - loss: 0.1321 - acc: 0.9861  Epoch 00075: val_loss improved from 0.09456 to 0.09342, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.075-0.0934.hdf5
122/122 [==============================] - 392s - loss: 0.1318 - acc: 0.9860 - val_loss: 0.0934 - val_acc: 0.9783
Epoch 77/300
121/122 [============================>.] - ETA: 2s - loss: 0.1414 - acc: 0.9857  Epoch 00076: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1407 - acc: 0.9858 - val_loss: 0.0934 - val_acc: 0.9788
Epoch 78/300
121/122 [============================>.] - ETA: 2s - loss: 0.1354 - acc: 0.9859  Epoch 00077: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1349 - acc: 0.9859 - val_loss: 0.0941 - val_acc: 0.9783
Epoch 79/300
121/122 [============================>.] - ETA: 2s - loss: 0.1407 - acc: 0.9868  Epoch 00078: val_loss improved from 0.09342 to 0.09320, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.078-0.0932.hdf5
122/122 [==============================] - 392s - loss: 0.1401 - acc: 0.9867 - val_loss: 0.0932 - val_acc: 0.9783
Epoch 80/300
121/122 [============================>.] - ETA: 2s - loss: 0.1348 - acc: 0.9866  Epoch 00079: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1348 - acc: 0.9866 - val_loss: 0.0935 - val_acc: 0.9777
Epoch 81/300
121/122 [============================>.] - ETA: 2s - loss: 0.1247 - acc: 0.9868  Epoch 00080: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1249 - acc: 0.9869 - val_loss: 0.0946 - val_acc: 0.9783
Epoch 82/300
121/122 [============================>.] - ETA: 2s - loss: 0.1230 - acc: 0.9873  Epoch 00081: val_loss did not improve

Epoch 00081: reducing learning rate to 9.99999997475e-08.
122/122 [==============================] - 391s - loss: 0.1223 - acc: 0.9874 - val_loss: 0.0936 - val_acc: 0.9788
Epoch 83/300
121/122 [============================>.] - ETA: 2s - loss: 0.1191 - acc: 0.9886  Epoch 00082: val_loss improved from 0.09320 to 0.09242, saving model to ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.082-0.0924.hdf5
122/122 [==============================] - 392s - loss: 0.1184 - acc: 0.9887 - val_loss: 0.0924 - val_acc: 0.9788
Epoch 84/300
121/122 [============================>.] - ETA: 2s - loss: 0.1106 - acc: 0.9881  Epoch 00083: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1101 - acc: 0.9882 - val_loss: 0.0928 - val_acc: 0.9788
Epoch 85/300
121/122 [============================>.] - ETA: 2s - loss: 0.1223 - acc: 0.9873  Epoch 00084: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1225 - acc: 0.9872 - val_loss: 0.0925 - val_acc: 0.9790
Epoch 86/300
121/122 [============================>.] - ETA: 2s - loss: 0.1228 - acc: 0.9876  Epoch 00085: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1222 - acc: 0.9876 - val_loss: 0.0931 - val_acc: 0.9790
Epoch 87/300
121/122 [============================>.] - ETA: 2s - loss: 0.1126 - acc: 0.9872  Epoch 00086: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1124 - acc: 0.9873 - val_loss: 0.0932 - val_acc: 0.9788
Epoch 88/300
121/122 [============================>.] - ETA: 2s - loss: 0.1204 - acc: 0.9870  Epoch 00087: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1204 - acc: 0.9870 - val_loss: 0.0939 - val_acc: 0.9785
Epoch 89/300
121/122 [============================>.] - ETA: 2s - loss: 0.1235 - acc: 0.9872  Epoch 00088: val_loss did not improve

Epoch 00088: reducing learning rate to 1.00000001169e-08.
122/122 [==============================] - 391s - loss: 0.1245 - acc: 0.9871 - val_loss: 0.0941 - val_acc: 0.9788
Epoch 90/300
121/122 [============================>.] - ETA: 2s - loss: 0.1276 - acc: 0.9870  Epoch 00089: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1272 - acc: 0.9871 - val_loss: 0.0926 - val_acc: 0.9785
Epoch 91/300
121/122 [============================>.] - ETA: 2s - loss: 0.1069 - acc: 0.9879  Epoch 00090: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1065 - acc: 0.9880 - val_loss: 0.0925 - val_acc: 0.9785
Epoch 92/300
121/122 [============================>.] - ETA: 2s - loss: 0.1190 - acc: 0.9875  Epoch 00091: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1189 - acc: 0.9875 - val_loss: 0.0935 - val_acc: 0.9788
Epoch 93/300
121/122 [============================>.] - ETA: 2s - loss: 0.1246 - acc: 0.9872  Epoch 00092: val_loss did not improve
122/122 [==============================] - 391s - loss: 0.1247 - acc: 0.9872 - val_loss: 0.0936 - val_acc: 0.9788
Epoch 94/300
121/122 [============================>.] - ETA: 2s - loss: 0.1185 - acc: 0.9870  Epoch 00093: val_loss did not improve

Epoch 00093: reducing learning rate to 9.99999993923e-10.
122/122 [==============================] - 391s - loss: 0.1188 - acc: 0.9869 - val_loss: 0.0942 - val_acc: 0.9783
Epoch 00093: early stopping
Out[8]:
<keras.callbacks.History at 0x7f8dca5b3e90>

In [ ]:
#resume training

model, model_name = get_best_model()
# print('Loading model from weights.004-0.0565.hdf5')
# model = load_model(CHECHPOINT_DIR+'weights.004-0.0565.hdf5')

# #try increasing learningrate
# optimizer = Adam(lr=1e-4)
# model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

model.fit_generator(train_generator, steps_per_epoch=steps_per_epoch, epochs=200, verbose=1, 
                    callbacks=[early_stopping, model_checkpoint, learningrate_schedule, tensorboard], 
                    validation_data=(X_valid_centered,y_valid), class_weight=class_weight, 
                    workers=3, pickle_safe=True, initial_epoch=83)

In [9]:
#test prepare

test_model, test_model_name = get_best_model()
# print('Loading model from weights.004-0.0565.hdf5')
# test_model = load_model('./checkpoints/checkpoint2/weights.004-0.0565.hdf5')

def test_generator(df, mean, datagen = None, batch_size = BATCHSIZE):
    n = df.shape[0]
    batch_index = 0
    while 1:
        current_index = batch_index * batch_size
        if n >= current_index + batch_size:
            current_batch_size = batch_size
            batch_index += 1    
        else:
            current_batch_size = n - current_index
            batch_index = 0        
        batch_df = df[current_index:current_index+current_batch_size]
        batch_x = np.zeros((batch_df.shape[0], ROWS, COLS, 3), dtype=K.floatx())
        i = 0
        for index,row in batch_df.iterrows():
            image_file = row['image_file']
            bbox = [row['xmin'],row['ymin'],row['xmax'],row['ymax']]
            cropped = load_img(TEST_DIR+image_file,bbox,target_size=(ROWS,COLS))
            x = np.asarray(cropped, dtype=K.floatx())
            x /= 255.
            if datagen is not None: x = datagen.random_transform(x)            
            x = preprocess_input(x, mean)
            batch_x[i] = x
            i += 1
        if batch_index%50 == 0: print('batch_index', batch_index)
        yield(batch_x)
        
test_aug_datagen = ImageDataGenerator(
    rotation_range=180,
    shear_range=0.2,
    zoom_range=0.1,
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True,
    vertical_flip=True)

train_mean = mean(X_valid)
print('train_mean', train_mean)


Loading model from checkpoint file ./resnet50_FT38_Classifier_Rep4/checkpoint/weights.082-0.0924.hdf5
Loading model Done!
train_mean [ 0.37204069  0.41050309  0.38143238]

In [ ]:
# train_mean = [0.37698776,  0.41491762,  0.38681713]
train_mean = mean(X_valid)

In [12]:
#validation data fish logloss
 
valid_pred = test_model.predict(X_valid_centered, batch_size=BATCHSIZE, verbose=1)
# valid_pred = test_model.predict_generator(test_generator(df=valid_df, mean=valid_mean),
#                                           val_samples=valid_df.shape[0], nb_worker=1, pickle_safe=False)
valid_logloss_df = pd.DataFrame(columns=['logloss','class'])
for i in range(y_valid.shape[0]):
    index = np.argmax(y_valid[i,:])
    fish = FISH_CLASSES[index]
    logloss = -math.log(valid_pred[i,index])
    valid_logloss_df.loc[len(valid_logloss_df)]=[logloss,fish]                                       
print('valid loss:', valid_logloss_df['logloss'].mean())
print('valid fish loss:', valid_logloss_df[valid_logloss_df['class']!='NoF']['logloss'].mean())
print(valid_logloss_df.groupby(['class'])['logloss'].mean())

train_pred = test_model.predict(X_train_centered, batch_size=BATCHSIZE, verbose=1)
# train_pred = test_model.predict_generator(test_generator(df=train_df, ),
#                                           val_samples=train_df.shape[0], nb_worker=1, pickle_safe=False)
train_logloss_df = pd.DataFrame(columns=['logloss','class'])
for i in range(y_train.shape[0]):
    index = np.argmax(y_train[i,:])
    fish = FISH_CLASSES[index]
    logloss = -math.log(train_pred[i,index])
    train_logloss_df.loc[len(train_logloss_df)]=[logloss,fish] 
print('train loss:', train_logloss_df['logloss'].mean())
print('train fish loss:', train_logloss_df[train_logloss_df['class']!='NoF']['logloss'].mean())
print(train_logloss_df.groupby(['class'])['logloss'].mean())


3863/3863 [==============================] - 40s     
valid loss: 0.0936035634052
valid fish loss: 0.213601306756
class
ALB      0.202928
BET      0.423660
DOL      0.661419
LAG      0.002563
NoF      0.058878
OTHER    0.201856
SHARK    0.005478
YFT      0.178296
Name: logloss, dtype: float64
15616/15616 [==============================] - 164s     
train loss: 0.0401916851351
train fish loss: 0.0417360296024
class
ALB      0.060663
BET      0.027422
DOL      0.001574
LAG      0.000586
NoF      0.039745
OTHER    0.012223
SHARK    0.001352
YFT      0.021237
Name: logloss, dtype: float64

In [ ]:
#GTbbox_CROPpred_df = ['image_file','crop_index','crop_class','xmin','ymin','xmax','ymax','split'
#                      'NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT', 'logloss']

file_name = 'GTbbox_CROPpred_df_'+test_model_name+'_.pickle'
if os.path.exists(OUTPUT_DIR+file_name):
    print ('Loading from file '+file_name)
    GTbbox_CROPpred_df = pd.read_pickle(OUTPUT_DIR+file_name)
else:
    print ('Generating file '+file_name) 
    nb_augmentation = 1
    if nb_augmentation ==1:
        test_preds = test_model.predict_generator(test_generator(df=GTbbox_df, mean=train_mean), 
                                                  steps=int(math.ceil(GTbbox_df.shape[0]/BATCHSIZE)), workers=1, pickle_safe=False)
    else:
        test_preds = np.zeros((GTbbox_df.shape[0], len(FISH_CLASSES)), dtype=K.floatx())
        for idx in range(nb_augmentation):
            print('{}th augmentation for testing ...'.format(idx+1))
            test_preds += test_model.predict_generator(test_generator(df=GTbbox_df, mean=train_mean, datagen=test_aug_datagen), 
                                                       steps=GTbbox_df.shape[0], workers=1, pickle_safe=False)
        test_preds /= nb_augmentation

    CROPpred_df = pd.DataFrame(test_preds, columns=FISH_CLASSES)
    GTbbox_CROPpred_df = pd.concat([GTbbox_df,CROPpred_df], axis=1)
    GTbbox_CROPpred_df['logloss'] = GTbbox_CROPpred_df.apply(lambda row: -math.log(row[row['crop_class']]), axis=1)
    GTbbox_CROPpred_df.to_pickle(OUTPUT_DIR+file_name) 

#logloss of every fish class
print(GTbbox_CROPpred_df.groupby(['crop_class'])['logloss'].mean())
print(GTbbox_CROPpred_df['logloss'].mean())

In [ ]:
Loading from file GTbbox_CROPpred_df_weights.000-0.0327.hdf5_.pickle
crop_class
ALB      0.076577
BET      0.139025
DOL      0.126520
LAG      0.000761
NoF      0.051943
OTHER    0.133949
SHARK    0.018328
YFT      0.090739
Name: logloss, dtype: float64
0.05936252677814113

In [ ]:
# RFCNbbox_RFCNpred_df = ['image_class','image_file','crop_index','xmin','ymin','xmax','ymax',
#                          'NoF_RFCN', 'ALB_RFCN', 'BET_RFCN', 'DOL_RFCN',
#                          'LAG_RFCN', 'OTHER_RFCN', 'SHARK_RFCN', 'YFT_RFCN']
# select fish_conf >= CONF_THRESH

file_name = 'RFCNbbox_RFCNpred_df_conf{:.2f}.pickle'.format(CONF_THRESH)
if os.path.exists(OUTPUT_DIR+file_name):
    print ('Loading from file '+file_name)
    RFCNbbox_RFCNpred_df = pd.read_pickle(OUTPUT_DIR+file_name)
else:
    print ('Generating file '+file_name)        
    RFCNbbox_RFCNpred_df = pd.DataFrame(columns=['image_class','image_file','crop_index','xmin','ymin','xmax','ymax',
                                                  'NoF_RFCN', 'ALB_RFCN', 'BET_RFCN', 'DOL_RFCN',
                                                  'LAG_RFCN', 'OTHER_RFCN', 'SHARK_RFCN', 'YFT_RFCN']) 

    with open('../data/RFCN_detections/detections_full_AGNOSTICnms_'+RFCN_MODEL+'.pkl','rb') as f:
        detections_full_AGNOSTICnms = pickle.load(f, encoding='latin1') 
    with open("../RFCN/ImageSets/Main/test.txt","r") as f:
        test_files = f.readlines()
    with open("../RFCN/ImageSets/Main/train_test.txt","r") as f:
        train_file_labels = f.readlines()
    assert len(detections_full_AGNOSTICnms) == len(test_files)
    
    count = np.zeros(len(detections_full_AGNOSTICnms))
    
    for im in range(len(detections_full_AGNOSTICnms)):
        if im%1000 == 0: print(im)
        basename = test_files[im][:9]
        if im<1000:
            image_class = '--'
        else:
            for i in range(len(train_file_labels)):
                if train_file_labels[i][:9] == basename:
                    image_class = train_file_labels[i][10:-1]
                    break
        image = Image.open(TEST_DIR+'/'+basename+'.jpg')
        width_image, height_image = image.size
        
        bboxes = []
        detects_im = detections_full_AGNOSTICnms[im]
        for i in range(len(detects_im)):
#             if np.sum(detects_im[i,5:]) >= CONF_THRESH:
            if np.max(detects_im[i,5:]) >= CONF_THRESH:
                bboxes.append(detects_im[i,:]) 
        count[im] = len(bboxes)
        if len(bboxes) == 0:
            ind = np.argmax(np.sum(detects_im[:,5:], axis=1))
            bboxes.append(detects_im[ind,:])
        bboxes = np.asarray(bboxes)

        for j in range(len(bboxes)):    
            bbox = bboxes[j]
            xmin = bbox[0]
            ymin = bbox[1]
            xmax = bbox[2]
            ymax = bbox[3]
            assert max(xmin,0)<min(xmax,width_image)
            assert max(ymin,0)<min(ymax,height_image)
            RFCNbbox_RFCNpred_df.loc[len(RFCNbbox_RFCNpred_df)]=[image_class,basename+'.jpg',j,max(xmin,0),max(ymin,0),
                                                                   min(xmax,width_image),min(ymax,height_image),
                                                                   bbox[4],bbox[5],bbox[6],bbox[7],bbox[8],bbox[9],bbox[10],bbox[11]]   
    
    RFCNbbox_RFCNpred_df.to_pickle(OUTPUT_DIR+file_name)
file_name = 'data_test_Crop_{}_{}.pickle'.format(ROWS, COLS) if os.path.exists(OUTPUT_DIR+file_name): print ('Loading from file '+file_name) with open(OUTPUT_DIR+file_name, 'rb') as f: data_test = pickle.load(f) X_test_crop = data_train['X_test_crop'] else: print ('Generating file '+file_name) X_test_crop = np.ndarray((RFCNbbox_RFCNpred_df.shape[0], ROWS, COLS, 3), dtype=np.uint8) i = 0 for index,row in RFCNbbox_RFCNpred_df.iterrows(): image_file = row['image_file'] bbox = [row['xmin'],row['ymin'],row['xmax'],row['ymax']] cropped = load_img(TEST_DIR+image_file,bbox,target_size=(ROWS,COLS)) X_test_crop[i] = np.asarray(cropped) i += 1 #save data to file data_test = {'X_test_crop': X_test_crop} with open(OUTPUT_DIR+file_name, 'wb') as f: pickle.dump(data_test, f) print('Loading data done.') X_test_crop = X_test_crop.astype(np.float32) print('Convert to float32 done.') X_test_crop /= 255. print('Rescale by 255 done.')

In [ ]:
file_name = 'data_trainfish_Crop_{}_{}.pickle'.format(ROWS, COLS)
if os.path.exists(OUTPUT_DIR+file_name):
    print ('Loading from file '+file_name)
    with open(OUTPUT_DIR+file_name, 'rb') as f:
        data_trainfish = pickle.load(f)
    X_trainfish_crop = data_train['X_trainfish_crop']
else:
    print ('Generating file '+file_name)

    GTbbox_CROPpred_fish_df = GTbbox_CROPpred_df.loc[GTbbox_CROPpred_df['crop_class']!='NoF']
    X_trainfish_crop = np.ndarray((GTbbox_CROPpred_fish_df.shape[0], ROWS, COLS, 3), dtype=np.uint8)
    i = 0
    for index,row in GTbbox_CROPpred_fish_df.iterrows():
        image_file = row['image_file']
        bbox = [row['xmin'],row['ymin'],row['xmax'],row['ymax']]
        cropped = load_img(TEST_DIR+image_file,bbox,target_size=(ROWS,COLS))
        X_trainfish_crop[i] = np.asarray(cropped)
        i += 1
   
    #save data to file
    data_trainfish = {'X_trainfish_crop': X_trainfish_crop}
    with open(OUTPUT_DIR+file_name, 'wb') as f:
        pickle.dump(data_trainfish, f)
        
print('Loading data done.')
X_trainfish_crop = X_trainfish_crop.astype(np.float32)
print('Convert to float32 done.')
X_trainfish_crop /= 255.
print('Rescale by 255 done.')

In [ ]:
mean(X_trainfish_crop)

In [ ]:
mean(X_test_crop[1251:])

In [ ]:
# test_mean = [0.41019869,  0.43978861,  0.39873621]
test_mean = [0.37698776,  0.41491762,  0.38681713]

In [ ]:
# RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df = ['image_class', 'image_file','crop_index','xmin','ymin','xmax','ymax',
#                                    'NoF_RFCN', 'ALB_RFCN', 'BET_RFCN', 'DOL_RFCN',
#                                    'LAG_RFCN', 'OTHER_RFCN', 'SHARK_RFCN', 'YFT_RFCN',
#                                    'NoF_CROP', 'ALB_CROP', 'BET_CROP', 'DOL_CROP',
#                                    'LAG_CROP', 'OTHER_CROP', 'SHARK_CROP', 'YFT_CROP',
#                                    'NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']

file_name = 'RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df_'+test_model_name+'_.pickle'
if os.path.exists(OUTPUT_DIR+file_name):
    print ('Loading from file '+file_name)
    RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df = pd.read_pickle(OUTPUT_DIR+file_name)
else:
    print ('Generating file '+file_name)  
    nb_augmentation = 1
    if nb_augmentation ==1:
        test_preds = test_model.predict_generator(test_generator(df=RFCNbbox_RFCNpred_df, mean=test_mean), 
                                                  val_samples=RFCNbbox_RFCNpred_df.shape[0], nb_worker=1, pickle_safe=False)
    else:
        test_preds = np.zeros((RFCNbbox_RFCNpred_df.shape[0], len(FISH_CLASSES)), dtype=K.floatx())
        for idx in range(nb_augmentation):
            print('{}th augmentation for testing ...'.format(idx+1))
            test_preds += test_model.predict_generator(test_generator(df=RFCNbbox_RFCNpred_df, mean=test_mean, datagen=test_aug_datagen), 
                                                       val_samples=RFCNbbox_RFCNpred_df.shape[0], nb_worker=1, pickle_safe=False)
        test_preds /= nb_augmentation

    CROPpred_df = pd.DataFrame(test_preds, columns=['ALB_CROP', 'BET_CROP', 'DOL_CROP', 'LAG_CROP', 'NoF_CROP', 'OTHER_CROP', 'SHARK_CROP', 'YFT_CROP'])
    RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df = pd.concat([RFCNbbox_RFCNpred_df,CROPpred_df], axis=1)
    
    RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df['NoF'] = RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df['NoF_RFCN']
    for fish in ['ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']:
        RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df[fish] = RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df.apply(lambda row: (1-row['NoF_RFCN'])*row[[fish+'_CROP']]/(1-row['NoF_CROP']) if row['NoF_CROP']!=1 else 0, axis=1)
#     for fish in FISH_CLASSES:
#         RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df[fish] = RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df[fish+'_CROP']

    RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df.to_pickle(OUTPUT_DIR+file_name)

In [ ]:
# clsMaxAve and hybrid RFCNpred&CROPpred such that RFCNpred for NoF and CROPpred for fish
# test_pred_df = ['logloss','image_class','image_file','NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']
# RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df = ['image_class', 'image_file','crop_index','xmin','ymin','xmax','ymax',
#                                    'NoF_RFCN', 'ALB_RFCN', 'BET_RFCN', 'DOL_RFCN',
#                                    'LAG_RFCN', 'OTHER_RFCN', 'SHARK_RFCN', 'YFT_RFCN',
#                                    'ALB_CROP', 'BET_CROP', 'DOL_CROP',
#                                    'LAG_CROP', 'OTHER_CROP', 'SHARK_CROP', 'YFT_CROP',
#                                    'NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']

file_name = 'test_pred_df_Hybrid_'+test_model_name+'_.pickle'
if os.path.exists(OUTPUT_DIR+file_name):
    print ('Loading from file '+file_name)
    test_pred_df = pd.read_pickle(OUTPUT_DIR+file_name)
else:
    print ('Generating file '+file_name)  
    with open("../RFCN/ImageSets/Main/test.txt","r") as f:
        test_files = f.readlines()
    
    test_pred_df = pd.DataFrame(columns=['logloss','image_class','image_file','NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT'])  
    for j in range(len(test_files)): 
        image_file = test_files[j][:-1]+'.jpg'
        test_pred_im_df = RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df.loc[RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df['image_file'] == image_file,
                                                                       ['image_class', 'NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']]
        image_class = test_pred_im_df.iloc[0]['image_class']
        test_pred_im_df.drop('image_class', axis=1, inplace=True)
        max_score = test_pred_im_df.max(axis=1)
        max_cls = test_pred_im_df.idxmax(axis=1)
        test_pred_im_df['max_score'] = max_score
        test_pred_im_df['max_cls'] = max_cls
        test_pred_im_df['Count'] = test_pred_im_df.groupby(['max_cls'])['max_cls'].transform('count')
        idx = test_pred_im_df.groupby(['max_cls'])['max_score'].transform(max) == test_pred_im_df['max_score']
        test_pred_im_clsMax_df = test_pred_im_df.loc[idx,['NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT', 'Count']]
        test_pred_im_clsMax_array = test_pred_im_clsMax_df.values
        pred = np.average(test_pred_im_clsMax_array[:,:-1], axis=0, weights=test_pred_im_clsMax_array[:,-1], returned=False).tolist()
        if image_class!='--':
            ind = FISH_CLASSES.index(image_class)
            logloss = -math.log(pred[ind]) 
        else:
            logloss = np.nan
        test_pred_im_clsMaxAve = [logloss,image_class,image_file]
        test_pred_im_clsMaxAve.extend(pred)
        test_pred_df.loc[len(test_pred_df)]=test_pred_im_clsMaxAve

    test_pred_df.to_pickle(OUTPUT_DIR+file_name)

In [ ]:
#### visualization
# RFCNbbox_RFCNpred_CROPpred_df = ['image_class', 'image_file','crop_index','x_min','y_min','x_max','ymax',
#                                    'NoF_RFCN', 'ALB_RFCN', 'BET_RFCN', 'DOL_RFCN',
#                                    'LAG_RFCN', 'OTHER_RFCN', 'SHARK_RFCN', 'YFT_RFCN'
#                                    'NoF_CROP', 'ALB_CROP', 'BET_CROP', 'DOL_CROP',
#                                    'LAG_CROP', 'OTHER_CROP', 'SHARK_CROP', 'YFT_CROP']
#GTbbox_CROPpred_df = ['image_file','crop_index','crop_class','xmin','ymin','xmax','ymax',
#                      'NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT', 'logloss']
# test_pred_df = ['logloss','image_class','image_file','NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']

for j in range(test_pred_df.shape[0]):
    image_logloss = test_pred_df.iat[j,0]
    image_class = test_pred_df.iat[j,1]
    image_file = test_pred_df.iat[j,2]
    if j<1000 and j%30== 0:
        pass
    else: 
        continue
    im = Image.open('../RFCN/JPEGImages/'+image_file)
    im = np.asarray(im)
    fig, ax = plt.subplots(figsize=(10, 8))
    ax.imshow(im, aspect='equal')
    RFCN_dets = RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df.loc[RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df['image_file']==image_file]
    for index,row in RFCN_dets.iterrows():
        bbox = [row['xmin'],row['ymin'],row['xmax'],row['ymax']]
        RFCN = [row['NoF_RFCN'],row['ALB_RFCN'],row['BET_RFCN'],row['DOL_RFCN'],row['LAG_RFCN'],row['OTHER_RFCN'],row['SHARK_RFCN'],row['YFT_RFCN']]
        CROP = [row['NoF'],row['ALB'],row['BET'],row['DOL'],row['LAG'],row['OTHER'],row['SHARK'],row['YFT']]
        score_RFCN = max(RFCN)
        score_CROP = max(CROP)
        index_RFCN = RFCN.index(score_RFCN)
        index_CROP = CROP.index(score_CROP)
        class_RFCN = FISH_CLASSES[index_RFCN]
        class_CROP = FISH_CLASSES[index_CROP]
        ax.add_patch(plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=2))
        ax.text(bbox[0], bbox[1] - 2, 'RFCN_{:s} {:.3f} \nHYBRID_{:s} {:.3f}'.format(class_RFCN, score_RFCN, class_CROP, score_CROP), bbox=dict(facecolor='red', alpha=0.5), fontsize=8, color='white')       
    GT_dets = GTbbox_CROPpred_df.loc[GTbbox_CROPpred_df['image_file']==image_file]
    for index,row in GT_dets.iterrows():
        bbox = [row['xmin'],row['ymin'],row['xmax'],row['ymax']]
        CROP = [row['NoF'],row['ALB'],row['BET'],row['DOL'],row['LAG'],row['OTHER'],row['SHARK'],row['YFT']]
        score_CROP = max(CROP)
        index_CROP = CROP.index(score_CROP)
        class_CROP = FISH_CLASSES[index_CROP]
        ax.add_patch(plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='green', linewidth=2))
        ax.text(bbox[0], bbox[3] + 40, 'GT_{:s} \nCROP_{:s} {:.3f}'.format(row['crop_class'], class_CROP, score_CROP), bbox=dict(facecolor='green', alpha=0.5), fontsize=8, color='white')
    ax.set_title(('Image {:s}    FISH {:s}    logloss {}').format(image_file, image_class, image_logloss), fontsize=10) 
    plt.axis('off')
    plt.tight_layout()
    plt.draw()

In [ ]:
#temperature
T = 2.5
test_pred_array = test_pred_df[FISH_CLASSES].values
test_pred_T_array = np.exp(np.log(test_pred_array)/T)
test_pred_T_array = test_pred_T_array/np.sum(test_pred_T_array, axis=1, keepdims=True)
test_pred_T_df = pd.DataFrame(test_pred_T_array, columns=FISH_CLASSES)
test_pred_T_df = pd.concat([test_pred_df[['image_class','image_file']],test_pred_T_df], axis=1)

#add logloss
test_pred_T_df['logloss'] = test_pred_T_df.apply(lambda row: -math.log(row[row['image_class']]) if row['image_class']!='--' else np.nan, axis=1)

#calculate train logloss
print(test_pred_T_df.groupby(['image_class'])['logloss'].mean())
train_logloss = test_pred_T_df['logloss'].mean()
print('logloss of train is', train_logloss )

In [ ]:
#test submission
submission = test_pred_T_df.loc[:999,['image_file','NoF', 'ALB', 'BET', 'DOL', 'LAG', 'OTHER', 'SHARK', 'YFT']]
submission.rename(columns={'image_file':'image'}, inplace=True)
sub_file = 'RFCN_AGONOSTICnms_'+RFCN_MODEL+'_'+CROP_MODEL+'_clsMaxAve_conf{:.2f}_T{}_'.format(CONF_THRESH, T)+'{:.4f}'.format(train_logloss)+'.csv'
submission.to_csv(sub_file, index=False)
print('Done!'+sub_file)

In [ ]: