{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# TP 4 : machine learning using neural network for text data\n",
        "\n",
        "In this practical session, we are going to build simple neural models able to classify reviews as positive or negative. The dataset used comes from AlloCine.\n",
        "The goals are to understand how to use pretrained embeddings.\n",
        "\n",
        "you need to load:\n",
        "- Allocine: Train, dev and test sets\n",
        "- Embeddings: cc.fr.300.10000.vec (10,000 first lines of the original file)\n",
        "\n",
        "## Pre-trained word embeddings\n",
        "Define a neural network that takes as input pre-trained word embeddings (here FastText embeddings). Words are represented by real-valued vectors from FastText. A review is represented by a vector that is the average or the sum of the word vectors.\n",
        "\n",
        "So instead of having an input vector of size 5000, we now have an input vector of size e.g. 300, that represents the ‘average’, combined meaning of all the words in the document taken together.\n"
      ],
      "metadata": {
        "id": "jShhTl5Mftkw"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Useful imports\n",
        "\n",
        "Here we also:\n",
        "* Look at the availability of a GPU. Reminder: in Collab, you have to go to Edit/Notebook settings to set the use of a GPU\n",
        "* Setting a seed, for reproducibility: https://pytorch.org/docs/stable/notes/randomness.html\n"
      ],
      "metadata": {
        "id": "mT2uF3G6HXko"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import time\n",
        "import pandas as pd\n",
        "import numpy as np\n",
        "# torch and torch modules to deal with text data\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "from torchtext.data.utils import get_tokenizer\n",
        "from torchtext.vocab import build_vocab_from_iterator\n",
        "from torch.utils.data import DataLoader\n",
        "# you can use scikit to print scores\n",
        "from sklearn.metrics import classification_report\n",
        "\n",
        "# For reproducibility, set a seed\n",
        "torch.manual_seed(0)\n",
        "\n",
        "# Check for GPU\n",
        "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
        "print(device)"
      ],
      "metadata": {
        "id": "nB_k89m8xAOt",
        "outputId": "b24410ea-3af2-412c-bc1c-1ba4447835fb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "cuda\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Paths to data:"
      ],
      "metadata": {
        "id": "taGY9N-PJvWS"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Data files\n",
        "train_file = \"allocine_train.tsv\"\n",
        "dev_file = \"allocine_dev.tsv\"\n",
        "test_file = \"allocine_test.tsv\"\n",
        "# embeddings\n",
        "embed_file='cc.fr.300.10000.vec'"
      ],
      "metadata": {
        "id": "kGty4hWCJurB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Part 0: Read and load the data\n",
        "\n",
        "The simplest solution is to use the DataLoader from PyTorch:    \n",
        "* the doc here https://pytorch.org/docs/stable/data.html and here https://pytorch.org/tutorials/beginner/basics/data_tutorial.html\n",
        "* an example of use, with numpy array: https://www.kaggle.com/arunmohan003/sentiment-analysis-using-lstm-pytorch\n",
        "\n",
        "Here, we are going to define our own Dataset class instead of using numpy arrays. It allows for a a finer definition of the behavior of our dataset, and it's easy to reuse.\n",
        "* Dataset is an abstract class in PyTorch, meaning it can't be used as is, it has to be redefined using inheritance https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset\n",
        "  * you must at least overwrite the ```__getitem__()``` method, supporting fetching a data sample for a given key.\n",
        "  * in practice, you also overwrite the ```__init__()``` to explain how to initialize the dataset, and the ```__len__``` to return the right size for the dataset\n",
        "\n",
        "You can also find many datasets for text ready to load in pytorch on: https://pytorch.org/text/stable/datasets.html"
      ],
      "metadata": {
        "id": "Wv6H41YoFycw"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1- Load data (code given)\n",
        "\n",
        "Read the code below that allows to load the data, note that:\n",
        "- we tokenize the text (here a simple tokenization based on spaces)\n",
        "- we build the vocabulary corresponding to the training data:\n",
        "  - the vocabulary corresponds to the set of unique tokens\n",
        "  - only tokens in the training data are known by the system\n",
        "  - the vocabulary here is a Torch specific object, more details in section 4 below\n",
        "\n",
        "▶▶ **Question:** why do we use only tokens in the training set to build the vocabulary? What do we do with the dev and test sets?"
      ],
      "metadata": {
        "id": "04vEei9QHPou"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Here we create a custom Dataset class that inherits from the Dataset class in PyTorch\n",
        "# A custom Dataset class must implement three functions: __init__, __len__, and __getitem__\n",
        "\n",
        "\n",
        "class Dataset(torch.utils.data.Dataset):\n",
        "\n",
        "    def __init__(self, tsv_file, vocab=None ):\n",
        "      \"\"\" (REQUIRED) Here we save the location of our input file,\n",
        "        load the data, i.e. retrieve the list of texts and associated labels,\n",
        "        build the vocabulary if none is given,\n",
        "        and define the pipelines used to prepare the data \"\"\"\n",
        "      self.tsv_file = tsv_file\n",
        "      self.data, self.label_list = self.load_data( )\n",
        "      # splits the string sentence by space, can t make the fr tokenzer work\n",
        "      self.tokenizer = get_tokenizer( None )\n",
        "      self.vocab = vocab\n",
        "      if not vocab:\n",
        "        self.build_vocab()\n",
        "      # pipelines for text and label\n",
        "      self.text_pipeline = lambda x: self.vocab(self.tokenizer(x)) #return a list of indices from a text\n",
        "      self.label_pipeline = lambda x: int(x) #simple mapping to self\n",
        "\n",
        "    def load_data( self ):\n",
        "      \"\"\" Read a tsv file and return the list of texts and associated labels\"\"\"\n",
        "      data = pd.read_csv( self.tsv_file, header=0, delimiter=\"\\t\", quoting=3)\n",
        "      instances = []\n",
        "      label_list = []\n",
        "      for i in data.index:\n",
        "        label_list.append( data[\"sentiment\"][i] )\n",
        "        instances.append( data[\"review\"][i] )\n",
        "      return instances, label_list\n",
        "\n",
        "    def build_vocab(self):\n",
        "      \"\"\" Build the vocabulary, i.e. retrieve the list of unique tokens\n",
        "      appearing in the corpus (= training set). Se also add a specific index\n",
        "      corresponding to unknown words.  \"\"\"\n",
        "      self.vocab = build_vocab_from_iterator(self.yield_tokens(), specials=[\"<unk>\"])\n",
        "      self.vocab.set_default_index(self.vocab[\"<unk>\"])\n",
        "\n",
        "    def yield_tokens(self):\n",
        "      \"\"\" Iterator on tokens \"\"\"\n",
        "      for text in self.data:\n",
        "        yield self.tokenizer(text)\n",
        "\n",
        "    def __len__(self):\n",
        "      \"\"\" (REQUIRED) Return the len of the data,\n",
        "      i.e. the total number of instances \"\"\"\n",
        "      return len(self.data)\n",
        "\n",
        "    def __getitem__(self, index):\n",
        "      \"\"\" (REQUIRED) Return a specific instance in a format that can be\n",
        "      processed by Pytorch, i.e. torch tensors \"\"\"\n",
        "      return (\n",
        "            tuple( [torch.tensor(self.text_pipeline( self.data[index] ), dtype=torch.int64),\n",
        "                    torch.tensor( self.label_pipeline( self.label_list[index] ), dtype=torch.int64) ] )\n",
        "        )"
      ],
      "metadata": {
        "id": "GdK1WAmcFYHS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 2- Generate data batches and iterator (code given)\n",
        "\n",
        "Then, we use *torch.utils.data.DataLoader* with a Dataset object as built by the code above. DataLoader has an argument to set the size of the batches, but since we have variable-size input sequences, we need to specify how to build the batches. This is done by redefining the function *collate_fn* used by *DataLoader*.\n",
        "\n",
        "```\n",
        "dataloader = DataLoader(dataset, batch_size=8, shuffle=False, collate_fn=collate_fn)\n",
        "```\n",
        "\n",
        "Below:\n",
        "* the text entries in the original data batch input are packed into a list and concatenated as a single tensor.\n",
        "* the offset is a tensor of delimiters to represent the beginning index of the individual sequence in the text tensor\n",
        "* Label is a tensor saving the labels of individual text entries.\n",
        "\n",
        "The offsets are used to retrieve the individual sequences in each batch (the sequences are concatenated)."
      ],
      "metadata": {
        "id": "bG3T9LQFTD73"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# This function explains how we process data to make batches of instances\n",
        "# - The list of texts / reviews that is returned is similar to a list of list:\n",
        "# each element is a batch, ie. a ensemble of BATCH_SIZE texts. But instead of\n",
        "# creating sublists, PyTorch concatenates all the tensors corresponding to\n",
        "# each text sequence into one tensor.\n",
        "# - The list of labels is the list of list of labels for each batch\n",
        "# - The offsets are used to save the position of each individual instance\n",
        "# within the big tensor\n",
        "def collate_fn(batch):\n",
        "    label_list, text_list, offsets = [], [], [0]\n",
        "    for ( _text, _label) in batch:\n",
        "         text_list.append( _text )\n",
        "         label_list.append( _label )\n",
        "         offsets.append(_text.size(0))\n",
        "    label = torch.tensor(label_list, dtype=torch.int64) #tensor of labels for a batch\n",
        "    offsets = torch.tensor(offsets[:-1]).cumsum(dim=0) #tensor of offset indices for a batch\n",
        "    text_list = torch.cat(text_list) # <--- here we concatenate the reviews in the batch\n",
        "    return text_list.to(device), label.to(device), offsets.to(device) #move the data to GPU"
      ],
      "metadata": {
        "id": "oG0ZEYvYccBr"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 3- Exercise: Load the data\n",
        "\n",
        "* Use the code above to load the training and dev data with a batch size of 1:\n",
        "  * First create an instance of the Dataset class\n",
        "  * Then use this instance to create an instance of the DataLoader class with a batch size of 2, with NO shuffling of the samples, and using the *collate_fn* function defined above. Recall that the DataLoader class has the following parameters:\n",
        "  ```\n",
        "  torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=None, collate_fn=None)\n",
        "  ```\n",
        "* Print the first two elements in the Dataset object built on the train set, and the first element in the DataLoader object built on the train. Print also the associated labels. Does it seem coherent?\n",
        "\n",
        "Once you checked that is seems ok, reload the data but this time, shuffle the data during loading."
      ],
      "metadata": {
        "id": "U0ueXxdpZcqx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load the training and development data\n"
      ],
      "metadata": {
        "id": "81k7Iaroayx0"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 0.4 Exercise: understand the Vocab object\n",
        "\n",
        "Here the **vocabulary** is a specific object in Pytorch: https://pytorch.org/text/stable/vocab.html\n",
        "\n",
        "For example, the vocabulary directly converts a list of tokens into integers, see below.\n",
        "\n",
        "Now try to:\n",
        "* Retrieve the indices of a specific word, e.g. 'mauvais'\n",
        "* Retrieve a word from its index, e.g. 368\n",
        "* You can also directly convert a sentence to a list of indices, using the *text_pipeline* defined in the *Dataset* class, try with:\n",
        "  * 'Avant cette série, je ne connaissais que Urgence'\n",
        "  * 'Avant cette gibberish, je ne connaissais que Urgence'\n",
        "  * what happened when you use a word that is unknown?"
      ],
      "metadata": {
        "id": "Tus9Kedas5dq"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Hints: look at these functions\n",
        "* lookup_indices(tokens: List[str]) → List[int]\n",
        "* lookup_token(index: int) → str"
      ],
      "metadata": {
        "id": "BR-hQMJlUfPR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "train.vocab(['Avant', 'cette', 'série', ','])"
      ],
      "metadata": {
        "id": "tb6TYA9Is5v6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "D5stQTekbC8p"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "5t6R_WeZbC_7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "UfPGcBdZbDCz"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "pUFUmVS2bDFu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Part 1- Using pretrained embeddings\n",
        "\n",
        "The first option would be to use randomly initialized word embeddings.\n",
        "It allows the use of dense, real-valued input, that could be updated during training.\n",
        "However, we probably don't have enough data to build good representations for our problem during training.\n",
        "One solution is to use pre-trained word embeddings, built over very big corpora with the aim of building good generic representations of the meaning of words.\n",
        "\n",
        "Upload the file *cc.fr.300.10000.vec': first 10,000 lines of the FastText embeddings for French, https://fasttext.cc/docs/en/crawl-vectors.html.\n",
        "\n",
        "* **Each word is associated to a real-valued and low-dimensional vector** (e.g. 300 dimensions). Crucially,  the  neural  network  will  also  learn / update the  embeddings  during  training (if not freezed):  the  embeddings  of  the network are also parameters that are optimized according to the loss function, allowing the model to learn a better representation of the words.\n",
        "\n",
        "* And **each review is represented by a vector** that should represent all the words it contains. One way to do that is to use **the average of the word vectors** (another typical option is to sum them). Instead of a bag-of-words representation of thousands of dimensions (the size of the vocabulary), we will thus end with an input vector of size e.g. 300, that represents the ‘average’, combined meaning of all the words in the document taken together."
      ],
      "metadata": {
        "id": "UDlM7OZq56HO"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.1 Load the vectors (code given)\n",
        "\n",
        "The function below loads the pre-trained embeddings, returning a dictionary mapping a word to its vector, as defined in the fasttext file.\n",
        "\n",
        "Note that the first line of the file gives the number of unique tokens (in the original file, here we only have 9,999 tokens) and the size of the embeddings.\n",
        "\n",
        "At the end, we print the vocabulary and the vector for a specific token."
      ],
      "metadata": {
        "id": "RX2DkAqws1gU"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import io\n",
        "\n",
        "def load_vectors(fname):\n",
        "    fin = io.open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n",
        "    n, d = map(int, fin.readline().split())\n",
        "    print(\"Originally we have: \", n, 'tokens, and vectors of',d, 'dimensions') #here in fact only 10000 words\n",
        "    data = {}\n",
        "    for line in fin:\n",
        "        tokens = line.rstrip().split(' ')\n",
        "        data[tokens[0]] = [float(t) for t in tokens[1:]]\n",
        "    return data\n",
        "\n",
        "vectors = load_vectors( embed_file )\n",
        "print( 'Version with', len( vectors), 'tokens')\n",
        "print(vectors.keys() )\n",
        "print( vectors['de'] )"
      ],
      "metadata": {
        "id": "yd2EEjECv4vk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.2 Build the weight matrix\n",
        "\n",
        "We have a list of words associated to vector.\n",
        "Now we need to specifically retrieve the vectors for the words present in our data, there is no need to keep vectors for all the words.\n",
        "We thus build a matrix over the dataset associating each word present in the dataset to its vector.\n",
        "For each word in dataset’s vocabulary, we check if it is in FastText’s vocabulary:\n",
        "* if yes: load its pre-trained word vector.\n",
        "* else: we initialize a random vector.\n",
        "\n",
        "\n",
        "**Question:**  Examine the coverage, i.e.:\n",
        "* print the number of tokens from FastText found in the training set\n",
        "* and the number of unknown words."
      ],
      "metadata": {
        "id": "GTA0vXeevSuO"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load the weight matrix: modify the code below to check the coverage of the\n",
        "# pre-trained embeddings\n",
        "emb_dim = 300\n",
        "matrix_len = len(train.vocab)\n",
        "weights_matrix = np.zeros((matrix_len, emb_dim))\n",
        "\n",
        "for i in range(0, len(train.vocab)):\n",
        "    word = train.vocab.lookup_token(i)\n",
        "    try:\n",
        "        weights_matrix[i] = vectors[word]\n",
        "    except KeyError:\n",
        "        weights_matrix[i] = np.random.normal(scale=0.6, size=(emb_dim, ))\n",
        "weights_matrix = torch.from_numpy(weights_matrix).to( torch.float32)\n",
        "\n",
        "print(weights_matrix)"
      ],
      "metadata": {
        "id": "4XXFTaRxvRNk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.3 Exercise: Model definition\n",
        "\n",
        "#### a/ Define the embedding layer:\n",
        "Now modify your model to add this embedding layer in the __init__() function below:\n",
        "\n",
        "* Define *self.embedding_bag*: a layer combining the word embeddings for the words. Here we just give the definition of the layer, i.e.:\n",
        "  * we use pre initialized weights\n",
        "  * we want to combine the embeddings by doing the average\n",
        "See ```nn.EmbeddingBeg.from_pretrained( ..)```, https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html\n",
        "* Retrieve the *embedding dimensions* to be used as parameter for the first linear function (look at the *EnbeddingBag* class definition).\n",
        "\n",
        "#### b/ Use the embedding layer\n",
        "Now you need to tell the model when to use this embedding layer, thus you need to modify the *forward()* function to say that it needs to first *embed* the input before going through the linear and non linear layers.\n",
        "\n",
        "Look at the example in the doc: https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html\n",
        "Note that this embedding layer needs the information about the offset, to retrieve the sequences / individual documents in the batch.\n",
        "\n"
      ],
      "metadata": {
        "id": "VcLWQgu877rQ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "class FeedforwardNeuralNetModel(nn.Module):\n",
        "    def __init__(self, hidden_dim, output_dim, weights_matrix):\n",
        "        # calls the init function of nn.Module.  Dont get confused by syntax,\n",
        "        # just always do it in an nn.Module\n",
        "        super(FeedforwardNeuralNetModel, self).__init__()\n",
        "\n",
        "        # Embedding layer\n",
        "        # ....\n",
        "\n",
        "        # Linear function\n",
        "        self.fc1 = nn.Linear(embed_dim, hidden_dim)\n",
        "\n",
        "        # Non-linearity\n",
        "        self.sigmoid = nn.Sigmoid()\n",
        "\n",
        "        # Linear function (readout)\n",
        "        self.fc2 = nn.Linear(hidden_dim, output_dim)\n",
        "\n",
        "    def forward(self, text, offsets):\n",
        "        # Embedding layer\n",
        "        # ....\n",
        "\n",
        "        # Linear function\n",
        "        out = self.fc1(embedded)\n",
        "\n",
        "        # Non-linearity\n",
        "        out = self.sigmoid(out)\n",
        "\n",
        "        # Linear function (readout)\n",
        "        out = self.fc2(out)\n",
        "        return out"
      ],
      "metadata": {
        "id": "fXOPuCv_vZrr"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.4 Exercise: Train and evaluation functions (code given)\n",
        "\n",
        "Look at the code below that performs the training and evaluation of your model.\n",
        "Note that:\n",
        "* one epoch is one ieration over the entire training set\n",
        "* each *input* is here a batch of several documents (here 2)\n",
        "* the model computes a loss after making a prediction for each input / batch. We accumulate this loss, and compute a score after seing each batch\n",
        "* at the end of each round / epoch, we print the accumulated loss and accuracy:\n",
        "  * A good indicator that your model is doing what is supposed to, is the loss: it should decrease during training. At the same time, the accuracy on the training set should increase.\n",
        "* in the evaluation procedure, we have to compute score for batched of data, that's why we have slight modifications in the code (use of *extend* tp have a set of predictions)\n",
        "\n",
        "Note: here we need to take into account the offsets in the training and evaluation procedures."
      ],
      "metadata": {
        "id": "UsXmIGqApbxj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def training(model, train_loader, optimizer, num_epochs=5 ):\n",
        "    for epoch in range(num_epochs):\n",
        "        train_loss, total_acc, total_count = 0, 0, 0\n",
        "        for input, label, offsets in train_loader:\n",
        "            # Step1. Clearing the accumulated gradients\n",
        "            optimizer.zero_grad()\n",
        "            # Step 2. Forward pass to get output/logits\n",
        "            outputs = model( input, offsets ) # <---- argument offsets en plus\n",
        "            # Step 3. Compute the loss, gradients, and update the parameters by\n",
        "            # calling optimizer.step()\n",
        "            # - Calculate Loss: softmax --> cross entropy loss\n",
        "            loss = criterion(outputs, label)\n",
        "            # - Getting gradients w.r.t. parameters\n",
        "            loss.backward()\n",
        "            # - Updating parameters\n",
        "            optimizer.step()\n",
        "            # Accumulating the loss over time\n",
        "            train_loss += loss.item()\n",
        "            total_acc += (outputs.argmax(1) == label).sum().item()\n",
        "            total_count += label.size(0)\n",
        "        # Compute accuracy on train set at each epoch\n",
        "        print('Epoch: {}. Loss: {}. ACC {} '.format(epoch, train_loss/len(train), total_acc/len(train)))\n",
        "        total_acc, total_count = 0, 0\n",
        "        train_loss = 0\n",
        "\n",
        "def evaluate( model, dev_loader ):\n",
        "    predictions = []\n",
        "    gold = []\n",
        "    with torch.no_grad():\n",
        "        for input, label, offsets in dev_loader:\n",
        "            probs = model(input, offsets) # <---- fct forward with offsets\n",
        "            # -- to deal with batches\n",
        "            predictions.extend( torch.argmax(probs, dim=1).cpu().numpy() )\n",
        "            gold.extend([int(l) for l in label])\n",
        "    print(classification_report(gold, predictions))\n",
        "    return gold, predictions"
      ],
      "metadata": {
        "id": "US_0JmN5phqs"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 1.3 Exercise: run experiments\n",
        "\n",
        "Look at the code below, it allows to run experiments with the following values for the hyper-parameters:\n",
        "  * batch size = 2\n",
        "  * hidden dimension = 4\n",
        "  * learning rate = 0.1\n",
        "  * number of epochs = 5\n",
        "  * using the Cross Entropy loss function\n",
        "  * using SGD as the optimizer algorithm\n",
        "\n",
        "Questions:\n",
        "  * What is the input dimension?\n",
        "  * What is the output dimension?\n",
        "  * What are the hyper-parameters that could be tuned? Propose a set of values to be tested for each one of them.\n",
        "  * Run the code: what is the behaviour of the loss and accuracy?\n",
        "  * What do you think about the performance of this model?"
      ],
      "metadata": {
        "id": "NC2VtTmv-Q_c"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Set the values of the hyperparameters\n",
        "hidden_dim = 4\n",
        "learning_rate = 0.1\n",
        "num_epochs = 5\n",
        "criterion = nn.CrossEntropyLoss()\n",
        "output_dim = 2"
      ],
      "metadata": {
        "id": "Jod8FnWPs_Vi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Initialize the model\n",
        "model_ffnn = FeedforwardNeuralNetModel( hidden_dim, output_dim, weights_matrix)\n",
        "optimizer = torch.optim.SGD(model_ffnn.parameters(), lr=learning_rate)\n",
        "model_ffnn = model_ffnn.to(device)\n",
        "# Train the model\n",
        "training( model_ffnn, train_loader, optimizer, num_epochs=5 )\n",
        "# Evaluate on dev\n",
        "gold, pred = evaluate( model_ffnn, dev_loader )"
      ],
      "metadata": {
        "id": "1Xug7ygbpAhS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Note:** that we don't use here a SoftMax over the output of the final layer to obtain class probability: this is because this SoftMax application is done in the loss function chosen (*nn.CrossEntropyLoss()*). Be careful, it's not the case of all the loss functions available in PyTorch."
      ],
      "metadata": {
        "id": "OBqQaAf6mxEI"
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "HNaP18nEZNTu"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}