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

add slides cours 2 + TP2

parent 760a90ed
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# TP 2: Linear Algebra and Feedforward neural network
Master LiTL - 2022-2023
## Requirements
In this section, we will go through some code to learn how to manipulate matrices and tensors, and we will take a look at some PyTorch code that allows to define, train and evaluate a simple neural network.
The modules used are the the same as in the previous session, *Numpy* and *Scikit*, with the addition of *PyTorch*. They are all already available within colab.
## Part 1: Linear Algebra
In this section, we will go through some python code to deal with matrices and also tensors, the data structures used in PyTorch.
Sources:
* Linear Algebra explained in the context of deep learning: https://towardsdatascience.com/linear-algebra-explained-in-the-context-of-deep-learning-8fcb8fca1494
* PyTorch tutorial: https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#sphx-glr-beginner-blitz-tensor-tutorial-py
* PyTorch doc on tensors: https://pytorch.org/docs/stable/torch.html
%% Cell type:code id: tags:
```
# Useful imports
import numpy as np
import torch
```
%% Cell type:markdown id: tags:
## 1.1 Numpy arrays
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type
%% Cell type:markdown id: tags:
### 1.1.1 Numpy arrays
▶▶ **Look at the code below and check that you understand each line:**
* We define a numpy array (i.e. a vector) **x** from a list
* We define a numpy array of shape 3x2 (i.e. a matrix) initialized with random numbers, called **W**
* We define a scalar, **b**
* Finally, with all these elements, we can compute **h = W.x + b**
%% Cell type:code id: tags:
```
x = np.array([1,2])
print("Our input vector with 2 elements:\n", x)
print( "x shape:", x.shape)
print( "x data type", x.dtype)
# Give a list of elements
# a = np.array(1,2,3,4) # WRONG
# a = np.array([1,2,3,4]) # RIGHT
# Generate a random matrix (with a generator and a seed, for reproducible results)
rng = np.random.default_rng(seed=42)
W = rng.random((3, 2))
print("\n Our weight matrix, of shape 3x2:\n", W)
print( "W shape:", W.shape)
print( "W data type", W.dtype)
# Bias, a scalar
b = 1
# Now, try to multiply
h = W.dot(x) + b
print("\n Our h layer:\n", h)
print( "h shape:", h.shape)
print( "h data type", h.dtype)
```
%% Cell type:markdown id: tags:
### 1.1.2 Operations on arrays
▶▶ **Look at the code below and check that you understand each line:**
* How to reshape a matrix i.e. change its dimensions
* How to compute the transpose of a vector / matrix
%% Cell type:code id: tags:
```
# Useful transformations
h = h.reshape((3,1))
print("\n h reshape:\n", h)
print( "h shape:", h.shape)
h1 = np.transpose(h)
print("\n h transpose:\n", h1)
print( "h shape:", h1.shape)
h2 = h.T
print("\n h transpose:\n", h2)
print( "h shape:", h2.shape)
Wt = W.T
print("\nW:\n", W)
print("\nW.T:\n", Wt)
```
%% Cell type:markdown id: tags:
▶▶ **A last note: creating an identity matrix**
%% Cell type:code id: tags:
```
## numpy code to create identity matrix
a = np.eye(4)
print(a)
```
%% Cell type:markdown id: tags:
## 1.2 Tensors
For neural networks implementation in PyTorch, we use tensors:
* a specialized data structure that are very similar to arrays and matrices
* used to encode the inputs and outputs of a model, as well as the model’s parameters
* similar to NumPy’s ndarrays, except that tensors can run on GPUs or other specialized hardware to accelerate computing
%% Cell type:markdown id: tags:
### 1.2.1 Tensor initialization
▶▶ **Look at the code below and check that you understand each line:**
* We define a PyTorch tensor (i.e. a matrix) **x_data** from a list of list
* We define a PyTorch tensor (i.e. a matrix) **x_np** from a numpy array
* How to initialize an random tensor, an one tensor and a zero tensor
* Finally, we define a PyTorch tensor (i.e. a matrix) from another tensor:
* **x_ones**: from the identity tensor
* **x_rand**: from a tensor initialized with random values
%% Cell type:code id: tags:
```
# Tensor initialization
## from data. The data type is automatically inferred.
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
print( "x_data", x_data)
print( "data type x_data=", x_data.dtype)
```
%% Cell type:code id: tags:
```
## from a numpy array
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print("\nx_np", x_np)
print( "data type, np_array=", np_array.dtype, "x_data=", x_np.dtype)
```
%% Cell type:code id: tags:
```
## with random values / ones / zeros
shape = (2, 3,) # shape is a tuple of tensor dimensions
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
```
%% Cell type:code id: tags:
```
## from another tensor
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"\nFrom Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"From Random Tensor: \n {x_rand} \n")
```
%% Cell type:markdown id: tags:
### 1.2.2 Tensor attributes
▶▶ **A tensor has different attributes, print the values for:**
* shape of the tensor
* type of the data stored
* device on which data are stored
Look at the doc here: https://www.tensorflow.org/api_docs/python/tf/Tensor#shape
%% Cell type:code id: tags:
```
# Tensor attributes
tensor = torch.rand(3, 4)
```
%% Cell type:markdown id: tags:
### 1.2.3 Move to GPU
The code below is used to:
* check on which device the code is running, 'cuda' stands for GPU. If not GPU is found that we use CPU.
▶▶ **Check and move to GPU:**
* Run the code, it should say 'no cpu'
* Move to GPU: in Colab, allocate a GPU by going to Edit > Notebook Settings (Modifier > Paramètres du notebook)
* you'll see an indicator of connexion in the uppper right part of the screen
* Run the code from 1.2 again and the cell below (you can use the function Run / Run before or Exécution / Exécuter avant), you'll need to do all the imports again. You see the difference?
%% Cell type:code id: tags:
```
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
print(f"Device tensor is stored on: {tensor.device}")
else:
print("no gpu")
print(tensor)
```
%% Cell type:markdown id: tags:
Below, run after moving to GPU.
%% Cell type:code id: tags:
```
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
print(f"Device tensor is stored on: {tensor.device}")
else:
print("no gpu")
print(tensor)
```
%% Cell type:markdown id: tags:
### 1.2.4 Tensor operations
Doc: https://pytorch.org/docs/stable/torch.html
▶▶ **Slicing operations:**
* Below we use slicing operations to modify tensors
%% Cell type:code id: tags:
```
# Tensor operations: similar to numpy arrays
tensor = torch.ones(4, 4)
print(tensor)
```
%% Cell type:code id: tags:
```
# ---------------------------------------------------------
# TODO: What do you expect?
# ---------------------------------------------------------
## Slicing
print("\nSlicing")
tensor[:,1] = 0
print(tensor)
# ---------------------------------------------------------
# TODO: Change the first column with the value in l
# ---------------------------------------------------------
l =[1.,2.,3.,4.]
l = torch.tensor( l )
tensor[:, 0] = l
print(tensor)
```
%% Cell type:markdown id: tags:
▶▶ **Other operations:**
* Check the code below that performs:
* tensor concatenation
* tensor multiplication
%% Cell type:code id: tags:
```
## Concatenation
print("\nConcatenate tensor 3 times")
print('Original tensor:\n', tensor, '\n')
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
```
%% Cell type:code id: tags:
```
## Multiplication: element_wise
print("\nMultiply tensor by itself, elementwise")
print('Original tensor:\n', tensor, '\n')
# This computes the element-wise product
t2 = tensor.mul(tensor)
print(f"tensor.mul(tensor) \n {t2} \n")
# Alternative syntax:
t3 = tensor * tensor
print(f"tensor * tensor \n {t3}")
```
%% Cell type:code id: tags:
```
## Matrix multiplication
print("\nMultiply tensor by itself")
print('Original tensor:\n', tensor, '\n')
t4 = tensor.matmul(tensor.T)
print(f"tensor.matmul(tensor.T) \n {t4} \n")
# Alternative syntax:
t5 = tensor @ tensor.T
print(f"tensor @ tensor.T \n {t5}")
```
%% Cell type:markdown id: tags:
### 1.2.5 Tensor operations on GPU
The tensor is stored on CPU by default.
▶▶ **Initialize the tensor using *device='cuda'*: where are stored t1, ..., t5?**
%% Cell type:code id: tags:
```
# Tensor operations: similar to numpy arrays
tensor = torch.ones(4, 4, device='cuda')
print(tensor)
# ---------------------------------------------------------
# TODO: What do you expect?
# ---------------------------------------------------------
## Slicing
print("\nSlicing")
tensor[:,1] = 0
print(tensor)
# ---------------------------------------------------------
# TODO: Change the first column with the value in l
# ---------------------------------------------------------
## Concatenation
print("\nConcatenate")
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
## Multiplication: element_wise
print("\nMultiply")
# This computes the element-wise product
t2 = tensor.mul(tensor)
print(f"tensor.mul(tensor) \n {t2} \n")
# Alternative syntax:
t3 = tensor * tensor
print(f"tensor * tensor \n {t3}")
## Matrix multiplication
t4 = tensor.matmul(tensor.T)
print(f"tensor.matmul(tensor.T) \n {t4} \n")
# Alternative syntax:
t5 = tensor @ tensor.T
print(f"tensor @ tensor.T \n {t5}")
```
%% Cell type:markdown id: tags:
### 1.2.5 Final exercise: compute *h*
▶▶ **Compute the tensor h, using the same data for x and W as at the beginning of this TP.**
* Define x as a tensor, print x, its shape and dtype
* Define W as a tensor, print W, its shape and dtype
* bias is style a scalar, of type float
* Finally compute h, print h and its dtype
```
x = np.array([1,2])
rng = np.random.default_rng(seed=42)
W = rng.random((3, 2))
```
Important note: when multiplying matrices, we need to have the same data type, e.g. not **x** with *int* and **W** with *float*.
So you have to say that the vector **x** has the data type *float*. Two ways:
* from the initialization: **x = torch.tensor([1,2], dtype=float)**
* from any tensor: **x = x.to( torch.float64)** (here using only **float** would give *float32*, not what we want)
%% Cell type:code id: tags:
```
# --------------------------------------------------------
# TODO: Write the code to compute h = W.x+b
# --------------------------------------------------------
# Define x
# ...
# Define W: generate a random matrix (with e generator, for reproducible results)
# ...
# Bias, a scalar
# ...
# Now, try to multiply
# ...
```
%% Cell type:markdown id: tags:
### Last minor note
%% Cell type:code id: tags:
```
## Operations that have a _ suffix are in-place. For example: x.copy_(y), x.t_(), will change x.
print(tensor, "\n")
tensor.add_(5)
print(tensor)
```
%% Cell type:markdown id: tags:
# Part 2: Feedforward Neural Network
In this practical session, we will explore a simple neural network architecture for NLP applications ; specifically, we will train a feedforward neural network for sentiment analysis, using the same dataset of reviews as in the previous session. We will also keep the bag of words representation.
Sources:
* This TP is inspired by a TP by Tim van de Cruys
* https://www.deeplearningwizard.com/deep_learning/practical_pytorch/pytorch_feedforward_neuralnetwork/
* https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html
* https://medium.com/swlh/sentiment-classification-using-feed-forward-neural-network-in-pytorch-655811a0913f
* https://www.deeplearningwizard.com/deep_learning/practical_pytorch/pytorch_feedforward_neuralnetwork/
%% Cell type:code id: tags:
```
# Useful imports
import pandas as pd
import numpy as np
import re
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
import torch
from torch.utils.data import TensorDataset, DataLoader
import torch.nn as nn
```
%% Cell type:code id: tags:
```
# Path to data
train_path = "allocine_train.tsv"
dev_path = "allocine_dev.tsv"
```
%% Cell type:markdown id: tags:
## 2.1 Read and load the data
Here we will keep the bag of word representation, as in the previous session.
You can find different ways of dealing with the input data in PyTorch. 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:
#### 2.1.1 Build BoW vectors (code given)
The code below allows to use scikit methods you already know to generate the bag of word representation.
%% Cell type:code id: tags:
```
# This will be the size of the vectors reprensenting the input
MAX_FEATURES = 5000
def vectorize_data( data_path, vectorizer=None ):
data_df = pd.read_csv( data_path, header=0,
delimiter="\t", quoting=3)
# If an existing vectorizer is not given, initialize the "CountVectorizer"
# object, which is scikit-learn's bag of words tool.
if not vectorizer:
vectorizer = CountVectorizer(
analyzer = "word",
max_features = MAX_FEATURES
)
vectorizer.fit(data_df["review"])
# Then transform the data
x_data = vectorizer.transform(data_df["review"])
# Vectorize also the labels
y_data = np.asarray(data_df["sentiment"])
return x_data, y_data, vectorizer
x_train, y_train, vectorizer = vectorize_data( train_path )
x_dev, y_dev, _ = vectorize_data( dev_path, vectorizer )
```
%% Cell type:markdown id: tags:
Count_Vectorizer returns sparse arrays (for computational reasons) but PyTorch will expect dense input:
%% Cell type:code id: tags:
```
# from sparse to dense
x_train = x_train.toarray()
x_dev = x_dev.toarray()
print("Train:", x_train.shape)
print("Dev:", x_dev.shape)
```
%% Cell type:markdown id: tags:
#### 2.1.2 Transform to tensors
▶▶ **Create a dataset object within the PyTorch library:**
The easiest way to load datasets with PyTorch is to use the DataLoader class. Here we're going to give our numpy array to this class, and first, we need to transform our data to tensors. Follow the following steps:
%% Cell type:code id: tags:
```
# Useful imports
import torch
from torch.utils.data import TensorDataset, DataLoader
```
%% Cell type:markdown id: tags:
* 1- **torch.from_numpy( A_NUMPY_ARRAY )**: transform your array into a tensor
* Note: you need to transform tensor type to float (for x), with **MY_TENSOR.to(torch.float)** (or cryptic error saying it was expecting long...).
* Print the shape of the tensor for your training data.
https://pytorch.org/docs/stable/generated/torch.from_numpy.html#torch-from-numpy
%% Cell type:code id: tags:
```
# create Tensor dataset, i.e. torch.from_numpy( A_NUMPY_ARRAY ).
# for x
# ...
# for y
# ...
# Print x shape
# ...
```
%% Cell type:markdown id: tags:
* 2- **torch.utils.data.TensorDataset(INPUT_TENSOR, TARGET_TENSOR)**: Dataset wrapping tensors.
* Take tensors as inputs
https://pytorch.org/docs/stable/data.html#torch.utils.data.TensorDataset
%% Cell type:code id: tags:
```
# TensorDataset(INPUT_TENSOR, TARGET_TENSOR)
# ...
```
%% Cell type:markdown id: tags:
* 3- **torch.utils.data.DataLoader**: many arguments in the constructor:
* In particular, *dataset* of the type TensorDataset can be used
* We'd rather shuffling our data in general, can be done here by changing the value of one argument
* Note also the possibility to change the batch_size, we'll talk about it later
https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader
```
DataLoader(
dataset,
batch_size=1,
shuffle=False,
num_workers=0,
collate_fn=None,
pin_memory=False,
)
```
%% Cell type:code id: tags:
```
# DataLoader( dataset, ...):
## - make sure to SHUFFLE your data
## - use batch_size = 1 (i.e. no batch)
# ...
```
%% Cell type:markdown id: tags:
## 2.2 Neural Network
Now we can build our learning model.
For this TP, we're going to walk through the code of a **simple feedforward neural network, with one hidden layer**.
This network takes as input bag of words vectors, exactly as our 'classic' models: each review is represented by a vector of the size the number of tokens in the vocabulary with '1' when a word is present and '0' for the other words.
%% Cell type:markdown id: tags:
### 2.2.1 Questions
▶▶ **What is the input dimension?**
▶▶ **What is the output dimension?**
%% Cell type:markdown id: tags:
### 2.2.2 Write the skeleton of the class
▶▶ We're going to **define our own neural network type**, by defining a new class:
* The class is called **FeedforwardNeuralNetModel**
* it inherits from the class **nn.Module**
* the constructor takes the following arguments:
* size of the input (i.e. **input_dim**)
* size of the hidden layer (i.e. **hidden_dim**)
* size of the output layer (i.e. **output_dim**)
* in the constructor, we will call the constructor of the parent class
%% Cell type:code id: tags:
```
# Start to define the class corresponding to our type of neural network
```
%% Cell type:markdown id: tags:
### 2.2.3 Write the constructor
▶▶ To continue the definition of our class, we need to explain how are built each layer of our network.
More precisely, we're going to define a few fields:
* a function corresponding to the action of our hidden layer:
* what kind of function is it ?
* you need to indicate the size of the input and output for this function, what are they?
* a non linear function, that will be used on the ouput of our hidden layer
* a final output function:
* what kind of function is it ?
* you need to indicate the size of the input and output for this function, what are they?
All the functions that can be used in Pytorch are defined here: https://pytorch.org/docs/stable/nn.functional.html
::::::::::::::::::::::::::::::::::::::::
--> https://pytorch.org/docs/stable/nn.html
--> https://pytorch.org/docs/stable/generated/torch.nn.Linear.html
:::::::::::::::::::::::::::::::::::::::::
Do you see things that you know?
Hint: here you define fields of your class, these fields corresponding to specific kind of functions.
E.g. you're going to initialize a field such as **self.fc1=SPECIFIC_TYPE_OF_FCT(expected arguments)**.
%% Cell type:code id: tags:
```
# Continue the definition of the class by defining three functions in your constructor
```
%% Cell type:markdown id: tags:
### 2.2.4 Write the **forward** method
The main function we have to write when defining a neural network is called the **forward** function.
This function computes the outputs of the network (the logit), it is thus used to train the network.
It details how we apply the functions defined in the constructor.
Let's define this function, with the following signature, where x is the input to the network:
```
def forward(self, x):
```
▶▶ Follow the steps:
* 1- Apply the first linear functiond defined in the constructor to **x**, i.e. go through the hidden layer.
* 2- Apply the non linear function to the output of step 1, i.e. use the activation function.
* 3- Apply the second linear function defined in the constructor to the output of step 2, i.e. go through the output layer.
* 4- Return the output of step 3.
You're done!
%% Cell type:code id: tags:
```
# Copy paste the rest of the definition of the class below
# ...
# Define the forward function, used to make all the calculations
# through the network
def forward(self, x):
''' y = g(x.W1+b).W2 '''
# ...
```
%% Cell type:markdown id: tags:
## 2.3 Training the network
Now we can use our beautiful class to define and then train our own neural network.
%% Cell type:markdown id: tags:
### 2.3.1 Hyper-parameters
We need to set up the values for the hyper-parameters, and define the form of the loss and the optimization methods.
▶▶ **Check that you understand what are each of the variables below**
* one that you probably don't know is the learning rate, we'll explain it in the next course. Broadly speaking, it corresponds to the amount of update used during training.
%% Cell type:code id: tags:
```
# Many choices here!
VOCAB_SIZE = MAX_FEATURES
input_dim = VOCAB_SIZE
hidden_dim = 4
output_dim = 2
num_epochs = 5
learning_rate = 0.1
```
%% Cell type:markdown id: tags:
### 2.3.2 Loss function
Another thing that has to be decided is the kind of loss function we want to use.
Here we use a common one, called CrossEntropy.
We will come back in more details on this loss.
One important note is that this function in PyTorch includes the SoftMax function that should be applied after the output layer to get labels.
%% Cell type:code id: tags:
```
criterion = nn.CrossEntropyLoss()
```
%% Cell type:markdown id: tags:
### 2.3.3 Initialization of the model
Now you can instantiate your class: define a model that is of the type FeedforwardNeuralNetModel using the values defined before as hyper-parameters.
%% Cell type:code id: tags:
```
# Initialization of the model
# ...
```
%% Cell type:markdown id: tags:
### 2.3.4 Optimizer
At last, we need to indicate the method we want to use to optimize our network.
Here, we use a common one called Stochastic Gradient Descent.
We will also go back on that later on.
Note that its arguments are:
* the parameters of our models (the Ws)
* the learning rate
Based on these information, it can make the necessary updates.
%% Cell type:code id: tags:
```
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
```
%% Cell type:markdown id: tags:
### 2.3.5 Training the network (code given)
A simple code to train the neural network is given below.
▶▶ **Run the code and look at the loss after each training step.**
%% Cell type:code id: tags:
```
# Start training
for epoch in range(num_epochs):
train_loss, total_acc, total_count = 0, 0, 0
# for each instance + its associated label
for input, label in train_loader:
# Clearing the accumulated gradients
# torch *accumulates* gradients. Before passing in a
# new instance, you need to zero out the gradients from the old
# instance
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# ==> Forward pass to get output/logits
# = apply all our functions: y = g(x.W1+b).W2
outputs = model( input )
# ==> Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, label)
# Getting gradients w.r.t. parameters
# Here is the way to find how to modify the parameters in
# order to lower the loss
loss.backward()
# ==> Updating parameters: you don t need to provide the loss here,
# when computing the loss, the information is saved in the parameters
# (more precisely, doing backward computes the gradients for all tensors,
# and these gradients are saved by each tensor)
optimizer.step()
# -- a useful print
# 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/x_train.shape[0],
total_acc/x_train.shape[0]))
total_acc, total_count = 0, 0
train_loss = 0
```
%% Cell type:markdown id: tags:
### 2.3.6 Evaluate the model (code given)
%% Cell type:code id: tags:
```
# Useful imports
from sklearn.metrics import classification_report
```
%% Cell type:code id: tags:
```
# create Tensor dataset
valid_data = TensorDataset( torch.from_numpy(x_dev).to(torch.float),
torch.from_numpy(y_dev))
valid_loader = DataLoader( valid_data )
# Disabling gradient calculation is useful for inference,
# when you are sure that you will not call Tensor.backward().
predictions, gold = [], []
with torch.no_grad():
for input, label in valid_loader:
probs = model(input)
predictions.append( torch.argmax(probs, dim=1).cpu().numpy()[0] )
gold.append(int(label))
print(classification_report(gold, predictions))
```
%% Cell type:markdown id: tags:
## 3. Move to GPU (code given)
Below we indicate the modifications needed to make all the computations on GPU instead of CPU.
%% Cell type:code id: tags:
```
## 1- Define the device to be used
# CUDA for PyTorch
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
print(device)
```
%% Cell type:code id: tags:
```
## 2- No change here
import torch
import torch.nn as nn
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(FeedforwardNeuralNetModel, self).__init__()
# Linear function ==> W1
self.fc1 = nn.Linear(input_dim, hidden_dim)
# Non-linearity ==> g
self.sigmoid = nn.Sigmoid()
# Linear function (readout) ==> W2
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
'''
y = g(x.W1+b).W2
'''
# Linear function # LINEAR ==> x.W1+b
out = self.fc1(x)
# Non-linearity # NON-LINEAR ==> h1 = g(x.W1+b)
out = self.sigmoid(out)
# Linear function (readout) # LINEAR ==> y = h1.W2
out = self.fc2(out)
return out
```
%% Cell type:code id: tags:
```
## 3- Move your model to the GPU
# Initialization of the model
model = FeedforwardNeuralNetModel(input_dim, hidden_dim, output_dim)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
## ------------ CHANGE HERE -----------------
model = model.to(device)
```
%% Cell type:code id: tags:
```
## 4- Move your data to GPU
# Start training
for epoch in range(num_epochs):
train_loss, total_acc, total_count = 0, 0, 0
for input, label in train_loader:
## ------------ CHANGE HERE -----------------
input = input.to(device)
label = label.to(device)
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# Forward pass to get output/logits
outputs = model( input )
# 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/x_train.shape[0],
total_acc/x_train.shape[0]))
total_acc, total_count = 0, 0
train_loss = 0
```
%% Cell type:code id: tags:
```
# -- 5- Again, move your data to GPU
predictions = []
gold = []
with torch.no_grad():
for input, label in valid_loader:
## ------------ CHANGE HERE -----------------
input = input.to(device)
probs = model(input)
#Here, we need CPU: else, it will generate the following error
# can't convert cuda:0 device type tensor to numpy.
# Use Tensor.cpu() to copy the tensor to host memory first.
# (if we need a numpy array)
predictions.append( torch.argmax(probs, dim=1).cpu().numpy()[0] )
#print( probs )
#print( torch.argmax(probs, dim=1) ) # Return the index of the max value
#print( torch.argmax(probs, dim=1).cpu().numpy()[0] )
gold.append(int(label))
print(classification_report(gold, predictions))
```
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment