Kaggle competition: CIFAR-10 - Object Recognition in Images
<SOS> metric: CategorizationAccuracy Kaggle data source: cifar-10<create_dataframe>
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
train_dataset = DogvsCatDataset(train_list, transform=ImageTransform(size, mean, std), phase='train')
 val_dataset = DogvsCatDataset(val_list, transform=ImageTransform(size, mean, std), phase='val' )<load_pretrained>
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 except ValueError:
strategy = tf.distribute.MirroredStrategy()
print("Number of accelerators: ", strategy.num_replicas_in_sync )
train_dataloader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
 val_dataloader = data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
 dataloader_dict = {'train': train_dataloader, 'val': val_dataloader}
print('Operation Check')
 batch_iterator = iter(train_dataloader)
 inputs, label = next(batch_iterator)
 print(inputs.size())
 print(label )<choose_model_class>
GCS_DS_PATH = KaggleDatasets().get_gcs_path("cifar-10-unzipped" )
use_pretrained = True
net = models.resnet50(pretrained=use_pretrained)
 print(net )<train_model>
IMAGE_SIZE = [32, 32]
EPOCHS = 100
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
ROOT_PATH_MAP = {
32: GCS_DS_PATH + "/tfrecords-jpeg-32x32/"
}
ROOT_PATH = ROOT_PATH_MAP[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(ROOT_PATH + "train/*.tfrec")
 VALIDATION_FILENAMES = tf.io.gfile.glob(ROOT_PATH + "validation/*.tfrec")
 TEST_FILENAMES = tf.io.gfile.glob(ROOT_PATH + "test/*.tfrec")
 CLASSES = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
net.fc = nn.Linear(in_features=2048, out_features=2)
 print('Done' )<find_best_params>
np.set_printoptions(threshold=15, linewidth=80)
 def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
 def display_batch_of_images(databatch, predictions=None):

 images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)//rows
FIGSIZE = 13.0
SPACING = 0.1
subplot=(rows,cols,1)
 if rows < cols:
plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))
else:
plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target(predictions[i], label)
 dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace=0, hspace=0)
 else:
plt.subplots_adjust(wspace=SPACING, hspace=SPACING)
 plt.show()
def display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
plt.show()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
 ax.set_facecolor('
ax.plot(training)
 ax.plot(validation)
 ax.set_title('model '+ title)
 ax.set_ylabel(title)
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.'] )
params_to_update = []
update_params_name = ['fc.weight', 'fc.bias']
for name, param in net.named_parameters() :
if name in update_params_name:
param.requires_grad = True
params_to_update.append(param)
 print(name)
 else:
param.requires_grad = False<train_model>
def to_float32(image, label):
return tf.cast(image, tf.float32), label
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_saturation(image, 0, 2)
 image = tf.clip_by_value(image, 0, 1)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
def lr_schedule(epoch):
lr = 1e-3
if epoch > 95:
lr *= 0.5e-3
elif epoch > 80:
lr *= 1e-3
elif epoch > 50:
lr *= 1e-2
elif epoch > 20:
lr *= 1e-1
print('Learning rate: ', lr)
 return lr<choose_model_class>
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(params=params_to_update,lr=lr_schedule(0))<train_model>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
def train_model(net, dataloader_dict, criterion, optimizer, num_epoch):
since = time.time()
best_model_wts = copy.deepcopy(net.state_dict())
 best_acc = 0.0
net = net.to(device)
 for epoch in range(num_epoch):
print('Epoch {}/{}'.format(epoch + 1, num_epoch))
print('-'*20)
 for phase in ['train', 'val']:
if phase == 'train':
net.train()
else:
net.eval()
epoch_loss = 0.0
epoch_corrects = 0
for inputs, labels in tqdm(dataloader_dict[phase]):
inputs = inputs.to(device)
 labels = labels.to(device)
 optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = net(inputs)
 _, preds = torch.max(outputs, 1)
 loss = criterion(outputs, labels)
 if phase == 'train':
loss.backward()
optimizer.step()
epoch_loss += loss.item() * inputs.size(0)
 epoch_corrects += torch.sum(preds == labels.data)
 epoch_loss = epoch_loss / len(dataloader_dict[phase].dataset)
 epoch_acc = epoch_corrects.double() / len(dataloader_dict[phase].dataset)
 print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(net.state_dict())
 time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
 time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
net.load_state_dict(best_model_wts)
 return net<train_model>
display_batch_of_images(next(train_batch))
num_epoch = 10
net = train_model(net, dataloader_dict, criterion, optimizer, num_epoch )<categorify>
validation_dataset = get_validation_dataset()
validation_dataset = validation_dataset.unbatch().batch(20)
 validation_batch = iter(validation_dataset )
id_list = []
pred_list = []
with torch.no_grad() :
for test_path in tqdm(test_list):
img = Image.open(test_path)
 _id = int(test_path.split('/')[-1].split('.')[0])
 transform = ImageTransform(size, mean, std)
 img = transform(img, phase='val')
 img = img.unsqueeze(0)
 img = img.to(device)
 net.eval()
outputs = net(img)
 preds = F.softmax(outputs, dim=1)[:, 1].tolist()
id_list.append(_id)
 pred_list.append(preds[0])
 res = pd.DataFrame({
'id': id_list,
'label': pred_list
})
 res.sort_values(by='id', inplace=True)
 res.reset_index(drop=True, inplace=True)
 res.to_csv('submission.csv', index=False )<import_modules>
display_batch_of_images(next(validation_batch))
<install_modules>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
!pip install segmentation_models_pytorch
! git clone https://github.com/Bjarten/early-stopping-pytorch.git
! mv./early-stopping-pytorch./lib<import_modules>
display_batch_of_images(next(test_batch))
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader, sampler
from pathlib import Path
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time
import torchvision
import cv2
import re
import segmentation_models_pytorch as smp
from lib.pytorchtools import *<categorify>
with strategy.scope() :
model = Sequential()
model.add(Conv2D(32,(3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', kernel_regularizer=l2(0.001), input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3)))
 model.add(BatchNormalization())
 model.add(Conv2D(32,(3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', kernel_regularizer=l2(0.001)))
 model.add(BatchNormalization())
 model.add(MaxPooling2D(( 2, 2)))
 model.add(Dropout(0.2))
model.add(Conv2D(64,(3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', kernel_regularizer=l2(0.001)))
 model.add(BatchNormalization())
 model.add(Conv2D(64,(3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', kernel_regularizer=l2(0.001)))
 model.add(BatchNormalization())
 model.add(MaxPooling2D(( 2, 2)))
 model.add(Dropout(0.3))
model.add(Conv2D(128,(3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', kernel_regularizer=l2(0.001)))
 model.add(BatchNormalization())
 model.add(Conv2D(128,(3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', kernel_regularizer=l2(0.001)))
 model.add(BatchNormalization())
 model.add(MaxPooling2D(( 2, 2)))
 model.add(Dropout(0.4))
model.add(Flatten())
 model.add(Dense(128, activation='relu', kernel_initializer='he_uniform', kernel_regularizer=l2(0.001)))
 model.add(BatchNormalization())
 model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
 model.summary()
class NerveDataset(Dataset):
def __init__(self, directory, pytorch=True, is_test=False):
super().__init__()
self.files = []
for file_name in directory.iterdir() :
if 'mask' in str(file_name):
continue
self.files.append(self.combine_files(file_name))
self.files = sorted(self.files, key=lambda file: int(re.search(r'\d+', str(file['image'])).group(0)))
 self.pytorch = pytorch
self.resize = torchvision.transforms.Resize(( 224,224),interpolation=Image.NEAREST)
 self.is_test = is_test
def combine_files(self, file_name: Path):
files = {
'image': file_name,
'mask': '.. ' + str(file_name ).split('.')[2] + '_mask.tif',
}
return files
def __len__(self):
return len(self.files)
 def open_as_array(self, idx, invert=False):
raw_image = self.resize(Image.open(self.files[idx]['image']))
raw_image = raw_image = np.stack([ np.array(raw_image)], axis=2)
 if invert:
raw_image = raw_image.transpose(( 2,0,1))
return(raw_image / np.iinfo(raw_image.dtype ).max)
 def open_mask(self, idx, add_dims=False):
raw_mask = self.resize(Image.open(self.files[idx]['mask']))
raw_mask = np.array(raw_mask)
 raw_mask = np.where(raw_mask==255, 1, 0)
 return np.expand_dims(raw_mask, 0)if add_dims else raw_mask
def __getitem__(self, idx):
x = torch.tensor(self.open_as_array(idx, invert=self.pytorch), dtype=torch.float32)
 if not self.is_test:
y = torch.tensor(self.open_mask(idx, add_dims=True), dtype=torch.torch.float32)
 return x, y
return x
def open_as_pil(self, idx):
arr = 256*self.open_as_array(idx)
 return Image.fromarray(arr.astype(np.uint8), 'L')
 def __repr__(self):
s = 'Dataset class with {} files'.format(self.__len__())
 return s 
<create_dataframe>
training_dataset = get_training_dataset().map(to_float32)
 validation_dataset = get_validation_dataset().map(to_float32)
 checkpoint = ModelCheckpoint("model_checkpoint.h5", monitor='val_loss', mode='min', save_best_only=True, verbose=1)
 early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1, restore_best_weights=True)
 reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, verbose=1, min_delta=0.0001)
 callbacks = [early_stopping, reduce_lr]
history = model.fit(training_dataset, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=validation_dataset, callbacks=callbacks )
images_path = Path('.. /input/ultrasound-nerve-segmentation/train')
 data = NerveDataset(images_path)
 len(data )<train_model>
cmdataset = get_validation_dataset(ordered=True)
 cmdataset = cmdataset.map(to_float32)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions )
split_rate = 0.7
train_ds_len = int(len(data)* split_rate)
 valid_ds_len = len(data)- train_ds_len
train_ds, valid_ds = torch.utils.data.random_split(data,(train_ds_len, valid_ds_len))
print(f'Train dataset length: {len(train_ds)}
')
 print(f'Validation dataset length: {len(valid_ds)}
')
 print(f'All data length: {len(data)}
' )<choose_model_class>
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
unet = model = smp.Unet(
 encoder_name="resnet34",
encoder_weights="imagenet",
in_channels=1,
classes=1,
activation = "sigmoid" 
)
 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 learning_rate = 0.001
epochs = 50
metrics = [smp.utils.metrics.IoU() ]
loss_function = smp.utils.losses.DiceLoss()
optimizer = torch.optim.Adam(model.parameters() , lr=learning_rate)
 scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs)
 stopper = EarlyStopping(patience=3)
 train_epoch = smp.utils.train.TrainEpoch(model,
loss=loss_function,
optimizer=optimizer,
metrics=metrics,
device=device,
verbose=True)
 val_epoch = smp.utils.train.ValidEpoch(model,
loss=loss_function,
metrics=metrics,
device=device,
verbose=True)
 train_dl = DataLoader(train_ds, batch_size=16, shuffle=True)
 valid_dl = DataLoader(valid_ds, batch_size=16, shuffle=True )<create_dataframe>
test_ds = get_test_dataset(ordered=True)
 test_ds = test_ds.map(to_float32)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 label_map = np.vectorize(lambda index : CLASSES[int(index)])
 predictions_with_label = label_map(predictions)
 print(predictions_with_label)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions_with_label]), fmt=['%s', '%s'], delimiter=',', header='id,label', comments='')
 !head submission.csv
test_images_path = Path('.. /input/ultrasound-nerve-segmentation/test')
 test_data = NerveDataset(test_images_path, is_test=True)
 test_dl = DataLoader(test_data, batch_size=1, shuffle=False)
 len(test_data )<categorify>
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )
def rle_encoding(x):
dots = np.where(x.T.flatten() ==1)[0]
run_lengths = []
prev = -2
for b in dots:
if(b>prev+1): run_lengths.extend(( b+1, 0))
run_lengths[-1] += 1
prev = b
return run_lengths<categorify>
images, labels = next(batch)
 probabilities = model.predict(tf.cast(images, tf.float32))
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )