Dog Breed Identification (ImageNet Dogs) on Kaggle

In this section, we will practice the dog breed identification problem on Kaggle. The web address of this competition is https://www.kaggle.com/c/dog-breed-identification

In this competition, 120 different breeds of dogs will be recognized. In fact, the dataset for this competition is a subset of the ImageNet dataset. Unlike the images in the CIFAR-10 dataset in :numref:sec_kaggle_cifar10, the images in the ImageNet dataset are both higher and wider in varying dimensions. :numref:fig_kaggle_dog shows the information on the competition’s webpage. You need a Kaggle account to submit your results.

The dog breed identification competition website. The competition dataset can be obtained by clicking the "Data" tab. :width:400px :label:fig_kaggle_dog

```{.python .input} from d2l import mxnet as d2l from mxnet import autograd, gluon, init, npx from mxnet.gluon import nn import os

npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import torch
  5. import torchvision
  6. from torch import nn
  7. import os

Obtaining and Organizing the Dataset

The competition dataset is divided into a training set and a test set, which contain 10222 and 10357 JPEG images of three RGB (color) channels, respectively. Among the training dataset, there are 120 breeds of dogs such as Labradors, Poodles, Dachshunds, Samoyeds, Huskies, Chihuahuas, and Yorkshire Terriers.

Downloading the Dataset

After logging into Kaggle, you can click on the “Data” tab on the competition webpage shown in :numref:fig_kaggle_dog and download the dataset by clicking the “Download All” button. After unzipping the downloaded file in ../data, you will find the entire dataset in the following paths:

  • ../data/dog-breed-identification/labels.csv
  • ../data/dog-breed-identification/sample_submission.csv
  • ../data/dog-breed-identification/train
  • ../data/dog-breed-identification/test

You may have noticed that the above structure is similar to that of the CIFAR-10 competition in :numref:sec_kaggle_cifar10, where folders train/ and test/ contain training and testing dog images, respectively, and labels.csv contains the labels for the training images. Similarly, to make it easier to get started, we provide a small sample of the dataset mentioned above: train_valid_test_tiny.zip. If you are going to use the full dataset for the Kaggle competition, you need to change the demo variable below to False.

```{.python .input}

@tab all

@save

d2l.DATA_HUB[‘dog_tiny’] = (d2l.DATA_URL + ‘kaggle_dog_tiny.zip’, ‘0cb91d09b814ecdc07b50f31f8dcad3e81d6a86d’)

If you use the full dataset downloaded for the Kaggle competition, change

the variable below to False

demo = True if demo: data_dir = d2l.download_extract(‘dog_tiny’) else: data_dir = os.path.join(‘..’, ‘data’, ‘dog-breed-identification’)

  1. ### Organizing the Dataset
  2. We can organize the dataset similarly to what we did in :numref:`sec_kaggle_cifar10`, namely splitting out
  3. a validation set from the original training set, and moving images into subfolders grouped by labels.
  4. The `reorg_dog_data` function below reads
  5. the training data labels, splits out the validation set, and organizes the training set.
  6. ```{.python .input}
  7. #@tab all
  8. def reorg_dog_data(data_dir, valid_ratio):
  9. labels = d2l.read_csv_labels(os.path.join(data_dir, 'labels.csv'))
  10. d2l.reorg_train_valid(data_dir, labels, valid_ratio)
  11. d2l.reorg_test(data_dir)
  12. batch_size = 4 if demo else 128
  13. valid_ratio = 0.1
  14. reorg_dog_data(data_dir, valid_ratio)

Image Augmentation

Recall that this dog breed dataset is a subset of the ImageNet dataset, whose images are larger than those of the CIFAR-10 dataset in :numref:sec_kaggle_cifar10. The following lists a few image augmentation operations that might be useful for relatively larger images.

```{.python .input} transform_train = gluon.data.vision.transforms.Compose([

  1. # Randomly crop the image to obtain an image with an area of 0.08 to 1 of
  2. # the original area and height-to-width ratio between 3/4 and 4/3. Then,
  3. # scale the image to create a new 224 x 224 image
  4. gluon.data.vision.transforms.RandomResizedCrop(224, scale=(0.08, 1.0),
  5. ratio=(3.0/4.0, 4.0/3.0)),
  6. gluon.data.vision.transforms.RandomFlipLeftRight(),
  7. # Randomly change the brightness, contrast, and saturation
  8. gluon.data.vision.transforms.RandomColorJitter(brightness=0.4,
  9. contrast=0.4,
  10. saturation=0.4),
  11. # Add random noise
  12. gluon.data.vision.transforms.RandomLighting(0.1),
  13. gluon.data.vision.transforms.ToTensor(),
  14. # Standardize each channel of the image
  15. gluon.data.vision.transforms.Normalize([0.485, 0.456, 0.406],
  16. [0.229, 0.224, 0.225])])
  1. ```{.python .input}
  2. #@tab pytorch
  3. transform_train = torchvision.transforms.Compose([
  4. # Randomly crop the image to obtain an image with an area of 0.08 to 1 of
  5. # the original area and height-to-width ratio between 3/4 and 4/3. Then,
  6. # scale the image to create a new 224 x 224 image
  7. torchvision.transforms.RandomResizedCrop(224, scale=(0.08, 1.0),
  8. ratio=(3.0/4.0, 4.0/3.0)),
  9. torchvision.transforms.RandomHorizontalFlip(),
  10. # Randomly change the brightness, contrast, and saturation
  11. torchvision.transforms.ColorJitter(brightness=0.4,
  12. contrast=0.4,
  13. saturation=0.4),
  14. # Add random noise
  15. torchvision.transforms.ToTensor(),
  16. # Standardize each channel of the image
  17. torchvision.transforms.Normalize([0.485, 0.456, 0.406],
  18. [0.229, 0.224, 0.225])])

During prediction, we only use image preprocessing operations without randomness.

```{.python .input} transform_test = gluon.data.vision.transforms.Compose([ gluon.data.vision.transforms.Resize(256),

  1. # Crop a 224 x 224 square area from the center of the image
  2. gluon.data.vision.transforms.CenterCrop(224),
  3. gluon.data.vision.transforms.ToTensor(),
  4. gluon.data.vision.transforms.Normalize([0.485, 0.456, 0.406],
  5. [0.229, 0.224, 0.225])])
  1. ```{.python .input}
  2. #@tab pytorch
  3. transform_test = torchvision.transforms.Compose([
  4. torchvision.transforms.Resize(256),
  5. # Crop a 224 x 224 square area from the center of the image
  6. torchvision.transforms.CenterCrop(224),
  7. torchvision.transforms.ToTensor(),
  8. torchvision.transforms.Normalize([0.485, 0.456, 0.406],
  9. [0.229, 0.224, 0.225])])

Reading the Dataset

As in :numref:sec_kaggle_cifar10, we can read the organized dataset consisting of raw image files.

```{.python .input} train_ds, valid_ds, train_valid_ds, test_ds = [ gluon.data.vision.ImageFolderDataset( os.path.join(data_dir, ‘train_valid_test’, folder)) for folder in (‘train’, ‘valid’, ‘train_valid’, ‘test’)]

  1. ```{.python .input}
  2. #@tab pytorch
  3. train_ds, train_valid_ds = [torchvision.datasets.ImageFolder(
  4. os.path.join(data_dir, 'train_valid_test', folder),
  5. transform=transform_train) for folder in ['train', 'train_valid']]
  6. valid_ds, test_ds = [torchvision.datasets.ImageFolder(
  7. os.path.join(data_dir, 'train_valid_test', folder),
  8. transform=transform_test) for folder in ['valid', 'test']]

Below we create data loader instances the same way as in :numref:sec_kaggle_cifar10.

```{.python .input} train_iter, train_valid_iter = [gluon.data.DataLoader( dataset.transform_first(transform_train), batch_size, shuffle=True, last_batch=’discard’) for dataset in (train_ds, train_valid_ds)]

valid_iter = gluon.data.DataLoader( valid_ds.transform_first(transform_test), batch_size, shuffle=False, last_batch=’discard’)

test_iter = gluon.data.DataLoader( test_ds.transform_first(transform_test), batch_size, shuffle=False, last_batch=’keep’)

  1. ```{.python .input}
  2. #@tab pytorch
  3. train_iter, train_valid_iter = [torch.utils.data.DataLoader(
  4. dataset, batch_size, shuffle=True, drop_last=True)
  5. for dataset in (train_ds, train_valid_ds)]
  6. valid_iter = torch.utils.data.DataLoader(valid_ds, batch_size, shuffle=False,
  7. drop_last=True)
  8. test_iter = torch.utils.data.DataLoader(test_ds, batch_size, shuffle=False,
  9. drop_last=False)

Fine-Tuning a Pretrained Model

Again, the dataset for this competition is a subset of the ImageNet dataset. Therefore, we can use the approach discussed in :numref:sec_fine_tuning to select a model pretrained on the full ImageNet dataset and use it to extract image features to be fed into a custom small-scale output network. High-level APIs of deep learning frameworks provide a wide range of models pretrained on the ImageNet dataset. Here, we choose a pretrained ResNet-34 model, where we simply reuse the input of this model’s output layer (i.e., the extracted features). Then we can replace the original output layer with a small custom output network that can be trained, such as stacking two fully-connected layers. Different from the experiment in :numref:sec_fine_tuning, the following does not retrain the pretrained model used for feature extraction. This reduces training time and memory for storing gradients.

Recall that we standardized images using the means and standard deviations of the three RGB channels for the full ImageNet dataset. In fact, this is also consistent with the standardization operation by the pretrained model on ImageNet.

```{.python .input} def get_net(devices): finetune_net = gluon.model_zoo.vision.resnet34_v2(pretrained=True)

  1. # Define a new output network
  2. finetune_net.output_new = nn.HybridSequential(prefix='')
  3. finetune_net.output_new.add(nn.Dense(256, activation='relu'))
  4. # There are 120 output categories
  5. finetune_net.output_new.add(nn.Dense(120))
  6. # Initialize the output network
  7. finetune_net.output_new.initialize(init.Xavier(), ctx=devices)
  8. # Distribute the model parameters to the CPUs or GPUs used for computation
  9. finetune_net.collect_params().reset_ctx(devices)
  10. return finetune_net
  1. ```{.python .input}
  2. #@tab pytorch
  3. def get_net(devices):
  4. finetune_net = nn.Sequential()
  5. finetune_net.features = torchvision.models.resnet34(pretrained=True)
  6. # Define a new output network (there are 120 output categories)
  7. finetune_net.output_new = nn.Sequential(nn.Linear(1000, 256),
  8. nn.ReLU(),
  9. nn.Linear(256, 120))
  10. # Move the model to devices
  11. finetune_net = finetune_net.to(devices[0])
  12. # Freeze parameters of feature layers
  13. for param in finetune_net.features.parameters():
  14. param.requires_grad = False
  15. return finetune_net

Before calculating the loss, we first obtain the input of the pretrained model’s output layer, i.e., the extracted feature. Then we use this feature as the input for our small custom output network to calculate the loss.

```{.python .input} loss = gluon.loss.SoftmaxCrossEntropyLoss()

