##%matplotlib notebook
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np5 Deep Learning related concepts
5.1 The output layer
Different types of output layers:
| Problem type | Last-layer activation | Loss function | Example |
|---|---|---|---|
| Binary classification | sigmoid | binary cross entropy | Dog vs cat, Sentiment analysis(pos/neg) |
| Multi-class, single-label classification | softmax | cross entropy | MNIST has 10 classes single label (one prediction is one digit) |
| Multi-class, multi-label classification | sigmoid | binary cross entropy | News tags classification, one blog can have multiple tags |
| Regression to arbitrary values | None | MSE | Predict house price(an integer/float point) |
| Regression to values between 0 and 1 | sigmoid | MSE or binary crossentropy | Engine health assessment where 0 is broken, 1 is new |
5.1.1 Sigmoïde
\[\text{Sigmoid}(x) = \frac{1}{1 + \exp(-x)}\]
x = np.arange(-10,10,0.01,dtype='f')
plt.plot(x,torch.sigmoid(torch.from_numpy(x)).numpy())
plt.grid()
a.k.a. inverse logit function (in the logistic regression)
5.1.2 Softmax
\[\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}\]
input = torch.randn(2, 3)
inputtensor([[ 0.3323, -0.9551, 1.0393],
[ 0.3995, 1.5046, -1.3479]])
out1 = nn.Softmax(dim=0)(input)
print(out1)
print(out1.sum(0))tensor([[0.4832, 0.0787, 0.9158],
[0.5168, 0.9213, 0.0842]])
tensor([1.0000, 1.0000, 1.0000])
out2 = nn.Softmax(dim=1)(input)
print(out2)
print(out2.sum(1))tensor([[0.3027, 0.0835, 0.6138],
[0.2384, 0.7200, 0.0415]])
tensor([1., 1.])
5.1.3 Binary Cross Entropy
torch.nn.BCELoss(weight=None, size_average=None, reduce=None, reduction='mean')
Creates a criterion that measures the Binary Cross Entropy between the target and the output:
The loss can be described as:
\[\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad\]
\[l_n = - w_n \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right],\]
where \(N\) is the batch size. If reduce is True, then
\[\ell(x, y) = \begin{cases} \text{mean}(L), & \text{if}\; \texttt{size\_average} = \text{True},\\ \text{sum}(L), & \text{if}\; \texttt{size\_average} = \text{False}. \end{cases}\]
This is used for measuring the error of a reconstruction in for example an auto-encoder. Note that the targets y should be numbers between 0 and 1.
m = nn.Sigmoid()
loss = nn.BCELoss()
input = torch.randn(3, requires_grad=True)
inputtensor([-0.4309, -1.5875, 1.2879], requires_grad=True)
target = torch.empty(3).random_(2)
targettensor([0., 1., 1.])
output = loss(m(input), target)
outputtensor(0.8393, grad_fn=<BinaryCrossEntropyBackward0>)
output.backward()
-input.gradtensor([-0.1313, 0.2768, 0.0721])
5.1.4 Cross Entropy
CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
his criterion combines nn.LogSoftmax and nn.NLLLoss in one single class.
It is useful when training a classification problem with C classes. If provided, the optional argument weight should be a 1D Tensor assigning weight to each of the classes. This is particularly useful when you have an unbalanced training set.
The input is expected to contain scores for each class.
input has to be a Tensor of size either \((minibatch, C)\) or \((minibatch, C, d_1, d_2, ..., d_K)\) with \(K \geq 2\) for the K-dimensional case (described later).
This criterion expects a class index (0 to C-1) as the target for each value of a 1D tensor of size minibatch
The loss can be described as:
\[ \text{loss}(x, class) = -\log\left(\frac{\exp(x[class])}{\sum_j \exp(x[j])}\right) = -x[class] + \log\left(\sum_j \exp(x[j])\right) \]
or in the case of the weight argument being specified:
\[ \text{loss}(x, class) = weight[class] \left(-x[class] + \log\left(\sum_j \exp(x[j])\right)\right) \]
The losses are averaged across observations for each minibatch.
Can also be used for higher dimension inputs, such as 2D images, by providing an input of size \((minibatch, C, d_1, d_2, ..., d_K)\) with \(K \geq 2\), where \(K\) is the number of dimensions, and a target of appropriate shape (see below).
5.1.5 Shape
- Input: \((N, C)\) where
C = number of classes, or \((N, C, d_1, d_2, ..., d_K)\) with \(K \geq 2\) in the case ofK-dimensional loss. - Target: \((N)\) where each value is \(0 \leq \text{targets}[i] \leq C-1\), or \((N, d_1, d_2, ..., d_K)\) with \(K \geq 2\) in the case of K-dimensional loss.
- Output: scalar. If reduce is
False, then the same size as the target: \((N)\), or \((N, d_1, d_2, ..., d_K)\) with \(K \geq 2\) in the case of K-dimensional loss.
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
inputtensor([[ 0.8217, -0.9423, 2.5946, -0.0575, -0.6044],
[-0.7121, 1.5265, -0.5370, 1.2039, 1.2252],
[ 1.2411, -0.1083, -0.7285, -0.8246, -0.9153]], requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
targettensor([2, 0, 4])
output = loss(input, target)
print(output)
output.backward()
print(-input.grad)tensor(2.0510, grad_fn=<NllLossBackward0>)
tensor([[-0.0432, -0.0074, 0.0789, -0.0179, -0.0104],
[ 0.3202, -0.1236, -0.0157, -0.0895, -0.0914],
[-0.2031, -0.0527, -0.0283, -0.0257, 0.3098]])
5.2 Data formatting and extraction
https://scikit-learn.org/stable/modules/feature_extraction.html
5.2.1 Create numerical features from categories
measurements = [
{'city': 'Dubai', 'temperature': 33.},
{'city': 'London', 'temperature': 12.},
{'city': 'San Francisco', 'temperature': 18.},
]
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()
vec.fit_transform(measurements).toarray()array([[ 1., 0., 0., 33.],
[ 0., 1., 0., 12.],
[ 0., 0., 1., 18.]])
vec.get_feature_names_out()array(['city=Dubai', 'city=London', 'city=San Francisco', 'temperature'],
dtype=object)
5.2.2 Text feature extraction
Bag of words
Bag-of-words representation counts occurrences of each word in each sample.
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',
]
X = vectorizer.fit_transform(corpus)
X<4x9 sparse matrix of type '<class 'numpy.int64'>'
with 19 stored elements in Compressed Sparse Row format>
vectorizer.get_feature_names_out()array(['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third',
'this'], dtype=object)
X.todense()matrix([[0, 1, 1, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 2, 1, 0, 1],
[1, 0, 0, 0, 1, 0, 1, 1, 0],
[0, 1, 1, 1, 0, 0, 1, 0, 1]])
Tf–idf term weighting
from sklearn.feature_extraction.text import TfidfTransformer
transformer = TfidfTransformer(smooth_idf=False)
tfidf = transformer.fit_transform(X)
tfidf<4x9 sparse matrix of type '<class 'numpy.float64'>'
with 19 stored elements in Compressed Sparse Row format>
tfidf.toarray()array([[0. , 0.43306685, 0.56943086, 0.43306685, 0. ,
0. , 0.33631504, 0. , 0.43306685],
[0. , 0.24014568, 0. , 0.24014568, 0. ,
0.89006176, 0.18649454, 0. , 0.24014568],
[0.56115953, 0. , 0. , 0. , 0.56115953,
0. , 0.23515939, 0.56115953, 0. ],
[0. , 0.43306685, 0.56943086, 0.43306685, 0. ,
0. , 0.33631504, 0. , 0.43306685]])
5.2.3 And more
See scikit-learn documentation regarding hashing, large text file loading, image feature extraction, etc.