<jupyter_start><jupyter_text>Computer Vision Nanodegree Project: Image Captioning---In this notebook, you will train your CNN-RNN model.You are welcome and encouraged to try out many different architectures and hyperparameters when searching for a good model.This does have the potential to make the project quite messy!  Before submitting your project, make sure that you clean up:- the code you write in this notebook.  The notebook should describe how to train a single CNN-RNN architecture, corresponding to your final choice of hyperparameters.  You should structure the notebook so that the reviewer can replicate your results by running the code in this notebook.- the output of the code cell in **Step 2**.  The output should show the output obtained when training the model from scratch.This notebook **will be graded**.Feel free to use the links below to navigate the notebook:- [Step 1](step1): Training Setup- [Step 2](step2): Train your Model- [Step 3](step3): (Optional) Validate your Model  Step 1: Training SetupIn this step of the notebook, you will customize the training of your CNN-RNN model by specifying hyperparameters and setting other options that are important to the training procedure.  The values you set now will be used when training your model in **Step 2** below.You should only amend blocks of code that are preceded by a `TODO` statement.  **Any code blocks that are not preceded by a `TODO` statement should not be modified**. Task 1Begin by setting the following variables:- `batch_size` - the batch size of each training batch.  It is the number of image-caption pairs used to amend the model weights in each training step.- `vocab_threshold` - the minimum word count threshold.  Note that a larger threshold will result in a smaller vocabulary, whereas a smaller threshold will include rarer words and result in a larger vocabulary.- `vocab_from_file` - a Boolean that decides whether to load the vocabulary from file.- `embed_size` - the dimensionality of the image and word embeddings.- `hidden_size` - the number of features in the hidden state of the RNN decoder.- `num_epochs` - the number of epochs to train the model.  We recommend that you set `num_epochs=3`, but feel free to increase or decrease this number as you wish.  [This paper](https://arxiv.org/pdf/1502.03044.pdf) trained a captioning model on a single state-of-the-art GPU for 3 days, but you'll soon see that you can get reasonable results in a matter of a few hours!  (_But of course, if you want your model to compete with current research, you will have to train for much longer._)- `save_every` - determines how often to save the model weights.  We recommend that you set `save_every=1`, to save the model weights after each epoch.  This way, after the `i`th epoch, the encoder and decoder weights will be saved in the `models/` folder as `encoder-i.pkl` and `decoder-i.pkl`, respectively.- `print_every` - determines how often to print the batch loss to the Jupyter notebook while training.  Note that you **will not** observe a monotonic decrease in the loss function while training - this is perfectly fine and completely expected!  You are encouraged to keep this at its default value of `100` to avoid clogging the notebook, but feel free to change it.- `log_file` - the name of the text file containing - for every step - how the loss and perplexity evolved during training.If you're not sure where to begin to set some of the values above, you can peruse [this paper](https://arxiv.org/pdf/1502.03044.pdf) and [this paper](https://arxiv.org/pdf/1411.4555.pdf) for useful guidance!  **To avoid spending too long on this notebook**, you are encouraged to consult these suggested research papers to obtain a strong initial guess for which hyperparameters are likely to work best.  Then, train a single model, and proceed to the next notebook (**3_Inference.ipynb**).  If you are unhappy with your performance, you can return to this notebook to tweak the hyperparameters (and/or the architecture in **model.py**) and re-train your model. Question 1**Question:** Describe your CNN-RNN architecture in detail.  With this architecture in mind, how did you select the values of the variables in Task 1?  If you consulted a research paper detailing a successful implementation of an image captioning model, please provide the reference.**Answer:**```----------------------------------------------------------------                            Encoder----------------------------------------------------------------        Layer (type)               Output Shape         Param ================================================================            Conv2d-1         [-1, 64, 112, 112]           9,408       BatchNorm2d-2         [-1, 64, 112, 112]             128              ReLU-3         [-1, 64, 112, 112]               0         MaxPool2d-4           [-1, 64, 56, 56]               0            Conv2d-5          [-1, 128, 56, 56]           8,192       BatchNorm2d-6          [-1, 128, 56, 56]             256              ReLU-7          [-1, 128, 56, 56]               0            Conv2d-8          [-1, 128, 56, 56]           4,608       BatchNorm2d-9          [-1, 128, 56, 56]             256             ReLU-10          [-1, 128, 56, 56]               0           Conv2d-11          [-1, 256, 56, 56]          32,768      BatchNorm2d-12          [-1, 256, 56, 56]             512           Conv2d-13          [-1, 256, 56, 56]          16,384      BatchNorm2d-14          [-1, 256, 56, 56]             512             ReLU-15          [-1, 256, 56, 56]               0       Bottleneck-16          [-1, 256, 56, 56]               0           Conv2d-17          [-1, 128, 56, 56]          32,768      BatchNorm2d-18          [-1, 128, 56, 56]             256             ReLU-19          [-1, 128, 56, 56]               0           Conv2d-20          [-1, 128, 56, 56]           4,608      BatchNorm2d-21          [-1, 128, 56, 56]             256             ReLU-22          [-1, 128, 56, 56]               0           Conv2d-23          [-1, 256, 56, 56]          32,768      BatchNorm2d-24          [-1, 256, 56, 56]             512             ReLU-25          [-1, 256, 56, 56]               0       Bottleneck-26          [-1, 256, 56, 56]               0           Conv2d-27          [-1, 128, 56, 56]          32,768      BatchNorm2d-28          [-1, 128, 56, 56]             256             ReLU-29          [-1, 128, 56, 56]               0           Conv2d-30          [-1, 128, 56, 56]           4,608      BatchNorm2d-31          [-1, 128, 56, 56]             256             ReLU-32          [-1, 128, 56, 56]               0           Conv2d-33          [-1, 256, 56, 56]          32,768      BatchNorm2d-34          [-1, 256, 56, 56]             512             ReLU-35          [-1, 256, 56, 56]               0       Bottleneck-36          [-1, 256, 56, 56]               0           Conv2d-37          [-1, 256, 56, 56]          65,536      BatchNorm2d-38          [-1, 256, 56, 56]             512             ReLU-39          [-1, 256, 56, 56]               0           Conv2d-40          [-1, 256, 28, 28]          18,432      BatchNorm2d-41          [-1, 256, 28, 28]             512             ReLU-42          [-1, 256, 28, 28]               0           Conv2d-43          [-1, 512, 28, 28]         131,072      BatchNorm2d-44          [-1, 512, 28, 28]           1,024           Conv2d-45          [-1, 512, 28, 28]         131,072      BatchNorm2d-46          [-1, 512, 28, 28]           1,024             ReLU-47          [-1, 512, 28, 28]               0       Bottleneck-48          [-1, 512, 28, 28]               0           Conv2d-49          [-1, 256, 28, 28]         131,072      BatchNorm2d-50          [-1, 256, 28, 28]             512             ReLU-51          [-1, 256, 28, 28]               0           Conv2d-52          [-1, 256, 28, 28]          18,432      BatchNorm2d-53          [-1, 256, 28, 28]             512             ReLU-54          [-1, 256, 28, 28]               0           Conv2d-55          [-1, 512, 28, 28]         131,072      BatchNorm2d-56          [-1, 512, 28, 28]           1,024             ReLU-57          [-1, 512, 28, 28]               0       Bottleneck-58          [-1, 512, 28, 28]               0           Conv2d-59          [-1, 256, 28, 28]         131,072      BatchNorm2d-60          [-1, 256, 28, 28]             512             ReLU-61          [-1, 256, 28, 28]               0           Conv2d-62          [-1, 256, 28, 28]          18,432      BatchNorm2d-63          [-1, 256, 28, 28]             512             ReLU-64          [-1, 256, 28, 28]               0           Conv2d-65          [-1, 512, 28, 28]         131,072      BatchNorm2d-66          [-1, 512, 28, 28]           1,024             ReLU-67          [-1, 512, 28, 28]               0       Bottleneck-68          [-1, 512, 28, 28]               0           Conv2d-69          [-1, 256, 28, 28]         131,072      BatchNorm2d-70          [-1, 256, 28, 28]             512             ReLU-71          [-1, 256, 28, 28]               0           Conv2d-72          [-1, 256, 28, 28]          18,432      BatchNorm2d-73          [-1, 256, 28, 28]             512             ReLU-74          [-1, 256, 28, 28]               0           Conv2d-75          [-1, 512, 28, 28]         131,072      BatchNorm2d-76          [-1, 512, 28, 28]           1,024             ReLU-77          [-1, 512, 28, 28]               0       Bottleneck-78          [-1, 512, 28, 28]               0           Conv2d-79          [-1, 512, 28, 28]         262,144      BatchNorm2d-80          [-1, 512, 28, 28]           1,024             ReLU-81          [-1, 512, 28, 28]               0           Conv2d-82          [-1, 512, 14, 14]          73,728      BatchNorm2d-83          [-1, 512, 14, 14]           1,024             ReLU-84          [-1, 512, 14, 14]               0           Conv2d-85         [-1, 1024, 14, 14]         524,288      BatchNorm2d-86         [-1, 1024, 14, 14]           2,048           Conv2d-87         [-1, 1024, 14, 14]         524,288      BatchNorm2d-88         [-1, 1024, 14, 14]           2,048             ReLU-89         [-1, 1024, 14, 14]               0       Bottleneck-90         [-1, 1024, 14, 14]               0           Conv2d-91          [-1, 512, 14, 14]         524,288      BatchNorm2d-92          [-1, 512, 14, 14]           1,024             ReLU-93          [-1, 512, 14, 14]               0           Conv2d-94          [-1, 512, 14, 14]          73,728      BatchNorm2d-95          [-1, 512, 14, 14]           1,024             ReLU-96          [-1, 512, 14, 14]               0           Conv2d-97         [-1, 1024, 14, 14]         524,288      BatchNorm2d-98         [-1, 1024, 14, 14]           2,048             ReLU-99         [-1, 1024, 14, 14]               0      Bottleneck-100         [-1, 1024, 14, 14]               0          Conv2d-101          [-1, 512, 14, 14]         524,288     BatchNorm2d-102          [-1, 512, 14, 14]           1,024            ReLU-103          [-1, 512, 14, 14]               0          Conv2d-104          [-1, 512, 14, 14]          73,728     BatchNorm2d-105          [-1, 512, 14, 14]           1,024            ReLU-106          [-1, 512, 14, 14]               0          Conv2d-107         [-1, 1024, 14, 14]         524,288     BatchNorm2d-108         [-1, 1024, 14, 14]           2,048            ReLU-109         [-1, 1024, 14, 14]               0      Bottleneck-110         [-1, 1024, 14, 14]               0          Conv2d-111          [-1, 512, 14, 14]         524,288     BatchNorm2d-112          [-1, 512, 14, 14]           1,024            ReLU-113          [-1, 512, 14, 14]               0          Conv2d-114          [-1, 512, 14, 14]          73,728     BatchNorm2d-115          [-1, 512, 14, 14]           1,024            ReLU-116          [-1, 512, 14, 14]               0          Conv2d-117         [-1, 1024, 14, 14]         524,288     BatchNorm2d-118         [-1, 1024, 14, 14]           2,048            ReLU-119         [-1, 1024, 14, 14]               0      Bottleneck-120         [-1, 1024, 14, 14]               0          Conv2d-121          [-1, 512, 14, 14]         524,288     BatchNorm2d-122          [-1, 512, 14, 14]           1,024            ReLU-123          [-1, 512, 14, 14]               0          Conv2d-124          [-1, 512, 14, 14]          73,728     BatchNorm2d-125          [-1, 512, 14, 14]           1,024            ReLU-126          [-1, 512, 14, 14]               0          Conv2d-127         [-1, 1024, 14, 14]         524,288     BatchNorm2d-128         [-1, 1024, 14, 14]           2,048            ReLU-129         [-1, 1024, 14, 14]               0      Bottleneck-130         [-1, 1024, 14, 14]               0          Conv2d-131          [-1, 512, 14, 14]         524,288     BatchNorm2d-132          [-1, 512, 14, 14]           1,024            ReLU-133          [-1, 512, 14, 14]               0          Conv2d-134          [-1, 512, 14, 14]          73,728     BatchNorm2d-135          [-1, 512, 14, 14]           1,024            ReLU-136          [-1, 512, 14, 14]               0          Conv2d-137         [-1, 1024, 14, 14]         524,288     BatchNorm2d-138         [-1, 1024, 14, 14]           2,048            ReLU-139         [-1, 1024, 14, 14]               0      Bottleneck-140         [-1, 1024, 14, 14]               0          Conv2d-141         [-1, 1024, 14, 14]       1,048,576     BatchNorm2d-142         [-1, 1024, 14, 14]           2,048            ReLU-143         [-1, 1024, 14, 14]               0          Conv2d-144           [-1, 1024, 7, 7]         294,912     BatchNorm2d-145           [-1, 1024, 7, 7]           2,048            ReLU-146           [-1, 1024, 7, 7]               0          Conv2d-147           [-1, 2048, 7, 7]       2,097,152     BatchNorm2d-148           [-1, 2048, 7, 7]           4,096          Conv2d-149           [-1, 2048, 7, 7]       2,097,152     BatchNorm2d-150           [-1, 2048, 7, 7]           4,096            ReLU-151           [-1, 2048, 7, 7]               0      Bottleneck-152           [-1, 2048, 7, 7]               0          Conv2d-153           [-1, 1024, 7, 7]       2,097,152     BatchNorm2d-154           [-1, 1024, 7, 7]           2,048            ReLU-155           [-1, 1024, 7, 7]               0          Conv2d-156           [-1, 1024, 7, 7]         294,912     BatchNorm2d-157           [-1, 1024, 7, 7]           2,048            ReLU-158           [-1, 1024, 7, 7]               0          Conv2d-159           [-1, 2048, 7, 7]       2,097,152     BatchNorm2d-160           [-1, 2048, 7, 7]           4,096            ReLU-161           [-1, 2048, 7, 7]               0      Bottleneck-162           [-1, 2048, 7, 7]               0          Conv2d-163           [-1, 1024, 7, 7]       2,097,152     BatchNorm2d-164           [-1, 1024, 7, 7]           2,048            ReLU-165           [-1, 1024, 7, 7]               0          Conv2d-166           [-1, 1024, 7, 7]         294,912     BatchNorm2d-167           [-1, 1024, 7, 7]           2,048            ReLU-168           [-1, 1024, 7, 7]               0          Conv2d-169           [-1, 2048, 7, 7]       2,097,152     BatchNorm2d-170           [-1, 2048, 7, 7]           4,096            ReLU-171           [-1, 2048, 7, 7]               0      Bottleneck-172           [-1, 2048, 7, 7]               0AdaptiveAvgPool2d-173          [-1, 2048, 1, 1]               0         Dropout-174                 [-1, 2048]               0          Linear-175                  [-1, 512]       1,048,576     BatchNorm1d-176                  [-1, 512]           1,024================================================================Total params: 24,029,504Trainable params: 1,049,600Non-trainable params: 22,979,904----------------------------------------------------------------Input size (MB): 0.57Forward/backward pass size (MB): 361.80Params size (MB): 91.67Estimated Total Size (MB): 454.04----------------------------------------------------------------```The encoder is based on the [ResNeXt-50 32x4d](http://pytorch.org/docs/stable/torchvision/models.html) model introduced by [Xie et al. 2017](http://arxiv.org/abs/1611.05431). The choice of this architecture is motivated by the results of [Bianco et al. 2018](http://arxiv.org/abs/1810.00736) and [Reddi et al. 2020](http://arxiv.org/abs/1911.02549) that indicate it has a better overall performance in comparison with [ResNet50](http://pytorch.org/docs/stable/torchvision/models.html) introduced by [He et al. 2015](https://arxiv.org/abs/1512.03385).```----------------------------------------------------------------                            Decoder----------------------------------------------------------------        Layer (type)               Output Shape         Param ================================================================         Embedding-1              [-1, 10, 512]       4,534,272               GRU-2   [[-1, 11, 512], [-1, 1, 512]]          0           Dropout-3              [-1, 11, 512]               0            Linear-4             [-1, 11, 8856]       4,543,128================================================================Total params: 9,077,400Trainable params: 9,077,400Non-trainable params: 0----------------------------------------------------------------Input size (MB): 0.04Forward/backward pass size (MB): 21.17Params size (MB): 34.63Estimated Total Size (MB): 55.84----------------------------------------------------------------```The decoder uses a single recurrent layer inspired by the architecture from [Vinyals et al. 2015](http://arxiv.org/abs/1411.4555). However, it replaces the LSTM with a [GRU](http://arxiv.org/abs/1406.1078) based on the image captioning results published by [Gu et al. 2017](http://arxiv.org/abs/1612.07086) and includes a Dropout layer motivated by the observations of [Eckhardt 2018](http://towardsdatascience.com/choosing-the-right-hyperparameters-for-a-simple-lstm-using-keras-f8e9ed76f046).The values of  `vocab_threshold`, `embed_size`, and `hidden_size` hyperparameters are set according to [Vinyals et al. 2015](http://arxiv.org/abs/1411.4555), while `batch_size` uses the same as [Xu et al. 2015](http://arxiv.org/abs/1502.03044). The `num_epochs` is chosen arbitrarily. (Optional) Task 2Note that we have provided a recommended image transform `transform_train` for pre-processing the training images, but you are welcome (and encouraged!) to modify it as you wish.  When modifying this transform, keep in mind that:- the images in the dataset have varying heights and widths, and- if using a pre-trained model, you must perform the corresponding appropriate normalization. Question 2**Question:** How did you select the transform in `transform_train`?  If you left the transform at its provided value, why do you think that it is a good choice for your CNN architecture?**Answer:**The provided `transform_train` pipeline is already a good choice. It implements augmentation through random cropping, which is paired with resizing to provide better results, and horizontal flipping of the original images, which tends to maintain the object context unaltered (e.g., land and water are below the sky). It also normalizes the image channels with the mean and variance values from PyTorch model zoo, which are the same ones used to pre-train the feature extraction layers of the encoder. In comparison, `transform_val` and `transform_test` follow the same pipeline without augmentation. Task 3Next, you will specify a Python list containing the learnable parameters of the model.  For instance, if you decide to make all weights in the decoder trainable, but only want to train the weights in the embedding layer of the encoder, then you should set `params` to something like:```params = list(decoder.parameters()) + list(encoder.embed.parameters())``` Question 3**Question:** How did you select the trainable parameters of your architecture?  Why do you think this is a good choice?**Answer:**The parameters of layers 1-173 of the encoder are pre-trained on [ImageNet](http://arxiv.org/abs/1409.0575) and layers 174-176 are re-trained on [COCO](http://arxiv.org/abs/1405.0312) to generate embedded image features using [fixed transfer-learning](http://cs231n.github.io/transfer-learning). The layers 1-4 of the decoder are re-trained on [COCO](http://arxiv.org/abs/1405.0312). This is a good idea because both datasets comprise a large collection of RGB images of diverse objects in multiple contexts and cycle/effort time is very limited for this project. Task 4Finally, you will select an [optimizer](http://pytorch.org/docs/master/optim.htmltorch.optim.Optimizer). Question 4**Question:** How did you select the optimizer used to train your model?**Answer:**The trainable parameters are optimized using [Adam](http://arxiv.org/abs/1412.6980) with an adaptive learning rate of $0.001$ following [Xu et al. 2014](http://arxiv.org/abs/1502.03044) design choice for [COCO](http://arxiv.org/abs/1405.0312).<jupyter_code>import math
import multiprocessing
import os

import torch
import torch.nn as nn
from torchvision import transforms

from data_loader import get_loader
from model import EncoderCNN, DecoderRNN

# TODO #1: Select appropriate values for the Python variables below.
batch_size = 64                                  # batch size
vocab_threshold = 5                              # minimum word count threshold
vocab_from_file = False                          # if True, load existing vocab file
embed_size = 512                                 # dimensionality of image and word embeddings
hidden_size = 512                                # number of features in hidden state of the RNN decoder
num_epochs = 5                                   # number of training epochs
save_every = 1                                   # determines frequency of saving model weights
print_every = 1000                               # determines window for printing average loss
log_file = 'training_log.txt'                    # name of file with saved training loss and perplexity
model_dir = os.path.join('.', 'models')          # path to save the trained CNN encoder and RNN decoder

# (Optional) TODO #2: Amend the image transform below.
transform_train = transforms.Compose([transforms.Resize(256),
                                      transforms.RandomCrop(224),
                                      transforms.RandomHorizontalFlip(),
                                      transforms.ToTensor(),
                                      transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])

# Build data loader.
data_loader = get_loader(transform=transform_train,
                         mode='train',
                         batch_size=batch_size,
                         vocab_threshold=vocab_threshold,
                         vocab_from_file=vocab_from_file,
                         num_workers=multiprocessing.cpu_count(),
                         cocoapi_loc=os.path.join('..', '..', 'Data'))

# The size of the vocabulary.
vocab_size = len(data_loader.dataset.vocab)

# Initialize the encoder and decoder.
encoder = EncoderCNN(embed_size)
decoder = DecoderRNN(embed_size, hidden_size, vocab_size)

# Move models to GPU if CUDA is available.
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
encoder, decoder = encoder.to(device), decoder.to(device)

# Define the loss function.
criterion = nn.CrossEntropyLoss().cuda() if torch.cuda.is_available() else nn.CrossEntropyLoss()

# TODO #3: Specify the learnable parameters of the model.
params = list(decoder.parameters()) + list(encoder.embedding.parameters())

# TODO #4: Define the optimizer.
optimizer = torch.optim.Adam(params, lr=0.001)

# Set the total number of training steps per epoch.
total_step = math.ceil(len(data_loader.dataset.caption_lengths) / data_loader.batch_sampler.batch_size)

# Get device name with gpu option.
if device.type == 'cuda':
    print('Using: {}'.format(torch.cuda.get_device_name(0)))

# Get device name with cpu option.
else:
    print('Using: {} with {} threads'.format(device, torch.get_num_threads()))<jupyter_output>loading annotations into memory...
Done (t=1.05s)
creating index...
index created!
[0/414113] Tokenizing captions...
[100000/414113] Tokenizing captions...
[200000/414113] Tokenizing captions...
[300000/414113] Tokenizing captions...
[400000/414113] Tokenizing captions...
loading annotations into memory...
Done (t=1.06s)
creating index...
index created!
Obtaining caption lengths...<jupyter_text>Step 2: Train your ModelOnce you have executed the code cell in **Step 1**, the training procedure below should run without issue.It is completely fine to leave the code cell below as-is without modifications to train your model.  However, if you would like to modify the code used to train the model below, you must ensure that your changes are easily parsed by your reviewer.  In other words, make sure to provide appropriate comments to describe how your code works!You may find it useful to load saved weights to resume training.  In that case, note the names of the files containing the encoder and decoder weights that you'd like to load (`encoder_file` and `decoder_file`).  Then you can load the weights by using the lines below:```python Load pre-trained weights before resuming training.encoder.load_state_dict(torch.load(os.path.join('./models', encoder_file)))decoder.load_state_dict(torch.load(os.path.join('./models', decoder_file)))```While trying out parameters, make sure to take extensive notes and record the settings that you used in your various training runs.  In particular, you don't want to encounter a situation where you've trained a model for several hours but can't remember what settings you used :). A Note on Tuning HyperparametersTo figure out how well your model is doing, you can look at how the training loss and perplexity evolve during training - and for the purposes of this project, you are encouraged to amend the hyperparameters based on this information.However, this will not tell you if your model is overfitting to the training data, and, unfortunately, overfitting is a problem that is commonly encountered when training image captioning models.For this project, you need not worry about overfitting. **This project does not have strict requirements regarding the performance of your model**, and you just need to demonstrate that your model has learned **_something_** when you generate captions on the test data.  For now, we strongly encourage you to train your model for the suggested 3 epochs without worrying about performance; then, you should immediately transition to the next notebook in the sequence (**3_Inference.ipynb**) to see how your model performs on the test data.  If your model needs to be changed, you can come back to this notebook, amend hyperparameters (if necessary), and re-train the model.That said, if you would like to go above and beyond in this project, you can read about some approaches to minimizing overfitting in section 4.3.1 of [this paper](http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7505636).  In the next (optional) step of this notebook, we provide some guidance for assessing the performance on the validation dataset.<jupyter_code>import sys

import numpy as np
import torch.utils.data as data

# Open the training log file.
f = open(log_file, 'w')

# Iterate over the training dataset.
for epoch in range(1, num_epochs+1):

    for i_step in range(1, total_step+1):

        # Randomly sample a caption length, and sample indices with that length.
        indices = data_loader.dataset.get_train_indices()
        # Create and assign a batch sampler to retrieve a batch with the sampled indices.
        new_sampler = data.sampler.SubsetRandomSampler(indices=indices)
        data_loader.batch_sampler.sampler = new_sampler

        # Obtain the batch.
        images, captions = next(iter(data_loader))

        # Move batch of images and captions to GPU if CUDA is available.
        images = images.to(device)
        captions = captions.to(device)

        # Zero the gradients.
        decoder.zero_grad()
        encoder.zero_grad()

        # Pass the inputs through the CNN-RNN model.
        features = encoder(images)
        outputs = decoder(features, captions)

        # Calculate the batch loss.
        loss = criterion(outputs.view(-1, vocab_size), captions.view(-1))

        # Backward pass.
        loss.backward()

        # Update the parameters in the optimizer.
        optimizer.step()

        # Get training statistics.
        message = 'Epoch [%d/%d], Step [%d/%d], Loss: %.4f, Perplexity: %5.4f'
        stats = message % (epoch, num_epochs, i_step, total_step, loss.item(), np.exp(loss.item()))

        # Print training statistics (on same line).
        print('\r'+stats, end="")
        sys.stdout.flush()

        # Print training statistics to file.
        f.write(stats + '\n')
        f.flush()

        # Print training statistics (on different line).
        if i_step % print_every == 0:
            print('\r'+stats)

    # Save the weights.
    if epoch % save_every == 0:
        torch.save(decoder.state_dict(), os.path.join(model_dir, 'decoder-{}.pkl'.format(epoch)))
        torch.save(encoder.state_dict(), os.path.join(model_dir, 'encoder-{}.pkl'.format(epoch)))

# Close the training log file.
f.close()<jupyter_output>Epoch [1/5], Step [1000/6471], Loss: 2.7756, Perplexity: 16.0484
Epoch [1/5], Step [2000/6471], Loss: 2.3028, Perplexity: 10.00190
Epoch [1/5], Step [3000/6471], Loss: 2.4603, Perplexity: 11.7084
Epoch [1/5], Step [4000/6471], Loss: 3.1333, Perplexity: 22.94858
Epoch [1/5], Step [5000/6471], Loss: 2.3320, Perplexity: 10.2986
Epoch [1/5], Step [6000/6471], Loss: 2.4834, Perplexity: 11.9823
Epoch [2/5], Step [1000/6471], Loss: 2.1592, Perplexity: 8.66421
Epoch [2/5], Step [2000/6471], Loss: 2.2683, Perplexity: 9.66316
Epoch [2/5], Step [3000/6471], Loss: 1.9266, Perplexity: 6.86614
Epoch [2/5], Step [4000/6471], Loss: 2.1426, Perplexity: 8.521547
Epoch [2/5], Step [5000/6471], Loss: 2.0458, Perplexity: 7.735020
Epoch [2/5], Step [6000/6471], Loss: 2.0632, Perplexity: 7.87098
Epoch [3/5], Step [1000/6471], Loss: 2.0422, Perplexity: 7.70749
Epoch [3/5], Step [2000/6471], Loss: 2.0533, Perplexity: 7.79340
Epoch [3/5], Step [3000/6471], Loss: 1.9583, Perplexity: 7.08762
Epoch [3/5], Step [40[...]<jupyter_text>Step 3: (Optional) Validate your ModelTo assess potential overfitting, one approach is to assess performance on a validation set.  If you decide to do this **optional** task, you are required to first complete all of the steps in the next notebook in the sequence (**3_Inference.ipynb**); as part of that notebook, you will write and test code (specifically, the `sample` method in the `DecoderRNN` class) that uses your RNN decoder to generate captions.  That code will prove incredibly useful here.If you decide to validate your model, please do not edit the data loader in **data_loader.py**.  Instead, create a new file named **data_loader_val.py** containing the code for obtaining the data loader for the validation data.  You can access:- the validation images at filepath `'/opt/cocoapi/images/train2014/'`, and- the validation image caption annotation file at filepath `'/opt/cocoapi/annotations/captions_val2014.json'`.The suggested approach to validating your model involves creating a json file such as [this one](https://github.com/cocodataset/cocoapi/blob/master/results/captions_val2014_fakecap_results.json) containing your model's predicted captions for the validation images.  Then, you can write your own script or use one that you [find online](https://github.com/tylin/coco-caption) to calculate the BLEU score of your model.  You can read more about the BLEU score, along with other evaluation metrics (such as TEOR and Cider) in section 4.1 of [this paper](https://arxiv.org/pdf/1411.4555.pdf).  For more information about how to use the annotation file, check out the [website](http://cocodataset.org/download) for the COCO dataset.<jupyter_code>import matplotlib.pyplot as plt

import nltk
from nltk.translate.meteor_score import meteor_score

# Download the body of knowledge to use.
nltk.download('wordnet')

# Seed random generators.
torch.manual_seed(42)
np.random.seed(42)

# Define a transform to pre-process the validation images.
transform_val = transforms.Compose([transforms.Resize(256),
                                    transforms.CenterCrop(224),
                                    transforms.ToTensor(),
                                    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])

# Create the data loader.
data_loader = get_loader(transform=transform_val,
                         mode='val',
                         batch_size=1,
                         num_workers=multiprocessing.cpu_count(),
                         cocoapi_loc=os.path.join('..', '..', 'Data'))

# Specify the saved image captioning models to load.
encoder_files = [f for f in os.listdir(model_dir) if f.startswith('encoder') and f.endswith('.pkl')]
decoder_files = [f for f in os.listdir(model_dir) if f.startswith('decoder') and f.endswith('.pkl')]
assert len(encoder_files) == len(decoder_files)

# Validate the image captioning models.
with torch.no_grad():
    max_score = 0.0
    scores = torch.zeros(len(encoder_files))
    for idx in torch.arange(len(encoder_files)):

        # Load the trained weights.
        encoder.load_state_dict(torch.load(os.path.join(model_dir, encoder_files[idx])))
        decoder.load_state_dict(torch.load(os.path.join(model_dir, decoder_files[idx])))

        # Set the evaluation mode.
        encoder.eval()
        decoder.eval()

        # Move neural networks to GPU if CUDA is available.
        encoder, decoder = encoder.to(device), decoder.to(device)

        # Calculate the meteor_score of the image captioning model.
        for (image, caption) in data_loader:
            caption = [''.join(c) for c in caption]
            image = image.to(device)
            features = encoder(image).unsqueeze(1)
            output = decoder.sample(features)
            prediction = data_loader.dataset.clean_sentence(output)
            scores[idx] += meteor_score(str(caption), prediction)

        # Save best performing neural networks.
        scores[idx] /= len(data_loader.dataset)
        if max_score < scores[idx]:
            min_score = scores[idx]
            torch.save(encoder.state_dict(), os.path.join(model_dir, 'encoder-deploy.pkl'))
            torch.save(decoder.state_dict(), os.path.join(model_dir, 'decoder-deploy.pkl'))

        # Display the meteor_score of the image captioning model.
        print('Meteor Score of checkpoint {}: {:0.4f}'.format(idx+1, scores[idx]))

# Plot all results.
plt.figure(figsize=(24, 16))
plt.plot(scores)<jupyter_output>[nltk_data] Downloading package wordnet to /home/gdonatti/nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
{'fraction_non_alphanumeric': 0.11980426185666733, 'fraction_numerical': 0.0967310592050983, 'mean_word_length': 1.9051987767584098, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 10, 'https://': 7, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 80, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '666011', 'license': 'MIT', 'n_tokens_mistral': 12499, 'n_tokens_neox': 9677, 'n_words': 3698, 'path': '2_Training.ipynb', 'repo_name': 'sdonatti/nd891-project-image-captioning', 'size': '35149'}