def evaluate_loss(data_iter, net, devices): l_sum, n = 0.0, 0 for features, labels in data_iter: X_shards, y_shards = d2l.split_batch(features, labels, devices) output_features = [net.features(X_shard) for X_shard in X_shards] outputs = [net.output_new(feature) for feature in output_features] ls = [loss(output, y_shard).sum() for output, y_shard in zip(outputs, y_shards)] l_sum += sum([float(l.sum()) for l in ls]) n += labels.size return l_sum / n

  1. ```{.python .input}
  2. #@tab pytorch
  3. loss = nn.CrossEntropyLoss(reduction='none')
  4. def evaluate_loss(data_iter, net, devices):
  5. l_sum, n = 0.0, 0
  6. for features, labels in data_iter:
  7. features, labels = features.to(devices[0]), labels.to(devices[0])
  8. outputs = net(features)
  9. l = loss(outputs, labels)
  10. l_sum = l.sum()
  11. n += labels.numel()
  12. return l_sum / n

Defining the Training Function

We will select the model and tune hyperparameters according to the model’s performance on the validation set. The model training function train only iterates parameters of the small custom output network.

```{.python .input} def train(net, train_iter, valid_iter, num_epochs, lr, wd, devices, lr_period, lr_decay):

  1. # Only train the small custom output network
  2. trainer = gluon.Trainer(net.output_new.collect_params(), 'sgd',
  3. {'learning_rate': lr, 'momentum': 0.9, 'wd': wd})
  4. num_batches, timer = len(train_iter), d2l.Timer()
  5. animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
  6. legend=['train loss', 'valid loss'])
  7. for epoch in range(num_epochs):
  8. metric = d2l.Accumulator(2)
  9. if epoch > 0 and epoch % lr_period == 0:
  10. trainer.set_learning_rate(trainer.learning_rate * lr_decay)
  11. for i, (features, labels) in enumerate(train_iter):
  12. timer.start()
  13. X_shards, y_shards = d2l.split_batch(features, labels, devices)
  14. output_features = [net.features(X_shard) for X_shard in X_shards]
  15. with autograd.record():
  16. outputs = [net.output_new(feature)
  17. for feature in output_features]
  18. ls = [loss(output, y_shard).sum() for output, y_shard
  19. in zip(outputs, y_shards)]
  20. for l in ls:
  21. l.backward()
  22. trainer.step(batch_size)
  23. metric.add(sum([float(l.sum()) for l in ls]), labels.shape[0])
  24. timer.stop()
  25. if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
  26. animator.add(epoch + (i + 1) / num_batches,
  27. (metric[0] / metric[1], None))
  28. if valid_iter is not None:
  29. valid_loss = evaluate_loss(valid_iter, net, devices)
  30. animator.add(epoch + 1, (None, valid_loss))
  31. if valid_iter is not None:
  32. print(f'train loss {metric[0] / metric[1]:.3f}, '
  33. f'valid loss {valid_loss:.3f}')
  34. else:
  35. print(f'train loss {metric[0] / metric[1]:.3f}')
  36. print(f'{metric[1] * num_epochs / timer.sum():.1f} examples/sec '
  37. f'on {str(devices)}')
  1. ```{.python .input}
  2. #@tab pytorch
  3. def train(net, train_iter, valid_iter, num_epochs, lr, wd, devices, lr_period,
  4. lr_decay):
  5. # Only train the small custom output network
  6. net = nn.DataParallel(net, device_ids=devices).to(devices[0])
  7. trainer = torch.optim.SGD((param for param in net.parameters()
  8. if param.requires_grad), lr=lr,
  9. momentum=0.9, weight_decay=wd)
  10. scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_period, lr_decay)
  11. num_batches, timer = len(train_iter), d2l.Timer()
  12. animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
  13. legend=['train loss', 'valid loss'])
  14. for epoch in range(num_epochs):
  15. metric = d2l.Accumulator(2)
  16. for i, (features, labels) in enumerate(train_iter):
  17. timer.start()
  18. features, labels = features.to(devices[0]), labels.to(devices[0])
  19. trainer.zero_grad()
  20. output = net(features)
  21. l = loss(output, labels).sum()
  22. l.backward()
  23. trainer.step()
  24. metric.add(l, labels.shape[0])
  25. timer.stop()
  26. if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
  27. animator.add(epoch + (i + 1) / num_batches,
  28. (metric[0] / metric[1], None))
  29. if valid_iter is not None:
  30. valid_loss = evaluate_loss(valid_iter, net, devices)
  31. animator.add(epoch + 1, (None, valid_loss))
  32. scheduler.step()
  33. if valid_iter is not None:
  34. print(f'train loss {metric[0] / metric[1]:.3f}, '
  35. f'valid loss {valid_loss:.3f}')
  36. else:
  37. print(f'train loss {metric[0] / metric[1]:.3f}')
  38. print(f'{metric[1] * num_epochs / timer.sum():.1f} examples/sec '
  39. f'on {str(devices)}')

Training and Validating the Model

Now we can train and validate the model. The following hyperparameters are all tunable. For example, the number of epochs can be increased. Because lr_period and lr_decay are set to 10 and 0.1, respectively, the learning rate of the optimization algorithm will be multiplied by 0.1 after every 10 epochs.

```{.python .input} devices, num_epochs, lr, wd = d2l.try_all_gpus(), 5, 0.01, 1e-4 lr_period, lr_decay, net = 10, 0.1, get_net(devices) net.hybridize() train(net, train_iter, valid_iter, num_epochs, lr, wd, devices, lr_period, lr_decay)

  1. ```{.python .input}
  2. #@tab pytorch
  3. devices, num_epochs, lr, wd = d2l.try_all_gpus(), 5, 0.001, 1e-4
  4. lr_period, lr_decay, net = 10, 0.1, get_net(devices)
  5. train(net, train_iter, valid_iter, num_epochs, lr, wd, devices, lr_period,
  6. lr_decay)

Classifying the Testing Set and Submitting Results on Kaggle

Similar to the final step in :numref:sec_kaggle_cifar10, in the end all the labeled data (including the validation set) are used for training the model and classifying the testing set. We will use the trained custom output network for classification.

```{.python .input} net = get_net(devices) net.hybridize() train(net, train_valid_iter, None, num_epochs, lr, wd, devices, lr_period, lr_decay)

preds = [] for data, label in test_iter: output_features = net.features(data.as_in_ctx(devices[0])) output = npx.softmax(net.output_new(output_features)) preds.extend(output.asnumpy()) ids = sorted(os.listdir( os.path.join(data_dir, ‘train_valid_test’, ‘test’, ‘unknown’))) with open(‘submission.csv’, ‘w’) as f: f.write(‘id,’ + ‘,’.join(train_valid_ds.synsets) + ‘\n’) for i, output in zip(ids, preds): f.write(i.split(‘.’)[0] + ‘,’ + ‘,’.join( [str(num) for num in output]) + ‘\n’)

  1. ```{.python .input}
  2. #@tab pytorch
  3. net = get_net(devices)
  4. train(net, train_valid_iter, None, num_epochs, lr, wd, devices, lr_period,
  5. lr_decay)
  6. preds = []
  7. for data, label in test_iter:
  8. output = torch.nn.functional.softmax(net(data.to(devices[0])), dim=0)
  9. preds.extend(output.cpu().detach().numpy())
  10. ids = sorted(os.listdir(
  11. os.path.join(data_dir, 'train_valid_test', 'test', 'unknown')))
  12. with open('submission.csv', 'w') as f:
  13. f.write('id,' + ','.join(train_valid_ds.classes) + '\n')
  14. for i, output in zip(ids, preds):
  15. f.write(i.split('.')[0] + ',' + ','.join(
  16. [str(num) for num in output]) + '\n')

The above code will generate a submission.csv file to be submitted to Kaggle in the same way described in :numref:sec_kaggle_house.

Summary

  • Images in the ImageNet dataset are larger (with varying dimensions) than CIFAR-10 images. We may modify image augmentation operations for tasks on a different dataset.
  • To classify a subset of the ImageNet dataset, we can leverage pre-trained models on the full ImageNet dataset to extract features and only train a custom small-scale output network. This will lead to less computational time and memory cost.

Exercises

  1. When using the fill Kaggle competition dataset, what results can you achieve when you increase the batch_size (batch size) and num_epochs (number of epochs)?
  2. Do you get better results if you use a deeper pretrained model? How do you tune hyperparameters? Can you further improve the results?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: