diff from Classifier_rep2 use centered data to train weights.088-0.0788.hdf5 loss: 0.0676 - acc: 0.9924 - val_loss: 0.0788 - val_acc: 0.9827 class ALB 0.135044 BET 0.519080 DOL 0.665302 LAG 0.000691 NoF 0.045853 OTHER 0.282091 SHARK 0.000237 YFT 0.208891 Name: logloss, dtype: float64 0.0788429576102 class ALB 0.029769 BET 0.007473 DOL 0.000601 LAG 0.000533 NoF 0.016169 OTHER 0.005027 SHARK 0.004082 YFT 0.025846 Name: logloss, dtype: float64 0.0176926563815

In [1]:
import os, random, glob, pickle, collections, math, json
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_Rep3'
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)
#     cropped.save('try.jpg')
#     cropped = Image.open('try.jpg')   
    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:]
    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][:-1]+'.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',max(xmin,0),max(ymin,0),min(xmax,width_image),min(ymax,height_image)]

    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.40802017  0.44779599  0.41339037]
mean of X_valid is [ 0.41244254  0.45302087  0.41779673]
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 [9]:
#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), 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)


Epoch 1/30
121/122 [============================>.] - ETA: 1s - loss: 12.9957 - acc: 0.3999  Epoch 00000: val_loss improved from inf to 1.29187, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.000-1.2919.hdf5
122/122 [==============================] - 227s - loss: 12.9693 - acc: 0.4011 - val_loss: 1.2919 - val_acc: 0.7756
Epoch 2/30
121/122 [============================>.] - ETA: 1s - loss: 10.3930 - acc: 0.5871  Epoch 00001: val_loss improved from 1.29187 to 1.11411, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.001-1.1141.hdf5
122/122 [==============================] - 222s - loss: 10.3937 - acc: 0.5873 - val_loss: 1.1141 - val_acc: 0.7756
Epoch 3/30
121/122 [============================>.] - ETA: 1s - loss: 9.0342 - acc: 0.6544   Epoch 00002: val_loss improved from 1.11411 to 1.06994, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.002-1.0699.hdf5
122/122 [==============================] - 222s - loss: 9.0396 - acc: 0.6544 - val_loss: 1.0699 - val_acc: 0.7756
Epoch 4/30
121/122 [============================>.] - ETA: 1s - loss: 8.0070 - acc: 0.6849   Epoch 00003: val_loss did not improve
122/122 [==============================] - 222s - loss: 7.9905 - acc: 0.6856 - val_loss: 1.0884 - val_acc: 0.7756
Epoch 5/30
121/122 [============================>.] - ETA: 1s - loss: 7.4372 - acc: 0.7137  Epoch 00004: val_loss did not improve
122/122 [==============================] - 222s - loss: 7.4447 - acc: 0.7138 - val_loss: 1.0839 - val_acc: 0.7756
Epoch 6/30
121/122 [============================>.] - ETA: 1s - loss: 6.8642 - acc: 0.7189  Epoch 00005: val_loss improved from 1.06994 to 0.95738, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.005-0.9574.hdf5
122/122 [==============================] - 223s - loss: 6.8901 - acc: 0.7195 - val_loss: 0.9574 - val_acc: 0.7758
Epoch 7/30
121/122 [============================>.] - ETA: 1s - loss: 6.5456 - acc: 0.7355  Epoch 00006: val_loss improved from 0.95738 to 0.74859, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.006-0.7486.hdf5
122/122 [==============================] - 223s - loss: 6.5318 - acc: 0.7355 - val_loss: 0.7486 - val_acc: 0.7813
Epoch 8/30
121/122 [============================>.] - ETA: 1s - loss: 6.3399 - acc: 0.7410  Epoch 00007: val_loss improved from 0.74859 to 0.59915, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.007-0.5991.hdf5
122/122 [==============================] - 223s - loss: 6.3096 - acc: 0.7407 - val_loss: 0.5991 - val_acc: 0.8103
Epoch 9/30
121/122 [============================>.] - ETA: 1s - loss: 5.8543 - acc: 0.7618  Epoch 00008: val_loss improved from 0.59915 to 0.57959, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.008-0.5796.hdf5
122/122 [==============================] - 222s - loss: 5.8406 - acc: 0.7620 - val_loss: 0.5796 - val_acc: 0.8082
Epoch 10/30
121/122 [============================>.] - ETA: 1s - loss: 5.8402 - acc: 0.7677  Epoch 00009: val_loss did not improve
122/122 [==============================] - 222s - loss: 5.8379 - acc: 0.7675 - val_loss: 0.5994 - val_acc: 0.8069
Epoch 11/30
121/122 [============================>.] - ETA: 1s - loss: 5.4904 - acc: 0.7663  Epoch 00010: val_loss improved from 0.57959 to 0.57824, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.010-0.5782.hdf5
122/122 [==============================] - 223s - loss: 5.4907 - acc: 0.7668 - val_loss: 0.5782 - val_acc: 0.8154
Epoch 12/30
121/122 [============================>.] - ETA: 1s - loss: 5.4105 - acc: 0.7753  Epoch 00011: val_loss did not improve
122/122 [==============================] - 223s - loss: 5.4348 - acc: 0.7750 - val_loss: 0.6038 - val_acc: 0.8017
Epoch 13/30
121/122 [============================>.] - ETA: 1s - loss: 5.2966 - acc: 0.7789  Epoch 00012: val_loss improved from 0.57824 to 0.52411, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.012-0.5241.hdf5
122/122 [==============================] - 223s - loss: 5.2929 - acc: 0.7790 - val_loss: 0.5241 - val_acc: 0.8325
Epoch 14/30
121/122 [============================>.] - ETA: 1s - loss: 5.0719 - acc: 0.7842  Epoch 00013: val_loss improved from 0.52411 to 0.52331, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.013-0.5233.hdf5
122/122 [==============================] - 223s - loss: 5.0540 - acc: 0.7846 - val_loss: 0.5233 - val_acc: 0.8317
Epoch 15/30
121/122 [============================>.] - ETA: 1s - loss: 4.8416 - acc: 0.7913  Epoch 00014: val_loss did not improve
122/122 [==============================] - 223s - loss: 4.8396 - acc: 0.7912 - val_loss: 0.5637 - val_acc: 0.8141
Epoch 16/30
121/122 [============================>.] - ETA: 1s - loss: 4.7307 - acc: 0.7949  Epoch 00015: val_loss did not improve
122/122 [==============================] - 222s - loss: 4.7234 - acc: 0.7950 - val_loss: 0.5787 - val_acc: 0.8079
Epoch 17/30
121/122 [============================>.] - ETA: 1s - loss: 4.6751 - acc: 0.8009  Epoch 00016: val_loss did not improve
122/122 [==============================] - 222s - loss: 4.6736 - acc: 0.8010 - val_loss: 0.5359 - val_acc: 0.8222
Epoch 18/30
121/122 [============================>.] - ETA: 1s - loss: 4.8269 - acc: 0.7946  Epoch 00017: val_loss did not improve
122/122 [==============================] - 223s - loss: 4.8214 - acc: 0.7944 - val_loss: 0.5502 - val_acc: 0.8165
Epoch 19/30
121/122 [============================>.] - ETA: 1s - loss: 4.5263 - acc: 0.8005  Epoch 00018: val_loss improved from 0.52331 to 0.52058, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.018-0.5206.hdf5
122/122 [==============================] - 222s - loss: 4.5198 - acc: 0.8000 - val_loss: 0.5206 - val_acc: 0.8216
Epoch 20/30
121/122 [============================>.] - ETA: 1s - loss: 4.3894 - acc: 0.8026  Epoch 00019: val_loss improved from 0.52058 to 0.49672, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.019-0.4967.hdf5
122/122 [==============================] - 222s - loss: 4.3869 - acc: 0.8030 - val_loss: 0.4967 - val_acc: 0.8302
Epoch 21/30
121/122 [============================>.] - ETA: 1s - loss: 4.5014 - acc: 0.8117  Epoch 00020: val_loss did not improve
122/122 [==============================] - 223s - loss: 4.4889 - acc: 0.8115 - val_loss: 0.5005 - val_acc: 0.8310
Epoch 22/30
121/122 [============================>.] - ETA: 1s - loss: 4.1160 - acc: 0.8093  Epoch 00021: val_loss improved from 0.49672 to 0.45490, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.021-0.4549.hdf5
122/122 [==============================] - 223s - loss: 4.1048 - acc: 0.8095 - val_loss: 0.4549 - val_acc: 0.8512
Epoch 23/30
121/122 [============================>.] - ETA: 1s - loss: 4.2141 - acc: 0.8148  Epoch 00022: val_loss did not improve
122/122 [==============================] - 223s - loss: 4.2403 - acc: 0.8147 - val_loss: 0.4969 - val_acc: 0.8304
Epoch 24/30
121/122 [============================>.] - ETA: 1s - loss: 4.3555 - acc: 0.8108  Epoch 00023: val_loss did not improve
122/122 [==============================] - 223s - loss: 4.3818 - acc: 0.8106 - val_loss: 0.5373 - val_acc: 0.8178
Epoch 25/30
121/122 [============================>.] - ETA: 1s - loss: 4.0177 - acc: 0.8194  Epoch 00024: val_loss did not improve
122/122 [==============================] - 223s - loss: 4.0255 - acc: 0.8194 - val_loss: 0.4804 - val_acc: 0.8390
Epoch 26/30
121/122 [============================>.] - ETA: 1s - loss: 4.0075 - acc: 0.8177  Epoch 00025: val_loss did not improve
122/122 [==============================] - 222s - loss: 4.0066 - acc: 0.8174 - val_loss: 0.4836 - val_acc: 0.8413
Epoch 27/30
121/122 [============================>.] - ETA: 1s - loss: 4.0357 - acc: 0.8141  Epoch 00026: val_loss improved from 0.45490 to 0.43242, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.026-0.4324.hdf5
122/122 [==============================] - 223s - loss: 4.0367 - acc: 0.8142 - val_loss: 0.4324 - val_acc: 0.8589
Epoch 28/30
121/122 [============================>.] - ETA: 1s - loss: 3.9834 - acc: 0.8250  Epoch 00027: val_loss did not improve
122/122 [==============================] - 222s - loss: 3.9735 - acc: 0.8252 - val_loss: 0.4959 - val_acc: 0.8333
Epoch 29/30
121/122 [============================>.] - ETA: 1s - loss: 3.9319 - acc: 0.8210  Epoch 00028: val_loss did not improve
122/122 [==============================] - 221s - loss: 3.9335 - acc: 0.8213 - val_loss: 0.4396 - val_acc: 0.8532
Epoch 30/30
121/122 [============================>.] - ETA: 1s - loss: 3.7612 - acc: 0.8170  Epoch 00029: val_loss improved from 0.43242 to 0.41071, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.029-0.4107.hdf5
122/122 [==============================] - 222s - loss: 3.7608 - acc: 0.8170 - val_loss: 0.4107 - val_acc: 0.8667
Out[9]:
<keras.callbacks.History at 0x7f8c79c6aa10>

In [ ]:
### 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=30)


Loading model from checkpoint file ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.029-0.4107.hdf5
Loading model Done!
Epoch 31/300
121/122 [============================>.] - ETA: 3s - loss: 3.4680 - acc: 0.8408  Epoch 00030: val_loss improved from 0.41071 to 0.34124, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.030-0.3412.hdf5
122/122 [==============================] - 425s - loss: 3.4688 - acc: 0.8407 - val_loss: 0.3412 - val_acc: 0.8952
Epoch 32/300
121/122 [============================>.] - ETA: 2s - loss: 2.8897 - acc: 0.8601  Epoch 00031: val_loss improved from 0.34124 to 0.31638, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.031-0.3164.hdf5
122/122 [==============================] - 407s - loss: 2.8964 - acc: 0.8600 - val_loss: 0.3164 - val_acc: 0.8985
Epoch 33/300
121/122 [============================>.] - ETA: 2s - loss: 2.5336 - acc: 0.8761  Epoch 00032: val_loss improved from 0.31638 to 0.31631, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.032-0.3163.hdf5
122/122 [==============================] - 409s - loss: 2.5220 - acc: 0.8760 - val_loss: 0.3163 - val_acc: 0.8998
Epoch 34/300
121/122 [============================>.] - ETA: 2s - loss: 2.1038 - acc: 0.8971  Epoch 00033: val_loss improved from 0.31631 to 0.28270, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.033-0.2827.hdf5
122/122 [==============================] - 408s - loss: 2.0996 - acc: 0.8972 - val_loss: 0.2827 - val_acc: 0.9143
Epoch 35/300
121/122 [============================>.] - ETA: 2s - loss: 1.9244 - acc: 0.9026  Epoch 00034: val_loss did not improve
122/122 [==============================] - 408s - loss: 1.9246 - acc: 0.9029 - val_loss: 0.2897 - val_acc: 0.9164
Epoch 36/300
121/122 [============================>.] - ETA: 2s - loss: 1.6446 - acc: 0.9131  Epoch 00035: val_loss improved from 0.28270 to 0.25480, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.035-0.2548.hdf5
122/122 [==============================] - 408s - loss: 1.6436 - acc: 0.9130 - val_loss: 0.2548 - val_acc: 0.9244
Epoch 37/300
121/122 [============================>.] - ETA: 2s - loss: 1.4453 - acc: 0.9181  Epoch 00036: val_loss improved from 0.25480 to 0.22811, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.036-0.2281.hdf5
122/122 [==============================] - 409s - loss: 1.4414 - acc: 0.9180 - val_loss: 0.2281 - val_acc: 0.9345
Epoch 38/300
121/122 [============================>.] - ETA: 2s - loss: 1.4207 - acc: 0.9264  Epoch 00037: val_loss did not improve
122/122 [==============================] - 408s - loss: 1.4166 - acc: 0.9262 - val_loss: 0.2391 - val_acc: 0.9280
Epoch 39/300
121/122 [============================>.] - ETA: 2s - loss: 1.2444 - acc: 0.9311  Epoch 00038: val_loss improved from 0.22811 to 0.22536, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.038-0.2254.hdf5
122/122 [==============================] - 409s - loss: 1.2405 - acc: 0.9315 - val_loss: 0.2254 - val_acc: 0.9353
Epoch 40/300
121/122 [============================>.] - ETA: 2s - loss: 1.0096 - acc: 0.9428  Epoch 00039: val_loss improved from 0.22536 to 0.21124, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.039-0.2112.hdf5
122/122 [==============================] - 408s - loss: 1.0120 - acc: 0.9429 - val_loss: 0.2112 - val_acc: 0.9412
Epoch 41/300
121/122 [============================>.] - ETA: 2s - loss: 0.9448 - acc: 0.9407  Epoch 00040: val_loss did not improve
122/122 [==============================] - 407s - loss: 0.9529 - acc: 0.9407 - val_loss: 0.2152 - val_acc: 0.9399
Epoch 42/300
121/122 [============================>.] - ETA: 2s - loss: 0.8826 - acc: 0.9474  Epoch 00041: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.8804 - acc: 0.9473 - val_loss: 0.2117 - val_acc: 0.9415
Epoch 43/300
121/122 [============================>.] - ETA: 2s - loss: 0.8022 - acc: 0.9525  Epoch 00042: val_loss improved from 0.21124 to 0.19187, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.042-0.1919.hdf5
122/122 [==============================] - 408s - loss: 0.8014 - acc: 0.9522 - val_loss: 0.1919 - val_acc: 0.9469
Epoch 44/300
121/122 [============================>.] - ETA: 2s - loss: 0.7673 - acc: 0.9515  Epoch 00043: val_loss improved from 0.19187 to 0.18473, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.043-0.1847.hdf5
122/122 [==============================] - 409s - loss: 0.7654 - acc: 0.9515 - val_loss: 0.1847 - val_acc: 0.9485
Epoch 45/300
121/122 [============================>.] - ETA: 2s - loss: 0.7233 - acc: 0.9542  Epoch 00044: val_loss improved from 0.18473 to 0.16483, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.044-0.1648.hdf5
122/122 [==============================] - 408s - loss: 0.7264 - acc: 0.9541 - val_loss: 0.1648 - val_acc: 0.9542
Epoch 46/300
121/122 [============================>.] - ETA: 2s - loss: 0.6095 - acc: 0.9592  Epoch 00045: val_loss did not improve
122/122 [==============================] - 407s - loss: 0.6067 - acc: 0.9593 - val_loss: 0.1724 - val_acc: 0.9513
Epoch 47/300
121/122 [============================>.] - ETA: 2s - loss: 0.6108 - acc: 0.9595  Epoch 00046: val_loss improved from 0.16483 to 0.15914, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.046-0.1591.hdf5
122/122 [==============================] - 409s - loss: 0.6082 - acc: 0.9595 - val_loss: 0.1591 - val_acc: 0.9547
Epoch 48/300
121/122 [============================>.] - ETA: 2s - loss: 0.5152 - acc: 0.9638  Epoch 00047: val_loss improved from 0.15914 to 0.14613, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.047-0.1461.hdf5
122/122 [==============================] - 408s - loss: 0.5144 - acc: 0.9640 - val_loss: 0.1461 - val_acc: 0.9581
Epoch 49/300
121/122 [============================>.] - ETA: 2s - loss: 0.4890 - acc: 0.9647  Epoch 00048: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.4871 - acc: 0.9644 - val_loss: 0.1615 - val_acc: 0.9537
Epoch 50/300
121/122 [============================>.] - ETA: 2s - loss: 0.4639 - acc: 0.9647  Epoch 00049: val_loss improved from 0.14613 to 0.14350, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.049-0.1435.hdf5
122/122 [==============================] - 408s - loss: 0.4637 - acc: 0.9647 - val_loss: 0.1435 - val_acc: 0.9596
Epoch 51/300
121/122 [============================>.] - ETA: 2s - loss: 0.4926 - acc: 0.9659  Epoch 00050: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.4957 - acc: 0.9657 - val_loss: 0.1475 - val_acc: 0.9568
Epoch 52/300
121/122 [============================>.] - ETA: 2s - loss: 0.3924 - acc: 0.9671  Epoch 00051: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.3916 - acc: 0.9672 - val_loss: 0.1475 - val_acc: 0.9557
Epoch 53/300
121/122 [============================>.] - ETA: 2s - loss: 0.3670 - acc: 0.9729  Epoch 00052: val_loss improved from 0.14350 to 0.13738, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.052-0.1374.hdf5
122/122 [==============================] - 409s - loss: 0.3660 - acc: 0.9730 - val_loss: 0.1374 - val_acc: 0.9588
Epoch 54/300
121/122 [============================>.] - ETA: 2s - loss: 0.3515 - acc: 0.9729  Epoch 00053: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.3505 - acc: 0.9729 - val_loss: 0.1432 - val_acc: 0.9573
Epoch 55/300
121/122 [============================>.] - ETA: 2s - loss: 0.3317 - acc: 0.9729  Epoch 00054: val_loss improved from 0.13738 to 0.12194, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.054-0.1219.hdf5
122/122 [==============================] - 409s - loss: 0.3355 - acc: 0.9728 - val_loss: 0.1219 - val_acc: 0.9653
Epoch 56/300
121/122 [============================>.] - ETA: 2s - loss: 0.2907 - acc: 0.9753  Epoch 00055: val_loss improved from 0.12194 to 0.12031, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.055-0.1203.hdf5
122/122 [==============================] - 409s - loss: 0.2911 - acc: 0.9753 - val_loss: 0.1203 - val_acc: 0.9651
Epoch 57/300
121/122 [============================>.] - ETA: 2s - loss: 0.2821 - acc: 0.9779  Epoch 00056: val_loss did not improve
122/122 [==============================] - 407s - loss: 0.2814 - acc: 0.9779 - val_loss: 0.1233 - val_acc: 0.9643
Epoch 58/300
121/122 [============================>.] - ETA: 2s - loss: 0.2293 - acc: 0.9798  Epoch 00057: val_loss improved from 0.12031 to 0.11471, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.057-0.1147.hdf5
122/122 [==============================] - 409s - loss: 0.2288 - acc: 0.9798 - val_loss: 0.1147 - val_acc: 0.9661
Epoch 59/300
121/122 [============================>.] - ETA: 2s - loss: 0.2860 - acc: 0.9782  Epoch 00058: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.2866 - acc: 0.9782 - val_loss: 0.1277 - val_acc: 0.9645
Epoch 60/300
121/122 [============================>.] - ETA: 2s - loss: 0.2594 - acc: 0.9791  Epoch 00059: val_loss did not improve
122/122 [==============================] - 407s - loss: 0.2603 - acc: 0.9790 - val_loss: 0.1244 - val_acc: 0.9648
Epoch 61/300
121/122 [============================>.] - ETA: 2s - loss: 0.2018 - acc: 0.9817  Epoch 00060: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.2012 - acc: 0.9817 - val_loss: 0.1156 - val_acc: 0.9666
Epoch 62/300
121/122 [============================>.] - ETA: 2s - loss: 0.2226 - acc: 0.9813  Epoch 00061: val_loss did not improve
122/122 [==============================] - 407s - loss: 0.2220 - acc: 0.9812 - val_loss: 0.1212 - val_acc: 0.9661
Epoch 63/300
121/122 [============================>.] - ETA: 2s - loss: 0.1986 - acc: 0.9821  Epoch 00062: val_loss improved from 0.11471 to 0.11134, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.062-0.1113.hdf5
122/122 [==============================] - 409s - loss: 0.1979 - acc: 0.9821 - val_loss: 0.1113 - val_acc: 0.9689
Epoch 64/300
121/122 [============================>.] - ETA: 2s - loss: 0.1948 - acc: 0.9811  Epoch 00063: val_loss improved from 0.11134 to 0.11031, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.063-0.1103.hdf5
122/122 [==============================] - 408s - loss: 0.1943 - acc: 0.9812 - val_loss: 0.1103 - val_acc: 0.9689
Epoch 65/300
121/122 [============================>.] - ETA: 2s - loss: 0.1844 - acc: 0.9835  Epoch 00064: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1844 - acc: 0.9835 - val_loss: 0.1124 - val_acc: 0.9684
Epoch 66/300
121/122 [============================>.] - ETA: 2s - loss: 0.1747 - acc: 0.9839  Epoch 00065: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1737 - acc: 0.9839 - val_loss: 0.1123 - val_acc: 0.9679
Epoch 67/300
121/122 [============================>.] - ETA: 2s - loss: 0.1703 - acc: 0.9856  Epoch 00066: val_loss improved from 0.11031 to 0.10744, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.066-0.1074.hdf5
122/122 [==============================] - 409s - loss: 0.1698 - acc: 0.9856 - val_loss: 0.1074 - val_acc: 0.9663
Epoch 68/300
121/122 [============================>.] - ETA: 2s - loss: 0.1613 - acc: 0.9838  Epoch 00067: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1607 - acc: 0.9839 - val_loss: 0.1082 - val_acc: 0.9684
Epoch 69/300
121/122 [============================>.] - ETA: 2s - loss: 0.1822 - acc: 0.9863  Epoch 00068: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1821 - acc: 0.9863 - val_loss: 0.1109 - val_acc: 0.9669
Epoch 70/300
121/122 [============================>.] - ETA: 2s - loss: 0.1708 - acc: 0.9846  Epoch 00069: val_loss improved from 0.10744 to 0.10363, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.069-0.1036.hdf5
122/122 [==============================] - 408s - loss: 0.1721 - acc: 0.9847 - val_loss: 0.1036 - val_acc: 0.9713
Epoch 71/300
121/122 [============================>.] - ETA: 2s - loss: 0.1078 - acc: 0.9884  Epoch 00070: val_loss improved from 0.10363 to 0.09960, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.070-0.0996.hdf5
122/122 [==============================] - 408s - loss: 0.1072 - acc: 0.9885 - val_loss: 0.0996 - val_acc: 0.9723
Epoch 72/300
121/122 [============================>.] - ETA: 2s - loss: 0.1476 - acc: 0.9862  Epoch 00071: val_loss improved from 0.09960 to 0.09620, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.071-0.0962.hdf5
122/122 [==============================] - 408s - loss: 0.1466 - acc: 0.9864 - val_loss: 0.0962 - val_acc: 0.9731
Epoch 73/300
121/122 [============================>.] - ETA: 2s - loss: 0.1212 - acc: 0.9884  Epoch 00072: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1210 - acc: 0.9885 - val_loss: 0.0976 - val_acc: 0.9723
Epoch 74/300
121/122 [============================>.] - ETA: 2s - loss: 0.1560 - acc: 0.9870  Epoch 00073: val_loss improved from 0.09620 to 0.09525, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.073-0.0952.hdf5
122/122 [==============================] - 409s - loss: 0.1554 - acc: 0.9871 - val_loss: 0.0952 - val_acc: 0.9749
Epoch 75/300
121/122 [============================>.] - ETA: 2s - loss: 0.1120 - acc: 0.9888  Epoch 00074: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1120 - acc: 0.9887 - val_loss: 0.1073 - val_acc: 0.9715
Epoch 76/300
121/122 [============================>.] - ETA: 2s - loss: 0.1015 - acc: 0.9894  Epoch 00075: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1012 - acc: 0.9894 - val_loss: 0.0979 - val_acc: 0.9731
Epoch 77/300
121/122 [============================>.] - ETA: 2s - loss: 0.1192 - acc: 0.9888  Epoch 00076: val_loss improved from 0.09525 to 0.09442, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.076-0.0944.hdf5
122/122 [==============================] - 408s - loss: 0.1194 - acc: 0.9889 - val_loss: 0.0944 - val_acc: 0.9764
Epoch 78/300
121/122 [============================>.] - ETA: 2s - loss: 0.0943 - acc: 0.9895  Epoch 00077: val_loss improved from 0.09442 to 0.09219, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.077-0.0922.hdf5
122/122 [==============================] - 408s - loss: 0.0939 - acc: 0.9895 - val_loss: 0.0922 - val_acc: 0.9749
Epoch 79/300
121/122 [============================>.] - ETA: 2s - loss: 0.1101 - acc: 0.9896  Epoch 00078: val_loss did not improve
122/122 [==============================] - 408s - loss: 0.1096 - acc: 0.9896 - val_loss: 0.0972 - val_acc: 0.9757
Epoch 80/300
104/122 [========================>.....] - ETA: 53s - loss: 0.0686 - acc: 0.9927 

In [8]:
#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=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=83)


Loading model from checkpoint file ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.082-0.0900.hdf5
Loading model Done!
Epoch 84/300
121/122 [============================>.] - ETA: 2s - loss: 0.0595 - acc: 0.9935   Epoch 00083: val_loss improved from inf to 0.08717, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.083-0.0872.hdf5
122/122 [==============================] - 401s - loss: 0.0594 - acc: 0.9934 - val_loss: 0.0872 - val_acc: 0.9785
Epoch 85/300
121/122 [============================>.] - ETA: 2s - loss: 0.0814 - acc: 0.9913  Epoch 00084: val_loss improved from 0.08717 to 0.08486, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.084-0.0849.hdf5
122/122 [==============================] - 387s - loss: 0.0817 - acc: 0.9914 - val_loss: 0.0849 - val_acc: 0.9790
Epoch 86/300
121/122 [============================>.] - ETA: 2s - loss: 0.0704 - acc: 0.9916  Epoch 00085: val_loss did not improve
122/122 [==============================] - 387s - loss: 0.0699 - acc: 0.9917 - val_loss: 0.0850 - val_acc: 0.9793
Epoch 87/300
121/122 [============================>.] - ETA: 2s - loss: 0.0517 - acc: 0.9927  Epoch 00086: val_loss improved from 0.08486 to 0.08256, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.086-0.0826.hdf5
122/122 [==============================] - 387s - loss: 0.0515 - acc: 0.9928 - val_loss: 0.0826 - val_acc: 0.9811
Epoch 88/300
121/122 [============================>.] - ETA: 2s - loss: 0.1176 - acc: 0.9912  Epoch 00087: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.1173 - acc: 0.9912 - val_loss: 0.0866 - val_acc: 0.9801
Epoch 89/300
121/122 [============================>.] - ETA: 2s - loss: 0.0679 - acc: 0.9925  Epoch 00088: val_loss improved from 0.08256 to 0.07884, saving model to ./resnet50_FT38_Classifier_Rep3/checkpoint/weights.088-0.0788.hdf5
122/122 [==============================] - 387s - loss: 0.0676 - acc: 0.9924 - val_loss: 0.0788 - val_acc: 0.9827
Epoch 90/300
121/122 [============================>.] - ETA: 2s - loss: 0.0641 - acc: 0.9933  Epoch 00089: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0638 - acc: 0.9933 - val_loss: 0.0817 - val_acc: 0.9814
Epoch 91/300
121/122 [============================>.] - ETA: 2s - loss: 0.0885 - acc: 0.9906  Epoch 00090: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0879 - acc: 0.9907 - val_loss: 0.0919 - val_acc: 0.9772
Epoch 92/300
121/122 [============================>.] - ETA: 2s - loss: 0.0717 - acc: 0.9923  Epoch 00091: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0712 - acc: 0.9924 - val_loss: 0.0973 - val_acc: 0.9757
Epoch 93/300
121/122 [============================>.] - ETA: 2s - loss: 0.0993 - acc: 0.9904  Epoch 00092: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0987 - acc: 0.9905 - val_loss: 0.1082 - val_acc: 0.9736
Epoch 94/300
121/122 [============================>.] - ETA: 2s - loss: 0.0686 - acc: 0.9932  Epoch 00093: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0684 - acc: 0.9932 - val_loss: 0.0854 - val_acc: 0.9795
Epoch 95/300
121/122 [============================>.] - ETA: 2s - loss: 0.0559 - acc: 0.9931  Epoch 00094: val_loss did not improve

Epoch 00094: reducing learning rate to 9.99999974738e-07.
122/122 [==============================] - 387s - loss: 0.0558 - acc: 0.9931 - val_loss: 0.0883 - val_acc: 0.9767
Epoch 96/300
121/122 [============================>.] - ETA: 2s - loss: 0.0508 - acc: 0.9938  Epoch 00095: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0505 - acc: 0.9939 - val_loss: 0.0851 - val_acc: 0.9775
Epoch 97/300
121/122 [============================>.] - ETA: 2s - loss: 0.0406 - acc: 0.9953  Epoch 00096: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0404 - acc: 0.9953 - val_loss: 0.0862 - val_acc: 0.9777
Epoch 98/300
121/122 [============================>.] - ETA: 2s - loss: 0.0429 - acc: 0.9941  Epoch 00097: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0429 - acc: 0.9939 - val_loss: 0.0832 - val_acc: 0.9783
Epoch 99/300
121/122 [============================>.] - ETA: 2s - loss: 0.0470 - acc: 0.9942  Epoch 00098: val_loss did not improve
122/122 [==============================] - 386s - loss: 0.0468 - acc: 0.9942 - val_loss: 0.0832 - val_acc: 0.9780
Epoch 100/300
121/122 [============================>.] - ETA: 2s - loss: 0.0346 - acc: 0.9950  Epoch 00099: val_loss did not improve

Epoch 00099: reducing learning rate to 9.99999997475e-08.
122/122 [==============================] - 386s - loss: 0.0344 - acc: 0.9950 - val_loss: 0.0819 - val_acc: 0.9783
Epoch 00099: early stopping
Out[8]:
<keras.callbacks.History at 0x7efb1d94ab50>

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_Rep3/checkpoint/weights.088-0.0788.hdf5
Loading model Done!
train_mean [ 0.41244254  0.45302087  0.41779673]

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

In [11]:
#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_logloss_df.groupby(['class'])['logloss'].mean())
print(valid_logloss_df['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_logloss_df.groupby(['class'])['logloss'].mean())
print(train_logloss_df['logloss'].mean())


3863/3863 [==============================] - 41s     
class
ALB      0.135044
BET      0.519080
DOL      0.665302
LAG      0.000691
NoF      0.045853
OTHER    0.282091
SHARK    0.000237
YFT      0.208891
Name: logloss, dtype: float64
0.0788429576102
15616/15616 [==============================] - 168s     
class
ALB      0.029769
BET      0.007473
DOL      0.000601
LAG      0.000533
NoF      0.016169
OTHER    0.005027
SHARK    0.004082
YFT      0.025846
Name: logloss, dtype: float64
0.0176926563815
class ALB 0.124283 BET 0.442586 DOL 0.678694 LAG 0.000818 NoF 0.061490 OTHER 0.289067 SHARK 0.000414 YFT 0.178863 Name: logloss, dtype: float64 0.0873555796313 class ALB 0.026392 BET 0.003495 DOL 0.001125 LAG 0.002566 NoF 0.026310 OTHER 0.009264 SHARK 0.006521 YFT 0.017942 Name: logloss, dtype: float64 0.0248458333809

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 [6]:
# 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)


Loading from file RFCNbbox_RFCNpred_df_conf0.80.pickle
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 [32]:
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.')


Generating file data_trainfish_Crop_224_224.pickle
Loading data done.
Convert to float32 done.
Rescale by 255 done.

In [33]:
mean(X_trainfish_crop)


Out[33]:
array([ 0.40706199,  0.4373979 ,  0.39489502], dtype=float32)

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


Out[28]:
array([ 0.41078389,  0.43895897,  0.39912957], dtype=float32)

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

In [8]:
# 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)


Loading from file RFCNbbox_RFCNpred_CROPpred_HYBRIDpred_df_weights.000-0.0327.hdf5_.pickle

In [9]:
# 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)


Loading from file test_pred_df_Hybrid_weights.000-0.0327.hdf5_.pickle

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 [11]:
#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 )


image_class
--            NaN
ALB      0.151489
BET      0.204419
DOL      0.141192
LAG      0.052902
NoF      0.125777
OTHER    0.128937
SHARK    0.180230
YFT      0.147513
Name: logloss, dtype: float64
logloss of train is 0.14783966909064958

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)


Done!RFCN_AGONOSTICnms_resnet101_rfcn_ohem_iter_30000_resnet50_FT38_Classifier_Rep_clsMaxAve_conf0.80_T2.5_0.1478.csv

In [ ]: