Skip to content
Snippets Groups Projects
Commit e13fd948 authored by chloebt's avatar chloebt
Browse files

add CM 4 and TP 5 and TP 6

parent 91deca49
Branches
Tags
No related merge requests found
%% Cell type:markdown id: tags:
# TP 5 : machine learning using neural network for text data
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.
The goals are to understand how to use pretrained embeddings, and to correctly tune a neural model.
you need to load:
- Allocine: Train, dev and test sets
- Embeddings: cc.fr.300.10000.vec (10,000 first lines of the original file)
## Part 1- Pre-trained word embeddings
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.
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.
## Part 2- Tuning report
Tune the model built on pre-trained word embeddings by testing several values for the different hyper-parameters, and by testing the addition on an hidden layer.
Describe the performance obtained by reporting the scores for each setting on the development set, printing the loss function against the hyper-parameter values, and reporting the score of the best model on the test set.
-------------------------------------
%% Cell type:markdown id: tags:
## Useful imports
Here we also:
* 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
* Setting a seed, for reproducibility: https://pytorch.org/docs/stable/notes/randomness.html
%% Cell type:code id: tags:
```
!pip install -q torchtext==0.14.1 torchdata==0.5.1
```
%% Cell type:code id: tags:
```
import time
import pandas as pd
import numpy as np
# torch and torch modules to deal with text data
import torch
import torch.nn as nn
import torchtext
from torchtext.data import get_tokenizer
#from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from torch.utils.data import DataLoader
# you can use scikit to print scores
from sklearn.metrics import classification_report
# For reproducibility, set a seed
torch.manual_seed(0)
# Check for GPU
device = "cuda" if torch.cuda.is_available() else "cpu"
print(device)
```
%% Cell type:markdown id: tags:
Paths to data:
%% Cell type:code id: tags:
```
# Data files
train_file = "allocine_train.tsv"
dev_file = "allocine_dev.tsv"
test_file = "allocine_test.tsv"
# embeddings
embed_file='cc.fr.300.10000.vec'
```
%% Cell type:markdown id: tags:
## 1- Read and load the data
%% Cell type:markdown id: tags:
### 1.1- The class Dataset (code given)
%% Cell type:markdown id: tags:
Reminder from TP1, the simplest solution is to use the DataLoader from PyTorch:
* the doc here https://pytorch.org/docs/stable/data.html and here https://pytorch.org/tutorials/beginner/basics/data_tutorial.html
* an example of use, with numpy array: https://www.kaggle.com/arunmohan003/sentiment-analysis-using-lstm-pytorch
Here, we are going to define our own Dataset class instead of using numpy arrays. It allows for a finer definition of the behavior of our dataset, and it's easy to reuse.
* 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
* you must at least overwrite the __getitem__() method, supporting fetching a data sample for a given key.
* 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
You can also find many datasets for text ready to load in pytorch on: https://pytorch.org/text/stable/datasets.html
%% Cell type:markdown id: tags:
#### Read and load data (code given)
Read the code below that allows to load the data, note that:
- we tokenize the text (here a simple tokenization based on spaces)
- we build the vocabulary corresponding to the training data:
- the vocabulary corresponds to the set of unique tokens
- only tokens in the training data are known by the system
- the vocabulary here is a Torch specific object, more details in section 0.4 below
▶▶ **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?
%% Cell type:code id: tags:
```
# Here we create a custom Dataset class that inherits from the Dataset class in PyTorch
# A custom Dataset class must implement three functions: __init__, __len__, and __getitem__
class Dataset(torch.utils.data.Dataset):
def __init__(self, tsv_file, vocab=None ):
""" (REQUIRED) Here we save the location of our input file,
load the data, i.e. retrieve the list of texts and associated labels,
build the vocabulary if none is given,
and define the pipelines used to prepare the data """
self.tsv_file = tsv_file
self.data, self.label_list = self.load_data( )
# splits the string sentence by space, can t make the fr tokenzer work
self.tokenizer = get_tokenizer( None )
self.vocab = vocab
if not vocab:
self.build_vocab()
# pipelines for text and label
self.text_pipeline = lambda x: self.vocab(self.tokenizer(x)) #return a list of indices from a text
self.label_pipeline = lambda x: int(x) #simple mapping to self
def load_data( self ):
""" Read a tsv file and return the list of texts and associated labels"""
data = pd.read_csv( self.tsv_file, header=0, delimiter="\t", quoting=3)
instances = []
label_list = []
for i in data.index:
label_list.append( data["sentiment"][i] )
instances.append( data["review"][i] )
return instances, label_list
def build_vocab(self):
""" Build the vocabulary, i.e. retrieve the list of unique tokens
appearing in the corpus (= training set). Se also add a specific index
corresponding to unknown words. """
self.vocab = build_vocab_from_iterator(self.yield_tokens(), specials=["<unk>"])
self.vocab.set_default_index(self.vocab["<unk>"])
def yield_tokens(self):
""" Iterator on tokens """
for text in self.data:
yield self.tokenizer(text)
def __len__(self):
""" (REQUIRED) Return the len of the data,
i.e. the total number of instances """
return len(self.data)
def __getitem__(self, index):
""" (REQUIRED) Return a specific instance in a format that can be
processed by Pytorch, i.e. torch tensors """
return (
tuple( [torch.tensor(self.text_pipeline( self.data[index] ), dtype=torch.int64),
torch.tensor( self.label_pipeline( self.label_list[index] ), dtype=torch.int64) ] )
)
```
%% Cell type:markdown id: tags:
### 1.2- Generate data batches and iterator (code given)
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*.
```
dataloader = DataLoader(dataset, batch_size=8, shuffle=False, collate_fn=collate_fn)
```
Below:
* the text entries in the original data batch input are packed into a list and concatenated as a single tensor.
* the offset is a tensor of delimiters to represent the beginning index of the individual sequence in the text tensor
* Label is a tensor saving the labels of individual text entries.
The offsets are used to retrieve the individual sequences in each batch (the sequences are concatenated).
%% Cell type:code id: tags:
```
# This function explains how we process data to make batches of instances
# - The list of texts / reviews that is returned is similar to a list of list:
# each element is a batch, ie. a ensemble of BATCH_SIZE texts. But instead of
# creating sublists, PyTorch concatenates all the tensors corresponding to
# each text sequence into one tensor.
# - The list of labels is the list of list of labels for each batch
# - The offsets are used to save the position of each individual instance
# within the big tensor
def collate_fn(batch):
label_list, text_list, offsets = [], [], [0]
for ( _text, _label) in batch:
text_list.append( _text )
label_list.append( _label )
offsets.append(_text.size(0))
label = torch.tensor(label_list, dtype=torch.int64) #tensor of labels for a batch
offsets = torch.tensor(offsets[:-1]).cumsum(dim=0) #tensor of offset indices for a batch
text_list = torch.cat(text_list) # <--- here we concatenate the reviews in the batch
return text_list.to(device), label.to(device), offsets.to(device) #move the data to GPU
```
%% Cell type:markdown id: tags:
### 1.3- ▶ Exercise: Load the data
#### ▶ (a) Load the training data
* Use the code above to load the training and dev data with a batch size of 2:
* First create an instance of the Dataset class
* 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:
```
torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=None, collate_fn=None)
```
#### ▶ (b) Print first training instances
* 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?
#### ▶ (c) Shuffling the data
Once you checked that is seems ok, reload the data but this time, shuffle the data during loading.
#### ▶ (d) Load the dev data
Now load the dev data, remembering that you need to give the training vocabulary.
%% Cell type:code id: tags:
```
# Load the training and development data
# ...
```
%% Cell type:markdown id: tags:
### 1.4- ▶ Exercise: understand the Vocab object
Here the **vocabulary** is a specific object in Pytorch: https://pytorch.org/text/stable/vocab.html
For example, the vocabulary directly converts a list of tokens into integers, see below.
Now try to:
* Retrieve the indices of a specific word, e.g. 'mauvais'
* Retrieve a word from its index, e.g. 368
* You can also directly convert a sentence to a list of indices, using the *text_pipeline* defined in the *Dataset* class, try with:
* 'Avant cette série, je ne connaissais que Urgence'
* 'Avant cette gibberish, je ne connaissais que Urgence'
* what happened when you use a word that is unknown?
%% Cell type:markdown id: tags:
Hints: look at these functions
* lookup_indices(tokens: List[str]) → List[int]
* lookup_token(index: int) → str
%% Cell type:code id: tags:
```
```
%% Cell type:code id: tags:
```
```
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
## 2- Using pre-trained embeddings (code given)
The first option would be to use randomly initialized word embeddings.
It allows the use of dense, real-valued input, that could be updated during training.
However, we probably don't have enough data to build good representations for our problem during training.
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.
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.
* **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.
* 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.
The functions to load the embeddings vectors and build the weight matrix are defined below.
%% Cell type:markdown id: tags:
#### 2.1 Load the vectors (code given)
The function below loads the pre-trained embeddings, returning a dictionary mapping a word to its vector, as defined in the fasttext file.
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.
At the end, we print the vocabulary and the vector for a specific token.
%% Cell type:code id: tags:
```
import io
def load_vectors(fname):
fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore')
n, d = map(int, fin.readline().split())
print("Originally we have: ", n, 'tokens, and vectors of',d, 'dimensions') #here in fact only 10000 words
data = {}
for line in fin:
tokens = line.rstrip().split(' ')
data[tokens[0]] = [float(t) for t in tokens[1:]]
return data
vectors = load_vectors( embed_file )
print( 'Version with', len( vectors), 'tokens')
print(vectors.keys() )
print( vectors['de'] )
```
%% Cell type:markdown id: tags:
### 2.2- Build the weight matrix (code given)
We have a list of words associated to vector.
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.
We thus build a matrix over the dataset associating each word present in the dataset to its vector.
For each word in dataset’s vocabulary, we check if it is in FastText’s vocabulary:
* if yes: load its pre-trained word vector.
* else: we initialize a random vector.
The code below will also examine the coverage, i.e.:
* print the number of tokens from FastText found in the training set
* and the number of unknown words.
%% Cell type:code id: tags:
```
# Load the weight matrix: modify the code below to check the coverage of the
# pre-trained embeddings
emb_dim = 300
matrix_len = len(train.vocab)
weights_matrix = np.zeros((matrix_len, emb_dim))
words_found, words_unk = 0,0
for i in range(0, len(train.vocab)):
word = train.vocab.lookup_token(i)
try:
weights_matrix[i] = vectors[word]
words_found += 1
except KeyError:
weights_matrix[i] = np.random.normal(scale=0.6, size=(emb_dim, ))
words_unk += 1
weights_matrix = torch.from_numpy(weights_matrix).to( torch.float32)
print( "Words found:", weights_matrix.size() )
print( "Unk words:", words_unk )
```
%% Cell type:markdown id: tags:
## 3- ▶ Exercise: Model definition
#### (a) Define the embedding layer:
Now modify your model to add an embedding layer in the __init__() function below:
* Define *self.embedding_bag*: a layer combining the word embeddings for the words. Here we just give the definition of the layer, i.e.:
* we use pre initialized weights
* we want to combine the embeddings by doing the average
See ```nn.EmbeddingBeg.from_pretrained( ..)```, https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html
* Retrieve the *embedding dimensions* to be used as parameter for the first linear function (look at the *EnbeddingBag* class definition).
#### (b) Use the embedding layer
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.
Look at the example in the doc: https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html
Note that this embedding layer needs the information about the offset, to retrieve the sequences / individual documents in the batch.
%% Cell type:code id: tags:
```
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, hidden_dim, output_dim, weights_matrix):
# calls the init function of nn.Module. Dont get confused by syntax,
# just always do it in an nn.Module
super(FeedforwardNeuralNetModel, self).__init__()
# Embedding layer
#self.embedding_bag = ...
embed_dim = self.embedding_bag.embedding_dim
# Linear function
self.fc1 = nn.Linear(embed_dim, hidden_dim)
# Non-linearity
self.sigmoid = nn.Sigmoid()
# Linear function (readout)
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, text, offsets):
# Embedding layer
#embedded = ...
# Linear function
out = self.fc1(embedded)
# Non-linearity
out = self.sigmoid(out)
# Linear function (readout)
out = self.fc2(out)
return out
```
%% Cell type:markdown id: tags:
## 4- Train and evaluation (code given)
Look at the code below that performs the training and evaluation of your model.
Note that:
* one epoch is one iteration over the entire training set
* each *input* is here a batch of several documents (here 2)
* 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
* at the end of each round / epoch, we print the accumulated loss and accuracy:
* 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.
* 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* to have a set of predictions)
Note: here we need to take into account the offsets in the training and evaluation procedures.
%% Cell type:code id: tags:
```
import matplotlib.pyplot as plt
import os
def my_plot(epochs, loss):
plt.plot(epochs, loss)
#fig.savefig(os.path.join('./lossGraphs', 'train.jpg'))
def training(model, train_loader, optimizer, num_epochs=5, plot=False ):
loss_vals = []
for epoch in range(num_epochs):
train_loss, total_acc, total_count = 0, 0, 0
for input, label, offsets in train_loader:
# Step1. Clearing the accumulated gradients
optimizer.zero_grad()
# Step 2. Forward pass to get output/logits
outputs = model( input, offsets ) # <---- argument offsets en plus
# Step 3. Compute the loss, gradients, and update the parameters by
# calling optimizer.step()
# - Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, label)
# - Getting gradients w.r.t. parameters
loss.backward()
# - Updating parameters
optimizer.step()
# Accumulating the loss over time
train_loss += loss.item()
total_acc += (outputs.argmax(1) == label).sum().item()
total_count += label.size(0)
# Compute accuracy on train set at each epoch
print('Epoch: {}. Loss: {}. ACC {} '.format(epoch, train_loss/len(train), total_acc/len(train)))
loss_vals.append(train_loss/len(train))
total_acc, total_count = 0, 0
train_loss = 0
if plot:
# plotting
my_plot(np.linspace(1, num_epochs, num_epochs).astype(int), loss_vals)
def evaluate( model, dev_loader ):
predictions = []
gold = []
with torch.no_grad():
for input, label, offsets in dev_loader:
probs = model(input, offsets) # <---- fct forward with offsets
# -- to deal with batches
predictions.extend( torch.argmax(probs, dim=1).cpu().numpy() )
gold.extend([int(l) for l in label])
print(classification_report(gold, predictions))
return gold, predictions
```
%% Cell type:code id: tags:
```
# Set the values of the hyperparameters
hidden_dim = 4
learning_rate = 0.001
num_epochs = 5
criterion = nn.CrossEntropyLoss()
output_dim = 2
```
%% Cell type:code id: tags:
```
# Initialize the model
model_ffnn = FeedforwardNeuralNetModel( hidden_dim, output_dim, weights_matrix)
optimizer = torch.optim.SGD(model_ffnn.parameters(), lr=learning_rate)
model_ffnn = model_ffnn.to(device)
# Train the model
training( model_ffnn, train_loader, optimizer, num_epochs=5, plot=True )
# Evaluate on dev
gold, pred = evaluate( model_ffnn, dev_loader )
```
%% Cell type:markdown id: tags:
## 5- ▶ Exercise: Tuning your model
The model comes with a variety of hyper-parameters. To find the best model, we need to test different values for these free parameters.
Be careful:
* you always optimize / fine-tune your model on the **development set**.
* Then you compare the results obtained with the different settings on the dev set to choose the best setting
* finally you report the results of the best model on the test set
* you always keep a track of your experimentation, for reproducibility purpose: report the values tested for each hyper-parameters and the values used by your best model.
In this part, you have to test different values for the following hyper-parameters:
1. Batch size: 2, 10, 100
2. Max number of epochs: max 100
3. Size of the hidden layer: 10, 64, 512
4. Activation function: Sigmoid, Relu, HardTahn
5. Learning rate: 0.0001, 0.1, 0.5, 10
6. Optimizer: SGD, Adam, RMSProp
Inspect your model to give some hypothesis on the influence of these parameters on the model by inspecting how they affect the loss during training and the performance of the model.
**Note:** (not done below) Here you are trying to make a report on the performance of your model. try to organise your code to keep track of what you're doing:
* give a different name to each model, to be able to run them again
* [Optional] save the results in a dictionnary of a file, to be able to use them later:
* think that you should be able to provide e.g. plots of your results (for example, plotting the accuracy for different value of a specific hyper-parameter), or analysis of your results (e.g. by inspecting the predictions of your model) so you need to be able to access the results.
%% Cell type:code id: tags:
```
```
%% Cell type:code id: tags:
```
```
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
### 5.7- [Optional] Additional exercise
Modify your model to test a variation on the architecture. Here you don't have to tune all your model again, just try for example when keeping the best values found previously for the hyper-parameters:
* Try with 1 additional hidden layer
This diff is collapsed.
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment