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

add tp2, rm tp2 from master iafa

parent 2cc644b3
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# TP 2 : 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 session is divided in 3 parts, note that the last one is an homework, that required that part 2 is done:
## Part 1- Embeddings from scratch
Build a neural network that takes as input randomly initialized embedding vectors for each word. A review is represented by a vector that is the average of the word vectors.
## Part 2- Pre-trained word embeddings
Define a neural network that takes as input pre-trained word embeddings (here FastText embeddings). A review is represented the same way.
## Part 3: Tuning (**DM: to return on Moodle before 04/11/22**)
Tune the model build on pre-trained word embeddings (part 2) by testing several values for the different hyper-parameters, and by testing two additional architectures (i.e. one additionnal hidden layer, and an LSTM 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:
## Part 0: Read and load the data (code given)
First, we need to understand how to use text data. Here we will start with the bag of word representation.
You can find different ways of dealing with the input data. 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
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:
## 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:
```
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
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)
# 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:
### 0.1 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
%% Cell type:code id: tags:
```
class Dataset(torch.utils.data.Dataset):
def __init__(self, tsv_file, vocab=None ):
self.tsv_file = tsv_file
self.data, self.label_list = self.load_data( )
# splits the string sentence by space.
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))
self.label_pipeline = lambda x: int(x) #simple mapping to self
def load_data( self ):
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):
self.vocab = build_vocab_from_iterator(self.yield_tokens(), specials=["<unk>"])
self.vocab.set_default_index(self.vocab["<unk>"])
def yield_tokens(self):
for text in self.data:
yield self.tokenizer(text)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
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:
### 0.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 varibale-size input sequences, we need to specify how to build the batches. This is done by redefning the function *collate_fn* used by *DataLoader*.
```
dataloader = DataLoader(train_iter, batch_size=8, shuffle=False, collate_fn=collate_batch)
```
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:
```
def collate_batch(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)
offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
text_list = torch.cat(text_list)
return text_list.to(device), label.to(device), offsets.to(device)
```
%% Cell type:markdown id: tags:
### 0.3 Exercise: Load the data
* Use the code above and *DataLoader* to load the training and test data with a batch size of 2.
* Print some instances and their associated labels.
%% Cell type:code id: tags:
```
# Load training and dev sets
```
%% Cell type:markdown id: tags:
### 0.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'
* Retrive 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:code id: tags:
```
train.vocab(['Avant', 'cette', 'série', ','])
```
%% Cell type:code id: tags:
```
# Retrieve the indices of a specific word, e.g. 'mauvais'
# Retrive a word from its index, e.g. 368
# Convert a sentence to a list of indices:
# 'Avant cette série, je ne connaissais que Urgence'
# 'Avant cette gibberish, je ne connaissais que Urgence'
```
%% Cell type:markdown id: tags:
------------------------------------------
## Part 1- Embeddings from scratch
We are now going to define a neural network that takes as input randomly initialized word embedding (also called Continuous Bag of words), i.e.:
* **Each word is associated to a randomly initialized real-valued and low-dimensional vector** (e.g. 50 dimensions). Crucially, the neural network will also learn 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. 50, that represents the ‘average’, combined meaning of all the words in the document taken together.
%% Cell type:markdown id: tags:
### 1.1 Exercise: Define the model
▶▶ **Bag of embeddings: Define the embedding layer in the __init__() function below.**
In order to use the input embeddings, we need an embedding layer that transforms our input words to vectors of size 'embed_dim' and performs an operation on these vectors to build a representation for each document (default=mean). More specifically, we'll use the *nn.EmbeddingBag* layer: https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html
* mode (string, optional) – "sum", "mean" or "max". Default=mean.
▶▶ **Now write the rest of the code to define the neural network:**
In the __init__(...) function, you need to:
- define a linear function that maps the input to the hidden dimensions (e.g. self.fc1)
- define an activation function, using the non-linear function sigmoid (e.g. self.sigmoid)
- define a second linear function, that takes the output of the hidden layer and maps to the output dimensions (e.g. self.fc2)
In the forward(self, x) function, you need to:
- pass the input *x* through the first linear function
- pass the output of this linear application through the activation function
- pass the final output through the second linear function and return its output
%% Cell type:code id: tags:
```
class FeedforwardNeuralNetModel2(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, output_dim):
super(FeedforwardNeuralNetModel2, self).__init__()
# Embedding layer
# Linear function ==> W1
# Non-linearity ==> g
# Linear function (readout) ==> W2
def forward(self, text, offsets):
# Embed the input
# Linear function # LINEAR ==> x.W1+b
# Non-linearity # NON-LINEAR ==> h1 = g(x.W1+b)
# Linear function (readout) # LINEAR ==> y = h1.W2
#return out
```
%% Cell type:markdown id: tags:
**Note:** The code of the *forward* function has a 2nd argument: the 'offsets' are used to retrieve the individual documents (each document is concatenated to the others in a batch, the offsets are used to retrieve the separate documents). It has to be used also for embedding the input.
%% Cell type:markdown id: tags:
### 1.2 Exercise: Train and evaluation functions
* Complete the training function below. 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.
* compute the loss and accuracy at the end of each training step (i.e. for each sample)
* Print the loss after each epoch during training
* Print the accuracy after each epoch during training
* Complete the evaluation function below. It should print the final scores (e.g. a classification report)
Note that to we need to take into account the offsets in the training and evaluation procedures.
%% Cell type:code id: tags:
```
def training(model, train_loader, optimizer, num_epochs=5 ):
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
# Step 2. Forward pass to get output/logits
# Step 3. Compute the loss, gradients, and update the parameters by
# calling optimizer.step()
# - Calculate Loss: softmax --> cross entropy loss
# - Getting gradients w.r.t. parameters
# - Updating parameters
# Accumulating the loss over time
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)))
total_acc, total_count = 0, 0
train_loss = 0
def evaluate( model, dev_loader ):
predictions = []
gold = []
with torch.no_grad():
for input, label, offsets in dev_loader:
# ...
return gold, predictions
```
%% Cell type:markdown id: tags:
### 1.3 Hyper-parameters
* Below we define the values for the hyper-parameters:
* embedding dimension = 300
* hidden dimension = 4
* learning rate = 0.1
* number of epochs = 5
* using the Cross Entropy loss function
* Additionally, we also have: batch size = 2
* What is the input dimension?
* What is the output dimension?
%% Cell type:code id: tags:
```
# Set the values of the hyperparameters
emb_dim = 300
hidden_dim = 4
learning_rate = 0.1
num_epochs = 5
criterion = nn.CrossEntropyLoss()
output_dim = 2
vocab_size = len(train.vocab)
```
%% Cell type:markdown id: tags:
### 1.4 Exercise: Run experiments
* Initialize the model and move the model to GPU
* Define an optimizer, i.e. define the method we'll use to optimize / find the best parameters of our model: check the doc https://pytorch.org/docs/stable/optim.html and use the **SGD** optimizer.
* Train the model
* Evaluate the model on the dev set
%% Cell type:code id: tags:
```
# Initialize the model
# Define an optimizer
# Train the model
# Evaluate on dev
```
%% Cell type:markdown id: tags:
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.
%% Cell type:markdown id: tags:
## Part 2- Using pretrained embeddings
Using the previous continuous representations allows to reduce the number of dimensions. But these representations are initialized randomly, and 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 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.
%% 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 and the size of the embeddings.
At the end, we print the vocabulary and the size of the embeddings.
%% 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)
Now we need to 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.
Print the number of tokens from FastText found in the training set.
%% Cell type:code id: tags:
```
emb_dim = 300
matrix_len = len(train.vocab)
weights_matrix = np.zeros((matrix_len, emb_dim))
words_found = 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, ))
weights_matrix = torch.from_numpy(weights_matrix)
print( weights_matrix.size())
```
%% Cell type:markdown id: tags:
### 2.3 Embedding layer (code given)
The code below defines a function that builds the embedding layer using the pretrained embeddings.
%% Cell type:code id: tags:
```
def create_emb_layer(weights_matrix, non_trainable=False):
num_embeddings, embedding_dim = weights_matrix.size()
emb_layer = nn.Embedding(num_embeddings, embedding_dim)
emb_layer.load_state_dict({'weight': weights_matrix}) # <----
if non_trainable:
emb_layer.weight.requires_grad = False
return emb_layer, num_embeddings, embedding_dim
```
%% Cell type:markdown id: tags:
### 2.4 Exercise: Model definition
* Now modify your model to add this embedding layer.
* Train and evaluate the model.
Note that the embedding bag now takes pre initialized weights.
%% Cell type:code id: tags:
```
class FeedforwardNeuralNetModel3(nn.Module):
def __init__(self, embed_dim, hidden_dim, output_dim, weights_matrix):
super(FeedforwardNeuralNetModel3, self).__init__()
def forward(self, text, offsets):
#return out
```
%% Cell type:code id: tags:
```
# Initialize the model
# Define an optimizer
# Train the model
# Evaluate on dev
```
%% Cell type:markdown id: tags:
### 2.5 Exercize: Plots
Make plots of the loss and accuracy during training (one point per epoch).
%% Cell type:markdown id: tags:
## Additional tricks
### Adjusting the learning rate
*scheduler*: *torch.optim.lr_scheduler* provides several methods to adjust the learning rate based on the number of epochs.
* Learning rate scheduling should be applied after optimizer’s update.
* torch.optim.lr_scheduler.StepLR: Decays the learning rate of each parameter group by gamma every step_size epochs.
https://pytorch.org/docs/stable/optim.html
### Weight initialization
Weight initialization is done by default uniformly. You can also specify the initialization and choose among varied options: https://pytorch.org/docs/stable/nn.init.html. Further info there https://stackoverflow.com/questions/49433936/how-to-initialize-weights-in-pytorch or there https://discuss.pytorch.org/t/clarity-on-default-initialization-in-pytorch/84696/3
### Look at the weights learned
```
print(model.embedding.weight[vocab.lookup_indices(['mauvais'])])
```
* We can also explore the embeddings that are created by the architecture. Run the script in interactive mode, and issue the following commands at the python prompt :
```
m = model.layers[0].get_weights()[0]
tp3_utils.calcSim(’mauvais’, w2i, i2w, m)
```
The first line extract the embedding matrix from the model, and the second line computes the most similar embeddings for the word 'mauvais', using cosine similarity. Do the results make sense ? Try another word with a positive connotation.
%% Cell type:markdown id: tags:
## Part 3: Tuning your model (homework)
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 differen settings on the dev set, and finally report the results of the best model on the test set.
For this homework, you have to test different values for the following hyper-parameters:
1. Batch size
2. Max number of epochs (with best batch size)
3. Size of the hidden layer
4. Activation function
5. Optimizer
6. Learning rate
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.
Once done, evaluate two variations of the architecture of the model (here you don't need to test different hyper-parameter values, you can for example keep the best ones from the previous experiments):
7. Try with 1 additional hidden layer
8. Try with an LSTM layer
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment