"In English, words are often separated from each other by whitespace, but whitespace is neither necessary nor sufficient to define what constitutes a word. In our example, names such as *Latin America*, *Michael Wood*, and *London Review of Books* could arguably be treated as large words even though they contain spaces, while segments such as *day-to-day* need to be separated into several parts.\n",
"In English, words are often separated from each other by whitespace, but whitespace is neither necessary nor sufficient to define what constitutes a word. In our example, names such as *Latin America*, *Michael Wood*, and *London Review of Books* could arguably be treated as large words even though they contain spaces, while segments such as *day-to-day* need to be separated into several parts.\n",
"\n",
"\n",
"In real applications, we would have to tokenize the raw text ourselves, or use some library such as [spaCy](https://spacy.io) or [Stanford CoreNLP](https://stanfordnlp.github.io/CoreNLP/). The WikiText dataset, however, is pre-tokenized, so that we can extract the tokens from a given line using a simple helper function that splits on whitespace:"
"In real applications, we would have to tokenize the raw text ourselves, perhaps using some library such as [spaCy](https://spacy.io) or [Stanford CoreNLP](https://stanfordnlp.github.io/CoreNLP/). The WikiText dataset, however, is pre-tokenized, so that we can extract the tokens from a given line using a simple helper function that splits on whitespace:"
]
]
},
},
{
{
...
@@ -359,7 +359,7 @@
...
@@ -359,7 +359,7 @@
"source": [
"source": [
"**🤔 Problem 4: Visualize Heaps’ law**\n",
"**🤔 Problem 4: Visualize Heaps’ law**\n",
"\n",
"\n",
"> Produce a plot that visualizes Heaps’ law for the WikiText dataset: on the $x$-axis, plot the text length; on the $y$-axis, plot the number of unique words at any given position in the text. How many new words, approximately, appear in the second half of the text?"
"> Produce a plot that visualizes Heaps’ law for the WikiText dataset: on the $x$-axis, plot the text length; on the $y$-axis, plot the number of unique words encountered up to a given position in the text. How many new words, approximately, appear in the second half of the text?"
]
]
},
},
{
{
...
@@ -393,7 +393,7 @@
...
@@ -393,7 +393,7 @@
"name": "python",
"name": "python",
"nbconvert_exporter": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"pygments_lexer": "ipython3",
"version": "3.8.2"
"version": "3.9.0"
}
}
},
},
"nbformat": 4,
"nbformat": 4,
...
...
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# Basic text processing
# Basic text processing
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
The purpose of this notebook is to introduce you to some basic concepts and techniques for processing text data.
The purpose of this notebook is to introduce you to some basic concepts and techniques for processing text data.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Dataset
## Dataset
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
The dataset for this notebook is [WikiText](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/), which is based on text extracted from ‘Good’ and ‘Featured’ articles on English Wikipedia. More specifically, we will be using the training portion of the WikiText-2 dataset.
The dataset for this notebook is [WikiText](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/), which is based on text extracted from ‘Good’ and ‘Featured’ articles on English Wikipedia. More specifically, we will be using the training portion of the WikiText-2 dataset.
We start by opening the file and store its contents in a list:
We start by opening the file and store its contents in a list:
> Take a close look at this line and compare it with the [original](https://en.wikipedia.org/wiki/The_Feast_of_the_Goat#Critical_reception). You will notice several differences between the two texts. What are your hypotheses as to how these differences come about?
> Take a close look at this line and compare it with the [original](https://en.wikipedia.org/wiki/The_Feast_of_the_Goat#Critical_reception). You will notice several differences between the two texts. What are your hypotheses as to how these differences come about?
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Tokenization
## Tokenization
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Many tasks in natural language processing rely on first segmenting the raw text into words or word-like units. This task is called **tokenization**.
Many tasks in natural language processing rely on first segmenting the raw text into words or word-like units. This task is called **tokenization**.
In English, words are often separated from each other by whitespace, but whitespace is neither necessary nor sufficient to define what constitutes a word. In our example, names such as *Latin America*, *Michael Wood*, and *London Review of Books* could arguably be treated as large words even though they contain spaces, while segments such as *day-to-day* need to be separated into several parts.
In English, words are often separated from each other by whitespace, but whitespace is neither necessary nor sufficient to define what constitutes a word. In our example, names such as *Latin America*, *Michael Wood*, and *London Review of Books* could arguably be treated as large words even though they contain spaces, while segments such as *day-to-day* need to be separated into several parts.
In real applications, we would have to tokenize the raw text ourselves, or use some library such as [spaCy](https://spacy.io) or [Stanford CoreNLP](https://stanfordnlp.github.io/CoreNLP/). The WikiText dataset, however, is pre-tokenized, so that we can extract the tokens from a given line using a simple helper function that splits on whitespace:
In real applications, we would have to tokenize the raw text ourselves, perhaps using some library such as [spaCy](https://spacy.io) or [Stanford CoreNLP](https://stanfordnlp.github.io/CoreNLP/). The WikiText dataset, however, is pre-tokenized, so that we can extract the tokens from a given line using a simple helper function that splits on whitespace:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
deftokens(lines):
deftokens(lines):
forlineinlines:
forlineinlines:
fortokeninline.rstrip().split():
fortokeninline.rstrip().split():
yieldtoken
yieldtoken
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
With this, we can count the number of tokens in the dataset:
With this, we can count the number of tokens in the dataset:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
sum(1fortintokens(wikitext))
sum(1fortintokens(wikitext))
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Vocabulary
## Vocabulary
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
The term *word* is used ambiguously in natural language processing. It can either refer to a *word token*, a word as it occurs in the running text; or to a *word type*, a unique word. To illustrate the distinction: We are interested in *word tokens* when we want to count the length of a text, and in *word types* when we want to compile a dictionary of all words in the text material.
The term *word* is used ambiguously in natural language processing. It can either refer to a *word token*, a word as it occurs in the running text; or to a *word type*, a unique word. To illustrate the distinction: We are interested in *word tokens* when we want to count the length of a text, and in *word types* when we want to compile a dictionary of all words in the text material.
The set of unique words in a dataset or task is called the **vocabulary**.
The set of unique words in a dataset or task is called the **vocabulary**.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
vocab=set(tokens(wikitext))
vocab=set(tokens(wikitext))
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Show the size of the vocabulary:
Show the size of the vocabulary:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
len(vocab)
len(vocab)
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
**🤔 Problem 2: Missing words**
**🤔 Problem 2: Missing words**
> When you compare this number to the corresponding number on the [WikiText website](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/), you will notice a small difference. Try to find out what causes this difference, and how you can change the code so that you get the same number as on the website.
> When you compare this number to the corresponding number on the [WikiText website](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/), you will notice a small difference. Try to find out what causes this difference, and how you can change the code so that you get the same number as on the website.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
For some natural language processing tasks, tokenization is the only thing we need to do in order to compile the vocabulary. For other tasks, we may want to apply additional pre-processing, and/or include only the most frequent words into the vocabulary.
For some natural language processing tasks, tokenization is the only thing we need to do in order to compile the vocabulary. For other tasks, we may want to apply additional pre-processing, and/or include only the most frequent words into the vocabulary.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
**🤔 Problem 3: Normalization**
**🤔 Problem 3: Normalization**
> The term **text normalization** refers to all kinds of pre-processing that we apply to a text in order to bring it into a more standard, convenient form. Two standard normalization techniques are lowercasing and the filtering-out of non-alphabetical tokens. What effect do these techniques have on the size of the vocabulary?
> The term **text normalization** refers to all kinds of pre-processing that we apply to a text in order to bring it into a more standard, convenient form. Two standard normalization techniques are lowercasing and the filtering-out of non-alphabetical tokens. What effect do these techniques have on the size of the vocabulary?
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## String-to-index mapping
## String-to-index mapping
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
One common task when processing text with neural networks is to encode words and other strings into contiguous ranges of integers, so that we can map them to the components of a vector. A standard pattern for doing this looks as follows:
One common task when processing text with neural networks is to encode words and other strings into contiguous ranges of integers, so that we can map them to the components of a vector. A standard pattern for doing this looks as follows:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
w2i={}
w2i={}
fortokenintokens(wikitext):
fortokenintokens(wikitext):
iftokennotinw2i:
iftokennotinw2i:
w2i[token]=len(w2i)
w2i[token]=len(w2i)
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Assuming that we already have a representation of the vocabulary, we can also use a different pattern:
Assuming that we already have a representation of the vocabulary, we can also use a different pattern:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
w2i={w:ifori,winenumerate(sorted(vocab))}
w2i={w:ifori,winenumerate(sorted(vocab))}
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
What index did the word *language* get?
What index did the word *language* get?
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
w2i['language']
w2i['language']
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Sometimes we also need to invert the string-to-integer mapping:
Sometimes we also need to invert the string-to-integer mapping:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
i2w={i:sfors,iinw2i.items()}
i2w={i:sfors,iinw2i.items()}
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Decoding should be the inverse of encoding:
Decoding should be the inverse of encoding:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
asserti2w[w2i['language']]=='language'
asserti2w[w2i['language']]=='language'
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Power-law behaviour of language
## Power-law behaviour of language
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Language data often exhibits a power-law behaviour. We want to check whether this also applies to the WikiText data. In particular, we want to check whether the word frequencies follow the expected Zipfian pattern. We start by collecting the frequencies:
Language data often exhibits a power-law behaviour. We want to check whether this also applies to the WikiText data. In particular, we want to check whether the word frequencies follow the expected Zipfian pattern. We start by collecting the frequencies:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
fromcollectionsimportCounter
fromcollectionsimportCounter
counter=Counter(tokens(wikitext))
counter=Counter(tokens(wikitext))
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
How often does the word *language* occur in the data?
How often does the word *language* occur in the data?
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
counter['language']
counter['language']
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Prepare `matplotlib` for plotting:
Prepare `matplotlib` for plotting:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
%matplotlibinline
%matplotlibinline
importmatplotlib.pyplotasplt
importmatplotlib.pyplotasplt
%configInlineBackend.figure_format='retina'
%configInlineBackend.figure_format='retina'
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Produce the rank/frequency plot for the 30,000 most common words:
Produce the rank/frequency plot for the 30,000 most common words:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
words,counts=zip(*counter.most_common(30000))
words,counts=zip(*counter.most_common(30000))
plt.xlabel('Rank')
plt.xlabel('Rank')
plt.yscale('log')
plt.yscale('log')
plt.ylabel('Frequency')
plt.ylabel('Frequency')
plt.plot(range(len(words)),counts)
plt.plot(range(len(words)),counts)
plt.show()
plt.show()
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
**🤔 Problem 4: Visualize Heaps’ law**
**🤔 Problem 4: Visualize Heaps’ law**
> Produce a plot that visualizes Heaps’ law for the WikiText dataset: on the $x$-axis, plot the text length; on the $y$-axis, plot the number of unique words at any given position in the text. How many new words, approximately, appear in the second half of the text?
> Produce a plot that visualizes Heaps’ law for the WikiText dataset: on the $x$-axis, plot the text length; on the $y$-axis, plot the number of unique words encountered up to a given position in the text. How many new words, approximately, appear in the second half of the text?
"In this notebook you will learn how to implement logistic regression in PyTorch and apply it to the task of sentiment analysis."
"In this notebook you will learn how to implement logistic regression in PyTorch, and apply it to the task of sentiment analysis."
]
]
},
},
{
{
...
@@ -35,7 +35,7 @@
...
@@ -35,7 +35,7 @@
"source": [
"source": [
"Our dataset is derived from the [Stanford Sentiment Treebank](https://nlp.stanford.edu/sentiment/), which consists of 11,855 sentences extracted from movie reviews. Each sentence has been manually labelled with a rating between 0 (very negative) and 4 (very positive) towards the movie at hand. For this data, sentiment analysis can be framed as a multi-class classification problem. We have pre-processed the original data by tokenization, removing non-alphabetical tokens, and lowercasing.\n",
"Our dataset is derived from the [Stanford Sentiment Treebank](https://nlp.stanford.edu/sentiment/), which consists of 11,855 sentences extracted from movie reviews. Each sentence has been manually labelled with a rating between 0 (very negative) and 4 (very positive) towards the movie at hand. For this data, sentiment analysis can be framed as a multi-class classification problem. We have pre-processed the original data by tokenization, removing non-alphabetical tokens, and lowercasing.\n",
"\n",
"\n",
"The following helper function loads the rating-labelled movie reviews from a tab-separated file. It returns two lists: one containing the tokenized reviews (lists of strings), and one containing the corresponding ratings (integers in the range 0–4)."
"The following helper function loads the rating-labelled movie reviews from a tab-separated file. It returns a list of pairs where the first component of each pair is a tokenized review (represented a lists of string tokens) and the second component is the corresponding ratings (an integer in the range 0–4)."
]
]
},
},
{
{
...
@@ -46,14 +46,30 @@
...
@@ -46,14 +46,30 @@
},
},
"outputs": [],
"outputs": [],
"source": [
"source": [
"def load_data(filename):\n",
"def load_data(filename, max_length=20):\n",
" reviews, ratings = [], []\n",
" items = []\n",
" with open(filename, 'rt', encoding='utf-8') as fp:\n",
" with open(filename, 'rt', encoding='utf-8') as fp:\n",
"By always predicting the majority class in the training data (rating 3), we can get a validation accuracy of slightly above 25%."
"By always predicting the majority class in the training data (rating 3), we can get an accuracy on the development data of slightly above 25%."
]
]
},
},
{
{
...
@@ -297,7 +324,7 @@
...
@@ -297,7 +324,7 @@
"id": "uX1ArQIMYD2S"
"id": "uX1ArQIMYD2S"
},
},
"source": [
"source": [
"We are now ready to set up a logistic regression model and train it using the cross-entropy loss function. Recall that a logistic regression model consists of a linear layer followed by the softmax function. In PyTorch, linear layers are implemented by the class [`nn.Linear`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html), and cross-entropy loss is implemented by the function [`cross_entropy()`](https://pytorch.org/docs/stable/nn.functional.html#cross-entropy). The softmax function will be computed inside the loss function; see the code below."
"We are now ready to set up a logistic regression model and train it using the categorical cross-entropy loss function. Recall that a logistic regression model consists of a linear layer followed by the softmax function. In PyTorch, linear layers are implemented by the class [`nn.Linear`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html), and cross-entropy loss is implemented by the function [`cross_entropy()`](https://pytorch.org/docs/stable/nn.functional.html#cross-entropy). The softmax function will be computed inside the loss function; see the note below."
]
]
},
},
{
{
...
@@ -354,18 +381,19 @@
...
@@ -354,18 +381,19 @@
},
},
"outputs": [],
"outputs": [],
"source": [
"source": [
"def train(vocab, x, y, n_epochs=40, batch_size=1068, lr=1e-4):\n",
In this notebook you will learn how to implement logistic regression in PyTorch and apply it to the task of sentiment analysis.
In this notebook you will learn how to implement logistic regression in PyTorch, and apply it to the task of sentiment analysis.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Loading the data
## Loading the data
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Our dataset is derived from the [Stanford Sentiment Treebank](https://nlp.stanford.edu/sentiment/), which consists of 11,855 sentences extracted from movie reviews. Each sentence has been manually labelled with a rating between 0 (very negative) and 4 (very positive) towards the movie at hand. For this data, sentiment analysis can be framed as a multi-class classification problem. We have pre-processed the original data by tokenization, removing non-alphabetical tokens, and lowercasing.
Our dataset is derived from the [Stanford Sentiment Treebank](https://nlp.stanford.edu/sentiment/), which consists of 11,855 sentences extracted from movie reviews. Each sentence has been manually labelled with a rating between 0 (very negative) and 4 (very positive) towards the movie at hand. For this data, sentiment analysis can be framed as a multi-class classification problem. We have pre-processed the original data by tokenization, removing non-alphabetical tokens, and lowercasing.
The following helper function loads the rating-labelled movie reviews from a tab-separated file. It returns two lists: one containing the tokenized reviews (lists of strings), and one containing the corresponding ratings (integers in the range 0–4).
The following helper function loads the rating-labelled movie reviews from a tab-separated file. It returns a list of pairs where the first component of each pair is a tokenized review (represented a lists of string tokens) and the second component is the corresponding ratings (an integer in the range 0–4).
The next cell prints the number of examples in the training data:
%% Cell type:code id: tags:
len(train_reviews),len(dev_reviews)
``` python
print(len(train_data))
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Vectorizing the data
## Vectorizing the data
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
To process the movie reviews using neural networks, we need to convert them into vectors of numerical values. A simple but common vector representation in natural language processing is the **bag-of-words**. Under this representation, we record *which* words occur in a review and *how often* they occur, but completely ignore their ordering. This is the representation that we will use in this notebook.
To process the movie reviews using neural networks, we need to convert them into vectors of numerical values. A simple but common vector representation in natural language processing is the **bag-of-words**. Under this representation, we record *which* words occur in a review and *how often* they occur, but completely ignore their ordering. This is the representation that we will use in this notebook.
We first construct a mapping from words to vector indices. The domain of this mapping will be our vocabulary.
We first construct a mapping from words to vector indices. The domain of this mapping will be our vocabulary.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defmake_vocab(reviews):
defmake_vocab(data):
vocab={}
vocab={}
forreviewinreviews:
forreview,ratingindata:
fortinreview:
fortinreview:
iftnotinvocab:
iftnotinvocab:
vocab[t]=len(vocab)
vocab[t]=len(vocab)
returnvocab
returnvocab
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Running the cell below shows the size of our vocabulary:
We create the vocabulary from the training data:
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
vocab=make_vocab(train_reviews)
vocab=make_vocab(train_data)
```
%% Cell type:markdown id: tags:
Running the cell below prints the size of the vocabulary:
len(vocab)
%% Cell type:code id: tags:
``` python
print(len(vocab))
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Next, we map each review to a vector that holds the counts for all the words in the vocabulary, and collect all sentence vectors into a PyTorch tensor. We do the same thing for all ratings, which results in a vector of integers.
Next, we map each review to a vector that holds the counts for all the words in the vocabulary, and collect all sentence vectors into a PyTorch tensor. We do the same thing for all ratings, which results in a vector of integers.
By always predicting the majority class in the training data (rating 3), we can get a validation accuracy of slightly above 25%.
By always predicting the majority class in the training data (rating 3), we can get an accuracy on the development data of slightly above 25%.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
accuracy(torch.full_like(dev_y,3),dev_y)
accuracy(torch.full_like(dev_y,3),dev_y)
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
## Training the model
## Training the model
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
We are now ready to set up a logistic regression model and train it using the cross-entropy loss function. Recall that a logistic regression model consists of a linear layer followed by the softmax function. In PyTorch, linear layers are implemented by the class [`nn.Linear`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html), and cross-entropy loss is implemented by the function [`cross_entropy()`](https://pytorch.org/docs/stable/nn.functional.html#cross-entropy). The softmax function will be computed inside the loss function; see the code below.
We are now ready to set up a logistic regression model and train it using the categorical cross-entropy loss function. Recall that a logistic regression model consists of a linear layer followed by the softmax function. In PyTorch, linear layers are implemented by the class [`nn.Linear`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html), and cross-entropy loss is implemented by the function [`cross_entropy()`](https://pytorch.org/docs/stable/nn.functional.html#cross-entropy). The softmax function will be computed inside the loss function; see the note below.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
importtorch.nnasnn
importtorch.nnasnn
importtorch.nn.functionalasF
importtorch.nn.functionalasF
importtorch.optimasoptim
importtorch.optimasoptim
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
We will train our model using minibatch gradient descent. The following function splits the data into randomly sampled minibatches of the specified size.
We will train our model using minibatch gradient descent. The following function splits the data into randomly sampled minibatches of the specified size.
# Backward pass; propagates the loss and computes the gradients
# Backward pass; propagates the loss and computes the gradients
loss.backward()
loss.backward()
# Update the parameters of the model
# Update the parameters of the model
optimizer.step()
optimizer.step()
returnmodel
returnmodel
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
**⚠️ The softmax is implicit!**
**⚠️ The softmax is implicit!**
One thing that you will note when you go through the code of the training loop is that there is no explicit call to the softmax function. The outputs of the network are not normalized probabilities but just scores (logits). The softmax is computed inside `cross_entropy()`.
One thing that you will note when you go through the code of the training loop is that there is no explicit call to the softmax function. The outputs of the network are not normalized probabilities but just scores (logits). The softmax is computed inside `cross_entropy()`.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Here is an embellished version of the training loop that plots the per-epoch losses and the per-epoch accuracies on the validation data.
Here is an embellished version of the training loop that plots the per-epoch losses and the per-epoch accuracies on the development data.
The data set that we used in this notebook is very small, and the model is very simple. For larger datasets and/or models, you may want to use a GPU, say on a service such as [Colab](http://colab.research.google.com). Fortunately, making a model ready for GPU training is rather straightforward in PyTorch: You only need to ‘send’ the model and its input to the correct device.
The data set that we used in this notebook is very small, and the model is very simple. For larger datasets and/or models, you may want to use a GPU, say on a service such as [Colab](http://colab.research.google.com). Fortunately, making a model ready for GPU training is rather straightforward in PyTorch: You only need to ‘send’ the model and its input to the correct device.
The next code cell contains a GPU-enabled version of the (embellished) training loop. Modified lines are marked as `CHANGED`.
The next code cell contains a GPU-enabled version of the (embellished) training loop. Modified lines are marked as `CHANGED`.