Fisheries competition

In this notebook we're going to investigate a range of different architectures for the Kaggle fisheries competition. The video states that vgg.py and vgg_ft() from utils.py have been updated to include VGG with batch normalization, but this is not the case. We've instead created a new file vgg_bn.py and an additional method vgg_ft_bn() (which is already in utils.py) which we use in this notebook.


In [1]:
from __future__ import division, print_function
%matplotlib inline
from importlib import reload  # Python 3
import utils; reload(utils)
from utils import *


Using cuDNN version 6021 on context None
Mapped name None to device cuda0: GeForce GTX TITAN X (0000:04:00.0)
Using Theano backend.

Setup dirs

We create the validation and sample sets in the usual way.


In [ ]:
%cd data/fish
%cd train
%mkdir ../valid

In [ ]:
g = glob('*')
for d in g: os.mkdir('../valid/'+d)

g = glob('*/*.jpg')
shuf = np.random.permutation(g)
for i in range(500): os.rename(shuf[i], '../valid/' + shuf[i])

In [ ]:
%mkdir ../sample
%mkdir ../sample/train
%mkdir ../sample/valid

In [ ]:
from shutil import copyfile

g = glob('*')
for d in g: 
    os.mkdir('../sample/train/'+d)
    os.mkdir('../sample/valid/'+d)

In [ ]:
g = glob('*/*.jpg')
shuf = np.random.permutation(g)
for i in range(400): copyfile(shuf[i], '../sample/train/' + shuf[i])

%cd ../valid

g = glob('*/*.jpg')
shuf = np.random.permutation(g)
for i in range(200): copyfile(shuf[i], '../sample/valid/' + shuf[i])

%cd ..

In [ ]:
%mkdir results
%mkdir sample/results
%cd ../..

In [2]:
path = "data/fish/"
#path = "data/fish/sample/"
model_path = path + 'models/'
if not os.path.exists(model_path): os.mkdir(model_path)
#batch_size=64
batch_size=4

In [3]:
batches = get_batches(path+'train', batch_size=batch_size)
val_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False)

(val_classes, trn_classes, val_labels, trn_labels, 
    val_filenames, filenames, test_filenames) = get_classes(path)


Found 3277 images belonging to 8 classes.
Found 500 images belonging to 8 classes.
Found 3277 images belonging to 8 classes.
Found 500 images belonging to 8 classes.
Found 1000 images belonging to 1 classes.

Sometimes it's helpful to have just the filenames, without the path.


In [4]:
raw_filenames = [f.split('/')[-1] for f in filenames]
raw_test_filenames = [f.split('/')[-1] for f in test_filenames]
raw_val_filenames = [f.split('/')[-1] for f in val_filenames]

Basic VGG

We start with our usual VGG approach. We will be using VGG with batch normalization. We explained how to add batch normalization to VGG in the imagenet_batchnorm notebook. VGG with batch normalization is implemented in vgg_bn.py, and there is a version of vgg_ft (our fine tuning function) with batch norm called vgg_ft_bn in utils.py.

Initial model

First we create a simple fine-tuned VGG model to be our starting point.


In [5]:
from vgg16bn import Vgg16BN
model = vgg_ft_bn(8)

In [6]:
trn = get_data(path+'train')
val = get_data(path+'valid')


Found 3277 images belonging to 8 classes.
Found 500 images belonging to 8 classes.

In [7]:
test = get_data(path+'test')


Found 1000 images belonging to 1 classes.

In [8]:
save_array(path+'results/trn.dat', trn)
save_array(path+'results/val.dat', val)

In [9]:
save_array(path+'results/test.dat', test)

In [10]:
trn = load_array(path+'results/trn.dat')
val = load_array(path+'results/val.dat')

In [11]:
test = load_array(path+'results/test.dat')

In [12]:
gen = image.ImageDataGenerator()

In [13]:
model.compile(optimizer=Adam(1e-3),
       loss='categorical_crossentropy', metrics=['accuracy'])

In [14]:
model.fit(trn, trn_labels, batch_size=batch_size, epochs=3, validation_data=(val, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/3
3277/3277 [==============================] - 37s 11ms/step - loss: 3.9257 - acc: 0.4644 - val_loss: 2.4930 - val_acc: 0.7300
Epoch 2/3
3277/3277 [==============================] - 38s 12ms/step - loss: 3.4486 - acc: 0.5639 - val_loss: 2.0932 - val_acc: 0.7700
Epoch 3/3
3277/3277 [==============================] - 40s 12ms/step - loss: 3.6786 - acc: 0.5777 - val_loss: 2.3186 - val_acc: 0.7720
Out[14]:
<keras.callbacks.History at 0x7fe7260cde48>

In [15]:
model.save_weights(path+'results/ft1.h5')

Precompute convolutional output

We pre-compute the output of the last convolution layer of VGG, since we're unlikely to need to fine-tune those layers. (All following analysis will be done on just the pre-computed convolutional features.)


In [16]:
model.load_weights(path+'results/ft1.h5')

In [17]:
conv_layers,fc_layers = split_at(model, Conv2D)

In [18]:
conv_model = Sequential(conv_layers)

In [19]:
conv_feat = conv_model.predict(trn)
conv_val_feat = conv_model.predict(val)

In [20]:
conv_test_feat = conv_model.predict(test)

In [21]:
save_array(path+'results/conv_val_feat.dat', conv_val_feat)
save_array(path+'results/conv_feat.dat', conv_feat)

In [22]:
save_array(path+'results/conv_test_feat.dat', conv_test_feat)

In [23]:
conv_feat = load_array(path+'results/conv_feat.dat')
conv_val_feat = load_array(path+'results/conv_val_feat.dat')

In [24]:
conv_test_feat = load_array(path+'results/conv_test_feat.dat')

In [25]:
conv_val_feat.shape


Out[25]:
(500, 512, 14, 14)

Train model

We can now create our first baseline model - a simple 3-layer FC net.


In [26]:
def get_bn_layers(p):
    return [
        MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
        BatchNormalization(axis=1),
        Dropout(p/4),
        Flatten(),
        Dense(512, activation='relu'),
        BatchNormalization(),
        Dropout(p),
        Dense(512, activation='relu'),
        BatchNormalization(),
        Dropout(p/2),
        Dense(8, activation='softmax')
    ]

In [27]:
p=0.6

In [28]:
bn_model = Sequential(get_bn_layers(p))
bn_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

In [29]:
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, epochs=3, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/3
3277/3277 [==============================] - 5s 1ms/step - loss: 1.5760 - acc: 0.5188 - val_loss: 0.7266 - val_acc: 0.8040
Epoch 2/3
3277/3277 [==============================] - 5s 1ms/step - loss: 0.9914 - acc: 0.6778 - val_loss: 0.4822 - val_acc: 0.8420
Epoch 3/3
3277/3277 [==============================] - 5s 1ms/step - loss: 0.7669 - acc: 0.7492 - val_loss: 0.4854 - val_acc: 0.8580
Out[29]:
<keras.callbacks.History at 0x7fe6febfc4a8>

In [30]:
bn_model.optimizer.lr = 1e-4

In [31]:
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, epochs=7, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.7059 - acc: 0.7653 - val_loss: 0.3493 - val_acc: 0.9000
Epoch 2/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.6098 - acc: 0.7913 - val_loss: 0.1816 - val_acc: 0.9460
Epoch 3/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.5225 - acc: 0.8227 - val_loss: 0.1861 - val_acc: 0.9600
Epoch 4/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.4977 - acc: 0.8361 - val_loss: 0.1854 - val_acc: 0.9400
Epoch 5/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.4303 - acc: 0.8572 - val_loss: 0.1740 - val_acc: 0.9520
Epoch 6/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.4181 - acc: 0.8624 - val_loss: 0.1647 - val_acc: 0.9620
Epoch 7/7
3277/3277 [==============================] - 5s 1ms/step - loss: 0.4063 - acc: 0.8651 - val_loss: 0.1483 - val_acc: 0.9620
Out[31]:
<keras.callbacks.History at 0x7fe6fa715908>

In [32]:
bn_model.save_weights(path+'models/conv_512_6.h5')

In [33]:
bn_model.evaluate(conv_val_feat, val_labels)


500/500 [==============================] - 0s 176us/step
Out[33]:
[0.14833525647222995, 0.96199999952316284]

In [34]:
bn_model.load_weights(path+'models/conv_512_6.h5')

Multi-input

The images are of different sizes, which are likely to represent the boat they came from (since different boats will use different cameras). Perhaps this creates some data leakage that we can take advantage of to get a better Kaggle leaderboard position? To find out, first we create arrays of the file sizes for each image:


In [35]:
sizes = [PIL.Image.open(path+'train/'+f).size for f in filenames]
id2size = list(set(sizes))
size2id = {o:i for i,o in enumerate(id2size)}

In [36]:
import collections
collections.Counter(sizes)


Out[36]:
Counter({(1192, 670): 179,
         (1244, 700): 24,
         (1276, 718): 187,
         (1280, 720): 1900,
         (1280, 750): 509,
         (1280, 924): 49,
         (1280, 974): 333,
         (1334, 750): 29,
         (1518, 854): 35,
         (1732, 974): 32})

Then we one-hot encode them (since we want to treat them as categorical) and normalize the data.


In [37]:
trn_sizes_orig = to_categorical([size2id[o] for o in sizes], len(id2size))

In [38]:
raw_val_sizes = [PIL.Image.open(path+'valid/'+f).size for f in val_filenames]
val_sizes = to_categorical([size2id[o] for o in raw_val_sizes], len(id2size))

In [39]:
trn_sizes = trn_sizes_orig-trn_sizes_orig.mean(axis=0)/trn_sizes_orig.std(axis=0)
val_sizes = val_sizes-trn_sizes_orig.mean(axis=0)/trn_sizes_orig.std(axis=0)

To use this additional "meta-data", we create a model with multiple input layers - sz_inp will be our input for the size information.


In [40]:
p=0.6

In [41]:
inp = Input(conv_layers[-1].output_shape[1:])
sz_inp = Input((len(id2size),))
bn_inp = BatchNormalization()(sz_inp)

x = MaxPooling2D()(inp)
x = BatchNormalization(axis=1)(x)
x = Dropout(p/4)(x)
x = Flatten()(x)
x = Dense(512, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(p)(x)
x = Dense(512, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(p/2)(x)
x = concatenate([x,bn_inp], axis=-1)
x = Dense(8, activation='softmax')(x)

When we compile the model, we have to specify all the input layers in an array.


In [42]:
model = Model([inp, sz_inp], x)
model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

And when we train the model, we have to provide all the input layers' data in an array.


In [43]:
model.fit([conv_feat, trn_sizes], trn_labels, batch_size=batch_size, epochs=3, 
             validation_data=([conv_val_feat, val_sizes], val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/3
3277/3277 [==============================] - 6s 2ms/step - loss: 1.6118 - acc: 0.4959 - val_loss: 0.6307 - val_acc: 0.7900
Epoch 2/3
3277/3277 [==============================] - 5s 2ms/step - loss: 0.9926 - acc: 0.6802 - val_loss: 0.4075 - val_acc: 0.9040
Epoch 3/3
3277/3277 [==============================] - 5s 2ms/step - loss: 0.7922 - acc: 0.7363 - val_loss: 0.4023 - val_acc: 0.8940
Out[43]:
<keras.callbacks.History at 0x7fe6f9888668>

In [44]:
bn_model.optimizer.lr = 1e-4

In [45]:
bn_model.fit(conv_feat, trn_labels, batch_size=batch_size, epochs=8, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.3631 - acc: 0.8731 - val_loss: 0.1572 - val_acc: 0.9560
Epoch 2/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.3434 - acc: 0.8901 - val_loss: 0.1620 - val_acc: 0.9480
Epoch 3/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.3195 - acc: 0.8874 - val_loss: 0.1522 - val_acc: 0.9560
Epoch 4/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.3192 - acc: 0.8953 - val_loss: 0.1497 - val_acc: 0.9620
Epoch 5/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.3041 - acc: 0.8999 - val_loss: 0.1678 - val_acc: 0.9580
Epoch 6/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.2948 - acc: 0.9017 - val_loss: 0.1225 - val_acc: 0.9600
Epoch 7/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.2868 - acc: 0.9045 - val_loss: 0.1491 - val_acc: 0.9620
Epoch 8/8
3277/3277 [==============================] - 5s 2ms/step - loss: 0.2704 - acc: 0.9112 - val_loss: 0.1286 - val_acc: 0.9720
Out[45]:
<keras.callbacks.History at 0x7fe6f8986080>

The model did not show an improvement by using the leakage, other than in the early epochs. This is most likely because the information about what boat the picture came from is readily identified from the image itself, so the meta-data turned out not to add any additional information.

Bounding boxes & multi output

Import / view bounding boxes

A kaggle user has created bounding box annotations for each fish in each training set image. You can download them from here. We will see if we can utilize this additional information. First, we'll load in the data, and keep just the largest bounding box for each image.


In [46]:
import ujson as json

In [47]:
anno_classes = ['alb', 'bet', 'dol', 'lag', 'other', 'shark', 'yft']

In [48]:
bb_json = {}
for c in anno_classes:
    j = json.load(open('{}annos/{}_labels.json'.format(path, c), 'r'))
    for l in j:
        if 'annotations' in l.keys() and len(l['annotations'])>0:
            bb_json[l['filename'].split('/')[-1]] = sorted(
                l['annotations'], key=lambda x: x['height']*x['width'])[-1]

In [49]:
bb_json['img_04908.jpg']


Out[49]:
{'class': 'rect',
 'height': 246.75000000000074,
 'width': 432.8700000000013,
 'x': 465.3000000000014,
 'y': 496.32000000000147}

In [50]:
file2idx = {o:i for i,o in enumerate(raw_filenames)}
val_file2idx = {o:i for i,o in enumerate(raw_val_filenames)}

For any images that have no annotations, we'll create an empty bounding box.


In [51]:
empty_bbox = {'height': 0., 'width': 0., 'x': 0., 'y': 0.}

In [52]:
for f in raw_filenames:
    if not f in bb_json.keys(): bb_json[f] = empty_bbox
for f in raw_val_filenames:
    if not f in bb_json.keys(): bb_json[f] = empty_bbox

Finally, we convert the dictionary into an array, and convert the coordinates to our resized 224x224 images.


In [53]:
bb_params = ['height', 'width', 'x', 'y']
def convert_bb(bb, size):
    bb = [bb[p] for p in bb_params]
    conv_x = (224. / size[0])
    conv_y = (224. / size[1])
    bb[0] = bb[0]*conv_y
    bb[1] = bb[1]*conv_x
    bb[2] = max(bb[2]*conv_x, 0)
    bb[3] = max(bb[3]*conv_y, 0)
    return bb

In [54]:
trn_bbox = np.stack([convert_bb(bb_json[f], s) for f,s in zip(raw_filenames, sizes)], 
                   ).astype(np.float32)
val_bbox = np.stack([convert_bb(bb_json[f], s) 
                   for f,s in zip(raw_val_filenames, raw_val_sizes)]).astype(np.float32)

Now we can check our work by drawing one of the annotations.


In [55]:
def create_rect(bb, color='red'):
    return plt.Rectangle((bb[2], bb[3]), bb[1], bb[0], color=color, fill=False, lw=3)

def show_bb(i):
    bb = val_bbox[i]
    plot(val[i])
    plt.gca().add_patch(create_rect(bb))

In [56]:
show_bb(0)


Create & train model

Since we're not allowed (by the kaggle rules) to manually annotate the test set, we'll need to create a model that predicts the locations of the bounding box on each image. To do so, we create a model with multiple outputs: it will predict both the type of fish (the 'class'), and the 4 bounding box coordinates. We prefer this approach to only predicting the bounding box coordinates, since we hope that giving the model more context about what it's looking for will help it with both tasks.


In [57]:
p=0.6

In [58]:
inp = Input(conv_layers[-1].output_shape[1:])
x = MaxPooling2D()(inp)
x = BatchNormalization(axis=1)(x)
x = Dropout(p/4)(x)
x = Flatten()(x)
x = Dense(512, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(p)(x)
x = Dense(512, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(p/2)(x)
x_bb = Dense(4, name='bb')(x)
x_class = Dense(8, activation='softmax', name='class')(x)

Since we have multiple outputs, we need to provide them to the model constructor in an array, and we also need to say what loss function to use for each. We also weight the bounding box loss function down by 1000x since the scale of the cross-entropy loss and the MSE is very different.


In [59]:
model = Model([inp], [x_bb, x_class])
model.compile(Adam(lr=0.001), loss=['mse', 'categorical_crossentropy'], metrics=['accuracy'],
             loss_weights=[.001, 1.])

In [60]:
model.fit(conv_feat, [trn_bbox, trn_labels], batch_size=batch_size, epochs=3, 
             validation_data=(conv_val_feat, [val_bbox, val_labels]))


Train on 3277 samples, validate on 500 samples
Epoch 1/3
3277/3277 [==============================] - 5s 2ms/step - loss: 5.8143 - bb_loss: 4172.2165 - class_loss: 1.6421 - bb_acc: 0.4681 - class_acc: 0.4968 - val_loss: 2.9193 - val_bb_loss: 1994.5001 - val_class_loss: 0.9248 - val_bb_acc: 0.5720 - val_class_acc: 0.7380
Epoch 2/3
3277/3277 [==============================] - 5s 2ms/step - loss: 2.2240 - bb_loss: 1217.7754 - class_loss: 1.0062 - bb_acc: 0.5914 - class_acc: 0.6710 - val_loss: 1.0859 - val_bb_loss: 567.0876 - val_class_loss: 0.5188 - val_bb_acc: 0.6760 - val_class_acc: 0.8280
Epoch 3/3
3277/3277 [==============================] - 5s 2ms/step - loss: 1.6619 - bb_loss: 845.2676 - class_loss: 0.8167 - bb_acc: 0.6164 - class_acc: 0.7263 - val_loss: 0.8365 - val_bb_loss: 524.5868 - val_class_loss: 0.3120 - val_bb_acc: 0.6920 - val_class_acc: 0.9040
Out[60]:
<keras.callbacks.History at 0x7fe6f00d4240>

In [61]:
model.optimizer.lr = 1e-5

In [62]:
model.fit(conv_feat, [trn_bbox, trn_labels], batch_size=batch_size, epochs=10, 
             validation_data=(conv_val_feat, [val_bbox, val_labels]))


Train on 3277 samples, validate on 500 samples
Epoch 1/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.4867 - bb_loss: 824.1590 - class_loss: 0.6625 - bb_acc: 0.6250 - class_acc: 0.7751 - val_loss: 0.7238 - val_bb_loss: 461.5646 - val_class_loss: 0.2622 - val_bb_acc: 0.6980 - val_class_acc: 0.9180
Epoch 2/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.4358 - bb_loss: 802.6221 - class_loss: 0.6332 - bb_acc: 0.6369 - class_acc: 0.7998 - val_loss: 0.7274 - val_bb_loss: 467.7118 - val_class_loss: 0.2597 - val_bb_acc: 0.7200 - val_class_acc: 0.9300
Epoch 3/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.3145 - bb_loss: 760.2161 - class_loss: 0.5543 - bb_acc: 0.6295 - class_acc: 0.8172 - val_loss: 0.6100 - val_bb_loss: 425.0035 - val_class_loss: 0.1850 - val_bb_acc: 0.6900 - val_class_acc: 0.9400
Epoch 4/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.3107 - bb_loss: 769.7151 - class_loss: 0.5410 - bb_acc: 0.6326 - class_acc: 0.8120 - val_loss: 0.6081 - val_bb_loss: 407.0788 - val_class_loss: 0.2010 - val_bb_acc: 0.7380 - val_class_acc: 0.9580
Epoch 5/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.1868 - bb_loss: 741.6034 - class_loss: 0.4452 - bb_acc: 0.6478 - class_acc: 0.8499 - val_loss: 0.6411 - val_bb_loss: 391.5067 - val_class_loss: 0.2496 - val_bb_acc: 0.7380 - val_class_acc: 0.9360
Epoch 6/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.1249 - bb_loss: 708.4818 - class_loss: 0.4164 - bb_acc: 0.6460 - class_acc: 0.8645 - val_loss: 0.6000 - val_bb_loss: 367.0677 - val_class_loss: 0.2329 - val_bb_acc: 0.7320 - val_class_acc: 0.9360
Epoch 7/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.0983 - bb_loss: 690.8757 - class_loss: 0.4074 - bb_acc: 0.6524 - class_acc: 0.8648 - val_loss: 0.5984 - val_bb_loss: 382.2247 - val_class_loss: 0.2162 - val_bb_acc: 0.7420 - val_class_acc: 0.9420
Epoch 8/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.0612 - bb_loss: 682.7924 - class_loss: 0.3784 - bb_acc: 0.6576 - class_acc: 0.8822 - val_loss: 0.5070 - val_bb_loss: 357.6869 - val_class_loss: 0.1494 - val_bb_acc: 0.7580 - val_class_acc: 0.9680
Epoch 9/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.0093 - bb_loss: 643.7483 - class_loss: 0.3656 - bb_acc: 0.6643 - class_acc: 0.8782 - val_loss: 0.5383 - val_bb_loss: 355.2063 - val_class_loss: 0.1831 - val_bb_acc: 0.7420 - val_class_acc: 0.9660
Epoch 10/10
3277/3277 [==============================] - 5s 2ms/step - loss: 1.0265 - bb_loss: 667.7229 - class_loss: 0.3588 - bb_acc: 0.6485 - class_acc: 0.8911 - val_loss: 0.5082 - val_bb_loss: 338.3510 - val_class_loss: 0.1698 - val_bb_acc: 0.7580 - val_class_acc: 0.9660
Out[62]:
<keras.callbacks.History at 0x7fe6efe58710>

Excitingly, it turned out that the classification model is much improved by giving it this additional task. Let's see how well the bounding box model did by taking a look at its output.


In [63]:
pred = model.predict(conv_val_feat[0:10])

In [64]:
def show_bb_pred(i):
    bb = val_bbox[i]
    bb_pred = pred[0][i]
    plt.figure(figsize=(6,6))
    plot(val[i])
    ax=plt.gca()
    ax.add_patch(create_rect(bb_pred, 'yellow'))
    ax.add_patch(create_rect(bb))

The image shows that it can find fish that are tricky for us to see!


In [65]:
show_bb_pred(6)



In [66]:
model.evaluate(conv_val_feat, [val_bbox, val_labels])


500/500 [==============================] - 0s 144us/step
Out[66]:
[0.50815983188152314,
 338.35100415039062,
 0.16980881087481975,
 0.75799999952316288,
 0.96599999999999997]

In [67]:
model.save_weights(path+'models/bn_anno.h5')

In [68]:
model.load_weights(path+'models/bn_anno.h5')

Larger size

Set up data

Let's see if we get better results if we use larger images. We'll use 640x360, since it's the same shape as the most common size we saw earlier (1280x720), without being too big.


In [69]:
trn = get_data(path+'train', (360,640))
val = get_data(path+'valid', (360,640))


Found 3277 images belonging to 8 classes.
Found 500 images belonging to 8 classes.

The image shows that things are much clearer at this size.


In [70]:
plot(trn[0])



In [71]:
test = get_data(path+'test', (360,640))


Found 1000 images belonging to 1 classes.

In [72]:
save_array(path+'results/trn_640.dat', trn)
save_array(path+'results/val_640.dat', val)

In [73]:
save_array(path+'results/test_640.dat', test)

In [74]:
trn = load_array(path+'results/trn_640.dat')
val = load_array(path+'results/val_640.dat')

We can now create our VGG model - we'll need to tell it we're not using the normal 224x224 images, which also means it won't include the fully connected layers (since they don't make sense for non-default sizes). We will also remove the last max pooling layer, since we don't want to throw away information yet.


In [75]:
vgg640 = Vgg16BN((360, 640)).model
vgg640.pop()
vgg640.input_shape, vgg640.output_shape
vgg640.compile(Adam(), 'categorical_crossentropy', metrics=['accuracy'])

We can now pre-compute the output of the convolutional part of VGG.


In [76]:
conv_val_feat = vgg640.predict(val, batch_size=batch_size, verbose=1)
conv_trn_feat = vgg640.predict(trn, batch_size=batch_size, verbose=1)


500/500 [==============================] - 17s 35ms/step
3277/3277 [==============================] - 121s 37ms/step

In [77]:
save_array(path+'results/conv_val_640.dat', conv_val_feat)
save_array(path+'results/conv_trn_640.dat', conv_trn_feat)

In [78]:
conv_test_feat = vgg640.predict(test, batch_size=batch_size, verbose=1)


1000/1000 [==============================] - 37s 37ms/step

In [79]:
save_array(path+'results/conv_test_640.dat', conv_test_feat)

In [80]:
conv_val_feat = load_array(path+'results/conv_val_640.dat')
conv_trn_feat = load_array(path+'results/conv_trn_640.dat')

In [81]:
conv_test_feat = load_array(path+'results/conv_test_640.dat')

Fully convolutional net (FCN)

Since we're using a larger input, the output of the final convolutional layer is also larger. So we probably don't want to put a dense layer there - that would be a lot of parameters! Instead, let's use a fully convolutional net (FCN); this also has the benefit that they tend to generalize well, and also seems like a good fit for our problem (since the fish are a small part of the image).


In [82]:
conv_layers,_ = split_at(vgg640, Convolution2D)

I'm not using any dropout, since I found I got better results without it.


In [83]:
nf=128; p=0.

In [84]:
def get_lrg_layers():
    return [
        BatchNormalization(axis=1, input_shape=conv_layers[-1].output_shape[1:]),
        Conv2D(nf,(3,3), activation='relu', padding='same'),
        BatchNormalization(axis=1),
        MaxPooling2D(),
        Conv2D(nf,(3,3), activation='relu', padding='same'),
        BatchNormalization(axis=1),
        MaxPooling2D(),
        Conv2D(nf,(3,3), activation='relu', padding='same'),
        BatchNormalization(axis=1),
        MaxPooling2D((1,2)),
        Conv2D(8,(3,3), padding='same'),
        Dropout(p),
        GlobalAveragePooling2D(),
        Activation('softmax')
    ]

In [85]:
lrg_model = Sequential(get_lrg_layers())

In [86]:
lrg_model.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
batch_normalization_13 (Batc (None, 512, 22, 40)       2048      
_________________________________________________________________
conv2d_27 (Conv2D)           (None, 128, 22, 40)       589952    
_________________________________________________________________
batch_normalization_14 (Batc (None, 128, 22, 40)       512       
_________________________________________________________________
max_pooling2d_14 (MaxPooling (None, 128, 11, 20)       0         
_________________________________________________________________
conv2d_28 (Conv2D)           (None, 128, 11, 20)       147584    
_________________________________________________________________
batch_normalization_15 (Batc (None, 128, 11, 20)       512       
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 128, 5, 10)        0         
_________________________________________________________________
conv2d_29 (Conv2D)           (None, 128, 5, 10)        147584    
_________________________________________________________________
batch_normalization_16 (Batc (None, 128, 5, 10)        512       
_________________________________________________________________
max_pooling2d_16 (MaxPooling (None, 128, 5, 5)         0         
_________________________________________________________________
conv2d_30 (Conv2D)           (None, 8, 5, 5)           9224      
_________________________________________________________________
dropout_12 (Dropout)         (None, 8, 5, 5)           0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 8)                 0         
_________________________________________________________________
activation_1 (Activation)    (None, 8)                 0         
=================================================================
Total params: 897,928
Trainable params: 896,136
Non-trainable params: 1,792
_________________________________________________________________

In [87]:
lrg_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

In [88]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=2, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/2
3277/3277 [==============================] - 11s 3ms/step - loss: 0.8285 - acc: 0.7296 - val_loss: 0.3240 - val_acc: 0.8800
Epoch 2/2
3277/3277 [==============================] - 11s 3ms/step - loss: 0.2611 - acc: 0.9237 - val_loss: 0.2912 - val_acc: 0.9260
Out[88]:
<keras.callbacks.History at 0x7fe6ef64afd0>

In [89]:
lrg_model.optimizer.lr=1e-5

In [90]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=6, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/6
3277/3277 [==============================] - 11s 3ms/step - loss: 0.1354 - acc: 0.9576 - val_loss: 0.1807 - val_acc: 0.9420
Epoch 2/6
3277/3277 [==============================] - 11s 3ms/step - loss: 0.1005 - acc: 0.9686 - val_loss: 0.3039 - val_acc: 0.9380
Epoch 3/6
3277/3277 [==============================] - 11s 3ms/step - loss: 0.0646 - acc: 0.9817 - val_loss: 0.2416 - val_acc: 0.9380
Epoch 4/6
3277/3277 [==============================] - 11s 3ms/step - loss: 0.0707 - acc: 0.9783 - val_loss: 0.2957 - val_acc: 0.9160
Epoch 5/6
3277/3277 [==============================] - 10s 3ms/step - loss: 0.0717 - acc: 0.9774 - val_loss: 0.1843 - val_acc: 0.9580
Epoch 6/6
3277/3277 [==============================] - 10s 3ms/step - loss: 0.0342 - acc: 0.9902 - val_loss: 0.1997 - val_acc: 0.9520
Out[90]:
<keras.callbacks.History at 0x7fe750834438>

When I submitted the results of this model to Kaggle, I got the best single model results of any shown here (ranked 22nd on the leaderboard as at Dec-6-2016.)


In [91]:
lrg_model.save_weights(path+'models/lrg_nmp.h5')

In [92]:
lrg_model.load_weights(path+'models/lrg_nmp.h5')

In [93]:
lrg_model.evaluate(conv_val_feat, val_labels)


500/500 [==============================] - 0s 876us/step
Out[93]:
[0.19972862920165063, 0.95199999999999996]

Another benefit of this kind of model is that the last convolutional layer has to learn to classify each part of the image (since there's only an average pooling layer after). Let's create a function that grabs the output of this layer (which is the 4th-last layer of our model).


In [94]:
l = lrg_model.layers
conv_fn = K.function([l[0].input, K.learning_phase()], l[-4].output)

In [95]:
def get_cm(imp, label):
    conv = conv_fn([inp,0])[0, label]
    return scipy.misc.imresize(conv, (360,640), interp='nearest')

We have to add an extra dimension to our input since the CNN expects a 'batch' (even if it's just a batch of one).


In [96]:
inp = np.expand_dims(conv_val_feat[0], 0)
np.round(lrg_model.predict(inp)[0],2)


Out[96]:
array([ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.], dtype=float32)

In [97]:
plt.imshow(to_plot(val[0]))


Out[97]:
<matplotlib.image.AxesImage at 0x7fe74b4f9d30>

In [98]:
cm = get_cm(inp, 0)


/home/roebius/anaconda/envs/f1/lib/python3.5/site-packages/ipykernel_launcher.py:3: DeprecationWarning: `imresize` is deprecated!
`imresize` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use ``skimage.transform.resize`` instead.
  This is separate from the ipykernel package so we can avoid doing imports until

The heatmap shows that (at very low resolution) the model is finding the fish!


In [99]:
plt.imshow(cm, cmap="cool")


Out[99]:
<matplotlib.image.AxesImage at 0x7fe74b4b56a0>

All convolutional net heatmap

To create a higher resolution heatmap, we'll remove all the max pooling layers, and repeat the previous steps.


In [100]:
def get_lrg_layers():
    return [
        BatchNormalization(axis=1, input_shape=conv_layers[-1].output_shape[1:]),
        Conv2D(nf,(3,3), activation='relu', padding='same'),
        BatchNormalization(axis=1),
        Conv2D(nf,(3,3), activation='relu', padding='same'),
        BatchNormalization(axis=1),
        Conv2D(nf,(3,3), activation='relu', padding='same'),
        BatchNormalization(axis=1),
        Conv2D(8,(3,3), padding='same'),
        GlobalAveragePooling2D(),
        Activation('softmax')
    ]

In [101]:
lrg_model = Sequential(get_lrg_layers())

In [102]:
lrg_model.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
batch_normalization_17 (Batc (None, 512, 22, 40)       2048      
_________________________________________________________________
conv2d_31 (Conv2D)           (None, 128, 22, 40)       589952    
_________________________________________________________________
batch_normalization_18 (Batc (None, 128, 22, 40)       512       
_________________________________________________________________
conv2d_32 (Conv2D)           (None, 128, 22, 40)       147584    
_________________________________________________________________
batch_normalization_19 (Batc (None, 128, 22, 40)       512       
_________________________________________________________________
conv2d_33 (Conv2D)           (None, 128, 22, 40)       147584    
_________________________________________________________________
batch_normalization_20 (Batc (None, 128, 22, 40)       512       
_________________________________________________________________
conv2d_34 (Conv2D)           (None, 8, 22, 40)         9224      
_________________________________________________________________
global_average_pooling2d_2 ( (None, 8)                 0         
_________________________________________________________________
activation_2 (Activation)    (None, 8)                 0         
=================================================================
Total params: 897,928
Trainable params: 896,136
Non-trainable params: 1,792
_________________________________________________________________

In [103]:
lrg_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

In [104]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=2, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/2
3277/3277 [==============================] - 14s 4ms/step - loss: 1.1088 - acc: 0.6372 - val_loss: 0.4324 - val_acc: 0.8800
Epoch 2/2
3277/3277 [==============================] - 13s 4ms/step - loss: 0.5384 - acc: 0.8218 - val_loss: 0.2910 - val_acc: 0.9120
Out[104]:
<keras.callbacks.History at 0x7fe74a14b908>

In [105]:
lrg_model.optimizer.lr=1e-5

In [106]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=6, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/6
3277/3277 [==============================] - 14s 4ms/step - loss: 0.3699 - acc: 0.8819 - val_loss: 0.1349 - val_acc: 0.9620
Epoch 2/6
3277/3277 [==============================] - 14s 4ms/step - loss: 0.2765 - acc: 0.9112 - val_loss: 0.2093 - val_acc: 0.9360
Epoch 3/6
3277/3277 [==============================] - 14s 4ms/step - loss: 0.2052 - acc: 0.9332 - val_loss: 0.1471 - val_acc: 0.9580
Epoch 4/6
3277/3277 [==============================] - 14s 4ms/step - loss: 0.1682 - acc: 0.9475 - val_loss: 0.2683 - val_acc: 0.9240
Epoch 5/6
3277/3277 [==============================] - 14s 4ms/step - loss: 0.1655 - acc: 0.9503 - val_loss: 0.2633 - val_acc: 0.9340
Epoch 6/6
3277/3277 [==============================] - 14s 4ms/step - loss: 0.1462 - acc: 0.9573 - val_loss: 0.1858 - val_acc: 0.9540
Out[106]:
<keras.callbacks.History at 0x7fe74a04ef28>

In [107]:
lrg_model.save_weights(path+'models/lrg_0mp.h5')

In [108]:
lrg_model.load_weights(path+'models/lrg_0mp.h5')

Create heatmap


In [109]:
l = lrg_model.layers
conv_fn = K.function([l[0].input, K.learning_phase()], l[-3].output)

In [110]:
def get_cm2(imp, label):
    conv = conv_fn([inp,0])[0, label]
    return scipy.misc.imresize(conv, (360,640))

In [111]:
inp = np.expand_dims(conv_val_feat[0], 0)

In [112]:
plt.imshow(to_plot(val[0]))


Out[112]:
<matplotlib.image.AxesImage at 0x7fe74b96fac8>

In [113]:
cm = get_cm2(inp, 0)


/home/roebius/anaconda/envs/f1/lib/python3.5/site-packages/ipykernel_launcher.py:3: DeprecationWarning: `imresize` is deprecated!
`imresize` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use ``skimage.transform.resize`` instead.
  This is separate from the ipykernel package so we can avoid doing imports until

In [114]:
cm = get_cm2(inp, 4)


/home/roebius/anaconda/envs/f1/lib/python3.5/site-packages/ipykernel_launcher.py:3: DeprecationWarning: `imresize` is deprecated!
`imresize` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use ``skimage.transform.resize`` instead.
  This is separate from the ipykernel package so we can avoid doing imports until

In [115]:
plt.imshow(cm, cmap="cool")


Out[115]:
<matplotlib.image.AxesImage at 0x7fe749d66cf8>

In [116]:
plt.figure(figsize=(10,10))
plot(val[0])
plt.imshow(cm, cmap="cool", alpha=0.5)


Out[116]:
<matplotlib.image.AxesImage at 0x7fe749d76cc0>

Inception mini-net

Here's an example of how to create and use "inception blocks" - as you see, they use multiple different convolution filter sizes and concatenate the results together. We'll talk more about these next year.


In [117]:
def conv2d_bn(x, nb_filter, nb_row, nb_col, subsample=(1, 1)):
    x = Conv2D(nb_filter, (nb_row, nb_col),
                      activation='relu', padding='same', strides=subsample)(x)
    return BatchNormalization(axis=1)(x)

In [118]:
def incep_block(x):
    branch1x1 = conv2d_bn(x, 32, 1, 1, subsample=(2, 2))
    branch5x5 = conv2d_bn(x, 24, 1, 1)
    branch5x5 = conv2d_bn(branch5x5, 32, 5, 5, subsample=(2, 2))

    branch3x3dbl = conv2d_bn(x, 32, 1, 1)
    branch3x3dbl = conv2d_bn(branch3x3dbl, 48, 3, 3)
    branch3x3dbl = conv2d_bn(branch3x3dbl, 48, 3, 3, subsample=(2, 2))

    branch_pool = AveragePooling2D(
        (3, 3), strides=(2, 2), padding='same')(x)
    branch_pool = conv2d_bn(branch_pool, 16, 1, 1)
    return concatenate([branch1x1, branch5x5, branch3x3dbl, branch_pool], axis=1)

In [119]:
inp = Input(vgg640.layers[-1].output_shape[1:]) 
x = BatchNormalization(axis=1)(inp)
x = incep_block(x)
x = incep_block(x)
x = incep_block(x)
x = Dropout(0.75)(x)
x = Conv2D(8,(3,3), padding='same')(x)
x = GlobalAveragePooling2D()(x)
outp = Activation('softmax')(x)

In [120]:
lrg_model = Model([inp], outp)

In [121]:
lrg_model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

In [122]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=2, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/2
3277/3277 [==============================] - 25s 8ms/step - loss: 1.1642 - acc: 0.6085 - val_loss: 0.4564 - val_acc: 0.8560
Epoch 2/2
3277/3277 [==============================] - 25s 8ms/step - loss: 0.5463 - acc: 0.8239 - val_loss: 0.2746 - val_acc: 0.9220
Out[122]:
<keras.callbacks.History at 0x7fe74793d4e0>

In [123]:
lrg_model.optimizer.lr=1e-5

In [124]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=6, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/6
3277/3277 [==============================] - 25s 8ms/step - loss: 0.3156 - acc: 0.9045 - val_loss: 0.1866 - val_acc: 0.9440
Epoch 2/6
3277/3277 [==============================] - 25s 8ms/step - loss: 0.2062 - acc: 0.9356 - val_loss: 0.1666 - val_acc: 0.9540
Epoch 3/6
3277/3277 [==============================] - 25s 8ms/step - loss: 0.1294 - acc: 0.9545 - val_loss: 0.1643 - val_acc: 0.9500
Epoch 4/6
3277/3277 [==============================] - 25s 8ms/step - loss: 0.1634 - acc: 0.9487 - val_loss: 0.1651 - val_acc: 0.9540
Epoch 5/6
3277/3277 [==============================] - 25s 8ms/step - loss: 0.1087 - acc: 0.9655 - val_loss: 0.1956 - val_acc: 0.9440
Epoch 6/6
3277/3277 [==============================] - 25s 8ms/step - loss: 0.1047 - acc: 0.9686 - val_loss: 0.1622 - val_acc: 0.9700
Out[124]:
<keras.callbacks.History at 0x7fe73f9efd30>

In [125]:
lrg_model.fit(conv_trn_feat, trn_labels, batch_size=batch_size, epochs=10, 
             validation_data=(conv_val_feat, val_labels))


Train on 3277 samples, validate on 500 samples
Epoch 1/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.1021 - acc: 0.9692 - val_loss: 0.1446 - val_acc: 0.9660
Epoch 2/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0782 - acc: 0.9747 - val_loss: 0.1612 - val_acc: 0.9560
Epoch 3/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0715 - acc: 0.9774 - val_loss: 0.2587 - val_acc: 0.9500
Epoch 4/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0829 - acc: 0.9719 - val_loss: 0.1757 - val_acc: 0.9580
Epoch 5/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0393 - acc: 0.9866 - val_loss: 0.1352 - val_acc: 0.9620
Epoch 6/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0797 - acc: 0.9744 - val_loss: 0.1558 - val_acc: 0.9580
Epoch 7/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0357 - acc: 0.9857 - val_loss: 0.2782 - val_acc: 0.9600
Epoch 8/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0520 - acc: 0.9835 - val_loss: 0.1987 - val_acc: 0.9620
Epoch 9/10
3277/3277 [==============================] - 25s 8ms/step - loss: 0.0507 - acc: 0.9841 - val_loss: 0.1673 - val_acc: 0.9660
Epoch 10/10
3277/3277 [==============================] - 26s 8ms/step - loss: 0.0429 - acc: 0.9869 - val_loss: 0.1740 - val_acc: 0.9620
Out[125]:
<keras.callbacks.History at 0x7fe73f9efe48>

In [126]:
lrg_model.save_weights(path+'models/lrg_nmp.h5')

In [127]:
lrg_model.load_weights(path+'models/lrg_nmp.h5')

Pseudo-labeling


In [128]:
# This is the original code, whose data preparation would require some completion steps
#
# preds = model.predict([conv_test_feat, test_sizes], batch_size=batch_size*2)
# gen = image.ImageDataGenerator()
# test_batches = gen.flow(conv_test_feat, preds, batch_size=16)
# val_batches = gen.flow(conv_val_feat, val_labels, batch_size=4)
# batches = gen.flow(conv_feat, trn_labels, batch_size=44)
# mi = MixIterator([batches, test_batches, val_batches)
# bn_model.fit_generator(mi, mi.N, epochs=8, validation_data=(conv_val_feat, val_labels))

In [129]:
# The following is a replacement code attempting to simplify the pseudo-labeling example (hope so...) by
# fitting the whole dataset in memory instead of using batches (which wouldn't work when directly
# passing to Keras' gen.flow a data array that is not images.

In [130]:
# we continue from the last lrg_model
preds = lrg_model.predict(conv_test_feat, batch_size=batch_size*2)

In [131]:
# create cumulative array of features and labels+pseudo-labels, then shuffle
all_feat = np.vstack((conv_trn_feat, conv_val_feat, conv_test_feat))
all_labels = np.vstack((trn_labels, val_labels, preds))
shuffix = np.arange(all_feat.shape[0])
np.random.shuffle(shuffix)
mix_feat = all_feat[shuffix]
mix_labels = all_labels[shuffix]

In [132]:
lrg_model.fit(mix_feat, mix_labels, batch_size=batch_size, epochs=8, 
             validation_data=(conv_val_feat, val_labels))


Train on 4777 samples, validate on 500 samples
Epoch 1/8
4777/4777 [==============================] - 36s 8ms/step - loss: 0.3209 - acc: 0.9267 - val_loss: 0.0682 - val_acc: 0.9820
Epoch 2/8
4777/4777 [==============================] - 36s 7ms/step - loss: 0.2274 - acc: 0.9537 - val_loss: 0.0143 - val_acc: 0.9980
Epoch 3/8
4777/4777 [==============================] - 36s 7ms/step - loss: 0.1677 - acc: 0.9634 - val_loss: 0.0128 - val_acc: 1.0000
Epoch 4/8
4777/4777 [==============================] - 36s 8ms/step - loss: 0.1487 - acc: 0.9696 - val_loss: 0.0082 - val_acc: 1.0000
Epoch 5/8
4777/4777 [==============================] - 36s 8ms/step - loss: 0.1485 - acc: 0.9755 - val_loss: 0.0196 - val_acc: 0.9940
Epoch 6/8
4777/4777 [==============================] - 36s 8ms/step - loss: 0.1375 - acc: 0.9711 - val_loss: 0.0068 - val_acc: 1.0000
Epoch 7/8
4777/4777 [==============================] - 36s 8ms/step - loss: 0.1327 - acc: 0.9780 - val_loss: 0.0081 - val_acc: 1.0000
Epoch 8/8
4777/4777 [==============================] - 36s 8ms/step - loss: 0.1358 - acc: 0.9728 - val_loss: 0.0071 - val_acc: 0.9980
Out[132]:
<keras.callbacks.History at 0x7fe73f7c3978>

Submit


In [133]:
def do_clip(arr, mx): return np.clip(arr, (1-mx)/7, mx)

In [134]:
lrg_model.evaluate(conv_val_feat, val_labels, batch_size*2)


500/500 [==============================] - 1s 1ms/step
Out[134]:
[0.0070939058528747406, 0.998]

In [135]:
preds = lrg_model.predict(conv_test_feat, batch_size=batch_size)

In [136]:
subm = do_clip(preds,0.82)

In [137]:
subm_name = path+'results/subm_bb.gz'

In [138]:
# classes = sorted(batches.class_indices, key=batches.class_indices.get)
classes = ['ALB', 'BET', 'DOL', 'LAG', 'NoF', 'OTHER', 'SHARK', 'YFT']

In [139]:
submission = pd.DataFrame(subm, columns=classes)
submission.insert(0, 'image', raw_test_filenames)
submission.head()


Out[139]:
image ALB BET DOL LAG NoF OTHER SHARK YFT
0 img_00005.jpg 0.025714 0.025714 0.025714 0.025714 0.820000 0.025714 0.025714 0.025714
1 img_00007.jpg 0.578604 0.025714 0.025714 0.047626 0.025714 0.025714 0.025714 0.353152
2 img_00009.jpg 0.820000 0.025714 0.025714 0.025714 0.025714 0.025714 0.025714 0.025714
3 img_00018.jpg 0.820000 0.025714 0.025714 0.025714 0.025714 0.025714 0.025714 0.025714
4 img_00027.jpg 0.820000 0.025714 0.025714 0.025714 0.025714 0.025714 0.025714 0.044003

In [140]:
submission.to_csv(subm_name, index=False, compression='gzip')

In [141]:
FileLink(subm_name)





In [ ]: