0% found this document useful (0 votes)
8 views689 pages

Lecture 8-Đã G P

Lecture 7 covers image segmentation, focusing on techniques such as isolated point detection, edge detection, and thresholding methods. It discusses the fundamentals of segmentation, the importance of edge detection in image perception, and various edge detection algorithms including Sobel and Canny. Additionally, it addresses the challenges of thresholding in segmentation and introduces Otsu's method for optimal threshold selection.

Uploaded by

Trân Trân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views689 pages

Lecture 8-Đã G P

Lecture 7 covers image segmentation, focusing on techniques such as isolated point detection, edge detection, and thresholding methods. It discusses the fundamentals of segmentation, the importance of edge detection in image perception, and various edge detection algorithms including Sobel and Canny. Additionally, it addresses the challenges of thresholding in segmentation and introduces Otsu's method for optimal threshold selection.

Uploaded by

Trân Trân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 689

Lecture 7

Image Segmentation
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
❖ Analytic element detection by Hough transform
Fundamentals

❖ Segmentation attempts to partition the pixels


of an image into groups that strongly correlate
with the objects in an image
❖ It is one of the most difficult tasks in image
processing
❖ Typically, the first step in any automated
computer vision application
Fundamentals—Segmentation Examples
Fundamentals—Segmentation Examples
Fundamentals

❖ There are three basic types of grey level


discontinuities that we tend to look for in
digital images:
▪ Points
▪ Lines
▪ Edges
❖ We typically find discontinuities using masks
and correlation
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
❖ Analytic element detection by Hough transform
Isolated Point Detection
❖ The detection of isolated points embedded in areas
of constant or nearly constant intensity in an image
can be fulfilled by using Laplacian operator
Isolated Point Detection

❖ The detection of isolated points embedded in


areas of constant or nearly constant intensity in
an image can be fulfilled by using Laplacian
operator
Isolated Point Detection—An Example

There is an isolated black


point in the input image

How to detect it?


X‐ray image of turbine blade
Isolated Point Detection—An Example
Outline
❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
▪ General concepts
▪ Basic edge detection
▪ More advanced techniques
❖ Segmentation based on thresholding
❖ Analytic element detection by Hough transform
General concepts
❖ What are edges?
▪ Edges are pixels where the image function changes abruptly

❖ Why edge detection is useful?


▪ Neurological and psychophysical research suggests that
locations in the image in which the function value changes
abruptly are important for image perception.
▪ Such a process will lead to a significant reduction of image
data, however, does not undermine understanding of the
content of the image (interpretation) in many cases.
Implementation in Matlab
close all;
clear all;
im = imread('truong.bmp');
%edgeResult = edge(im,'canny');
edgeResult = edge(im,'Sobel');
imwrite(edgeResult,’result.bmp');
figure;
imshow(edgeResult,[]);
Implementation in Matlab
close all;
clear all; % Log Edge Detection
I = rgb2gray(imread(“truong.bmp")); M = edge(I, 'log');
subplot(2, 4, 1), subplot(2, 4, 5),
imshow(I); imshow(M);
title("Gray Scale Image"); title("Log");

% Sobel Edge Detection % Zerocross Edge Detection


J = edge(I, 'Sobel'); M = edge(I, 'zerocross');
subplot(2, 4, 2), subplot(2, 4, 6),
imshow(J); imshow(M);
title("Sobel"); title("Zerocross");

% Prewitt Edge detection % Canny Edge Detection


K = edge(I, 'Prewitt'); N = edge(I, 'Canny');
subplot(2, 4, 3), subplot(2, 4, 7),
imshow(K); imshow(N);
title("Prewitt");
title("Canny");

% Robert Edge Detection


L = edge(I, 'Roberts');
subplot(2, 4, 4),
imshow(L);
title("Robert");
Outline
Main causes of edges
❖ • Depth discontinuity
▪ one surface occludes another
❖ Surface orientation discontinuity
▪ the edge of a block
❖ reflectance discontinuity
▪ texture or color changes
❖ illumination discontinuity
▪ shadows
General concepts

There are 3 fundamental steps for edge detection


▪ Image smoothing for noise reduction
▪ Detection of edge points. This is a local operation
that extracts from an image all points that are
potential candidates to become edge points
▪ Edge localization. This step is to select from the
candidate edge points only the points that are
true members of the set of points comprising an
edge
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
▪ General concepts
▪ Basic edge detection
▪ More advanced techniques
❖ Segmentation based on thresholding
❖ Analytic element detection by Hough transform
Basic Edge Detection
❖ Edges can be regarded as the extrema points
of the first‐order derivative
Basic Edge Detection
Basic Edge Detection
❖ Look for points where the gradient magnitude is
a maximum along the direction perpendicular to
the edge
❖ The direction perpendicular to the edge can be
estimated using the direction of the gradient
Basic Edge Detection
❖ For discrete case, 2D gradients are usually computed
by using various kinds of gradient operators
❖ Image’s gradient can be obtained by filtering the image
with the gradient operator
Basic Edge Detection—An Example (Sobel)
Implementation in Matlab
im = imread('hustgray.bmp');
im = double(im);
figure;
subplot(2,2,1); imshow(im,[]);
title('original input');

sobelKernelY = [1 2 1;0 0 0; -1 -2 -1];


sobelKernelX = [-1 0 1;-2 0 2; -1 0 1];

derivativeX = imfilter(im, sobelKernelX,'replicate');


subplot(2,2,2); imshow(derivativeX,[]);
title('partial derivative along X direction');

derivativeY = imfilter(im, sobelKernelY,'replicate');


subplot(2,2,3); imshow(derivativeY,[]);
title('partial derivative along Y direction');

gradientMagnitude = sqrt(derivativeX.^2 + derivativeY.^2);


subplot(2,2,4); imshow(gradientMagnitude,[]);
title('gradient magnitude');
Basic Edge Detection—An Example (Sobel)
original input partial derivative along X direction

Input image f x
partial derivative along Y direction gradient magnitude

f y Gradient magnitude
Basic Edge Detection —An Example (Sobel)
❖ Derivative with smoothing
▪ Consider a single row or column of the image

Where is the edge?


Basic Edge Detection
❖ Derivative with smoothing
❖ Finite difference filters respond strongly to noise
▪ Image noise results in pixels that look very
different from their neighbors
▪ Generally, the larger the noise the stronger
the response
❖ What is to be done?
▪ Smoothing the image should help, by forcing
pixels different from their neighbors (=noise p
ixels?) to look more like neighbors
Basic Edge Detection
❖ Derivative with smoothing

To find edges, look for peaks in d(f*g)/dx


Basic Edge Detection
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
▪ General concepts
▪ Basic edge detection
▪ More advanced techniques
❖ Segmentation based on thresholding
❖ Analytic element detection by Hough transform
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
An example of LoG filter

close all;
clear all;
logFunction =
fspecial('log',51,8);
figure;
surfl(logFunction);
shading interp
colormap(gray);
figure;
imshow(logFunction,[]);
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)

❖ The Marr‐Hildreth edge detection algorithm


may be summarized as follows
1. Filter the input image with a Gaussian low‐pass
filter
2. Compute the Laplacian of the result in step 1
3. Find the zero‐crossings of the image from step 2
4.(Of course, steps 1 and 2 can be combined by
using one operator LoG)
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
How to identify the zero‐crossing points?

▪ If p is a zero‐crossing point, the signs


of at least two of its opposing neighboring
pixels must differ
▪ Usually, we also require that the
absolute value of their difference must
also exceed a pre‐defined threshold
before we can call p a zero‐crossing
pixel (see the example in the next page)
Marr‐Hildreth Edge Detector (Zero‐crossings of LoG)
Canny Edge Detection [1]
❖ Although the algorithm is more complex, the
performance of the Canny edge detector is superior
in general to the edge detectors discussed before
❖ It can be summarized as the following steps
1. Smooth the input image with a Gaussian filter
2. Compute the gradient magnitude and angle maps
3. Apply nonmaxima suppression to the gradient
magnitude map
4.Use double thresholding and connectivity analysis to
detect and link edges

[1] J. Canny, A Computational Approach To Edge Detection, IEEE Trans. Pattern


Analysis and Machine Intelligence, 8:679‐714, 1986.
Canny Edge Detection
Canny Edge Detection
Canny Edge Detection
Canny Edge Detection
Canny Edge Detection
Implementation Tips
In Matlab, edge detection can be completed by
using the built‐in function “edge”

close all;
clear all;
im = imread('hustgray.bmp');
%edgeResult = edge(im,’Sobel');
edgeResult = edge(im,’canny');
imwrite(edgeResult,'canny.bmp');
figure;
imshow(edgeResult,[]);
Canny Edge Detection
Edge detection result by using “canny”
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
▪ Foundation
▪ Basic global thresholding
▪ Otsu’s optimum global thresholding
▪ Variable thresholding
❖ Analytic element detection by Hough transform
Foundation
❖ Because of its intuitive properties, simplicity of
implementation, and computational speed, image
thresholding enjoys a central role in image segmentation
Foundation—Thresholding Example
❖ Imagine a poker playing robot that needs to visually
interpret the cards in its hand
Foundation—Thresholding Example
If you get the threshold wrong, the results can be disastrous
Foundation- the role of noise in thresholding

Without additional processing, we have little hope of finding a suitable


threshold for segmenting the third image
Foundation—the role of illumination

Without additional processing, we have little hope of finding a suitable


threshold for segmenting the third image
Foundation—the role of illumination
❖ The success of intensity thresholding is related to the
width and depth of the valley(s) separating the
histogram modes
❖ The key factors are
▪ The separation between peaks (the further apart the
peaks are, the better the chances of separating the
modes)
▪ The noise content in the image (the modes broaden
as noise increases)
▪ The uniformity of the illumination
▪ The uniformity of the reflectance properties of the
image
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
▪ Foundation
▪ Basic global thresholding
▪ Otsu’s optimum global thresholding
▪ Variable thresholding
❖ Analytic element detection by Hough transform
Basic Global Thresholding
❖ Partition the image histogram using a single global
threshold
❖ The success of this technique very strongly depends
on how well the histogram can be partitioned
Basic Global Thresholding
Basic Global Thresholding—An Example

Input image
Basic Global Thresholding—An Example
im = (imread('fingerprint.jpg'));
figure; imhist(im);

figure;
subplot(1,2,1); imshow(im,[]);
title('input image');

thresh = mean2(im);

done = false;
while ~done
g = im > thresh;
newThresh = 0.5 * (mean(im(g)) +
mean(im(~g)));
done = abs(thresh - newThresh) < 0.5;
thresh = newThresh;
end

result = im > thresh;


subplot(1,2,2); imshow(result,[]);
title('segmentation result');
Basic Global Thresholding—An Example
3500

3000

2500

2000

1500

1000

500

0 50 100 150 200 250

Using the basic global thresholding algorithm, threshold = 125.4


Basic Global Thresholding—An Example

input image segmentation result


Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
▪ Foundation
▪ Basic global thresholding
▪ Otsu’s optimum global thresholding
▪ Variable thresholding
❖ Analytic element detection by Hough transform
Otsu’s Optimum Global Thresholding
❖ Otsu’s method can choose the optimum threshold in
the sense that it maximizes the between‐class
variance
Basic Global Thresholding—An Example
Otsu’s Optimum Global Thresholding

Implementation Tips
In Matlab, “graythresh” computes Otsu’s threshold
Otsu’s Optimum Global Thresholding—An Example
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
▪ Foundation
▪ Basic global thresholding
▪ Otsu’s optimum global thresholding
▪ Variable thresholding
❖ Analytic element detection by Hough transform
Variable Thresholding

❖ Factors such as noise and nonuniform illumination


play a major role in the performance of a
thresholding algorithm
❖ In some cases (even seems very simple), a global
threshold does not work well
❖ That’s why we want to have a variable thresholding
scheme
Variable Thresholding based on Local Image Properties

❖ This basic approach uses the standard deviation and


mean of the pixels in a neighborhood of every pixel
in an image
❖ For each pixel, a distinct threshold will be computed
Variable Thresholding based on Local Image Properties

Đo sự khác nhau giữa những pixel lân cận

Đo sự khác nhau giữa 2 miền


ảnh sử dụng 1 cửa sổ trượt
Variable Thresholding—Moving Average

❖ Moving average is a special case of the local


thresholding, which is based on computing a moving
average along scan lines of an image
❖ It is especially useful in document processing

❖ The scanning is carried out line by line in a zigzag


pattern to reduce illumination bias
Variable Thresholding based on Local Image Properties

❖ Moving average at the pixel k is formed by averaging


the intensities of that pixel and its n-1 preceding
neighbors
❖ Suppose we have a 5*5 image, n = 4
Variable Thresholding based on Local Image Properties

❖ Moving average at the pixel k is formed by averaging


the intensities of that pixel and its n-1 preceding
neighbors
❖ Suppose we have a 5*5 image, n = 4
Variable Thresholding based on Local Image Properties

❖ Moving average at the pixel k is formed by averaging


the intensities of that pixel and its n-1 preceding
neighbors
❖ Suppose we have a 5*5 image, n = 4
Variable Thresholding—Moving Average

An example
▪ A handwritten text shaded by a spot intensity pattern;
this form of shading is typical of images obtained with
a photographic flash
%this is the function for implementing the moving average threshold
%algorithm. It is created by Gonzalez
function g = movingThresh(f,n,K)
%f is the iput gray-scale image; n is the number of the pixels involved for
%averaging; K is the constant for thesholding segmentation
f=single(f);
[M,N]=size(f);
%preliminairies
if (n<1)|| (rem(n,1)~=0)
error('n must be an integer >=1.')
end
if K<0 || K>1
error('K must be a fraction in the range [0, 1].')
end
%Flip every other row of f to produce the equivalent of a zig-zag scanning
%pattern. Convert image to a vector
f(2:2:end,:)=fliplr(f(2:2:end,:));
f=f';
f=f(:)';

%compute the moving average


maf=ones(1,n)/n;
ma=filter(maf,1,f);

%perform thresholding
g=f>K*ma;
%go back to the image format
g=reshape(g,N,M);
g = g';
%flip alternate row back
g(2:2:end,:)=fliplr(g(2:2:end,:));
%this is the demo for moving average threshold
close all;
clear all
im = rgb2gray(imread('text_ni.bmp'));
figure;
imshow(im,[]);
title('input image’);

%Ostu global threshold


ostuThreshold = graythresh(im);
segmentationResultByOstu = im2bw(im, ostuThreshold);
figure;
imshow(segmentationResultByOstu);
title('segmentation result by Ostu global threshold');

%moving average method


numberOfPixelsInvolvedInAveraging = 20;
KForThesholding = 0.5;
movingAveResult =
movingThresh(im,numberOfPixelsInvolvedInAveraging,KForThesholding);
figure;
imshow(movingAveResult);
title('segmentation result by moving average');
Variable Thresholding—Moving Average
Variable Thresholding—Moving Average
Variable Thresholding—Moving Average
Another example
❖ Text image corrupted by a sinusoidal intensity variation typical
of the variation that may occur when the power supply in a
document scanner is not grounded properly
Variable Thresholding—Moving Average
Variable Thresholding—Moving Average
Outline

❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
▪ Foundation
▪ Basic global thresholding
▪ Otsu’s optimum global thresholding
▪ Variable thresholding
❖ Analytic element detection by Hough transform
Analytic element detection—Hough transform
What can Hough transform do?
Find lines or curves in an input image. Such an image might
be the output of a edge detector discussed in the previous
lectures
Voting schemes

❖ Let each feature vote for all the models that are
compatible with it
❖ Hopefully the noise features will not vote
consistently for any single model
❖ Missing data doesn’t matter as long as there are
enough features remaining to agree on a good
model
Hough transform
▪ An early type of voting scheme
Ý tưởng chung của việc phát hiện đường thẳng trong thuật toán này
là tạo mapping từ không gian ảnh (A) sang một không gian mới (B)
mà mỗi đường thẳng trong không gian (A) sẽ ứng với một điểm trong
không gian (B).
Parameter space representation
A line in the image corresponds to a point in
Hough space
Analytic element detection—Hough transform
Parameter space representation
Parameter space representation
Parameter space representation
Parameter space representation
Algorithm outline
Basic illustration
A real example
Incorporating image gradients
Hough transform for finding lines in Matlab
Hough transform for finding lines in Matlab
Hough transform for circles
Hough transform – General Procedure
Hough transform—Circles detection
Hough transform—Circles detection
Hough transform: Discussion
Thanks for your attention!
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 10:
Machine learning background
(part 2)
Van-Truong Pham, PhD
School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Gradient descent (GD)
▪ Bài toán thường gặp trong machine learning: tìm các cực tiểu toàn cục
của một hàm số
▪ Việc giải trực tiếp phương trình đạo hàm bằng không có thể phức tạp
hoặc có vô số nghiệm.
▪ Hạ gradient (gradient descent) và các biến thể của nó: là hướng tiếp
cận phổ biến để giải bài toán tối ưu
Chọn một điểm xuất phát rồi tiến dần đến đích sau mỗi vòng lặp
Gradient descent (GD)
▪ Cập nhật biến cần tìm: xt+1= 𝑥𝑡 − 𝑓′(𝑥𝑡)

Lưu ý gradient của hàm số f(x) theo x ký hiệu là ∇𝑥 f(x)


𝑑𝑓(𝑥)
t+1= 𝑥𝑡 − 𝛻𝑥 𝑓(𝑥𝑡)𝛻𝑥 𝑓(𝑥)
𝑓′(𝑥)x=
𝑑𝑥
 là một số dương, gọi là tốc độ học (learning rate)

Dấu trừ thể hiện xt cần đi ngược với đạo hàm 𝑓′(𝑥𝑡)
(gradient descent)
Gradient descent (GD)
▪ Hạ gradient (GD) cho bài toán linear regression
𝑛
1
𝐿෠ 𝑤 = ෍(𝑤 𝑇 𝑥𝑖 − 𝑦𝑖 )2 = 𝑋𝑤 − 𝑌 2
2
𝑛
𝑖=1
Đạo hàm của hàm mất mát theo 𝑤 (tính loss gradient):

𝛻𝐿෠ (𝑤)=𝛻𝑤 𝑋𝑤 − 𝑌 22 = 𝛻𝑤 𝑋𝑤 − 𝑌 𝑇 𝑋𝑤 − 𝑌
= 𝛻𝑤 𝑤 𝑇 𝑋 𝑇 𝑋𝑤 − 2𝑤 𝑇 𝑋 𝑇 𝑌 + 𝑌 𝑇 𝑌
= 2𝑋 𝑇 𝑋𝑤 − 2𝑋 𝑇 𝑌

Mục tiêu: Tìm 𝑤 để tối thiểu hóa 𝐿෠ (𝑤)


• Đặt một số giá trị ước lượng ban đầu cho 𝑤
• Ở mỗi bước, tính ∇𝐿෠ (𝑤), tại giá trị w ở bước trước đó

• Cập nhật theo bước step  (learning rate):


𝑤 ← 𝑤 − ∇𝐿෠ 𝑤
 𝑤𝑛𝑒𝑤 = 𝑤 𝑜𝑙𝑑 − ∇𝐿෠ 𝑤𝑜𝑙𝑑
Gradient descent (GD)
Hạ Gradient cho bài toán Linear regression
• Hàm dự đoán
• Tham số

• Hàm mất mát

• Bài toán tối ưu

• Gradient descent:

7
Gradient descent (GD)
▪ Đạo hàm riêng theo tham số

• Đạo hàm riêng theo

8
Gradient descent (GD)
• Đạo hàm riêng theo

▪ Khởi tạo w0, w1

▪ Lặp lại cho tới khi hội tụ:

9
Gradient descent (GD)

10
Gradient descent (GD)
Gradient descent với norm1
• Khi hàm mất mát có dạng hàm sai khác tuyệt đối:

• Đạo hàm riêng theo wj

• Lặp lại cho tới khi hội tụ:

11
Gradient descent (GD)
Gradient descent với nhiều biến
• Hàm dự đoán
• Tham số

• Hàm dự đoán

• Bài toán tối ưu

• Gradient descent:

12
Gradient descent (GD)
Gradient descent: convexity
▪ Với hàm convex: gradient descent cho nghiệm toàn cục, hội tụ với mọi giá trị khởi tạo

▪ Với hàm non-convex: gradient descent cho nghiệm toàn cục hay cục bộ tùy vào giá trị
khởi tạo

13
Gradient descent (GD)
Learning rate
▪ Learning rate  (trong neural networks hay đặt là )
ảnh hưởng đến sự hội tụ tới nghiệm của GD

▪ Nếu  quá nhỏ, quá trình tối ưu hóa


cần rất nhiều vòng lặp (iterations) để hội
tụ tới nghiệm

▪ Nếu  quá lớn, quá trình tối ưu hóa


không hội tụ (bị phân kỳ)
và không đạt tới giá trị cực tiểu

14
Gradient descent (GD)
▪ Gradient descent
𝑤 ← 𝑤 − ∇𝐿෠ (𝑤)
• Khi cập nhật tham số w, ta sử dụng tất cả các điểm dữ liệu xi
(gọi là batch gradient descent)

• Có hạn chế khi cơ sở dữ liệu lớn (có rất nhiều điểm): tính đạo hàm cho tất cả
các điểm cùng lúc trong một vòng lặp dẫn đến tốn dung lượng bộ nhớ, thời
gian tính toán.

• Với online learning, batch GD thực hiện tính lại gradient của hàm mất mát với
toàn bộ dữ liệu → mất đi tính online (thời gian thực)

➢ Giải pháp: Stochastic Gradient Descent (SGD)


Stochastic Gradient Descent (SGD)
▪ Stochastic gradient descent (SGD)
• Chỉ tính đạo hàm của hàm mất mát dựa trên một (hoặc một số) điểm
dữ liệu, sau đó cập nhật tham số dựa trên đạo hàm này.
• Sau khi duyệt qua tất cả các điểm dữ liệu, thuật toán lặp lại quá trình trên.
- Mỗi lần cập nhật nghiệm là một vòng lặp (iteration)

- Mỗi lần duyệt hết toàn bộ dữ liệu gọi là một epoch

• Sau mỗi epoch, thứ tự lấy các dữ iệu cần được xáo trộn để đảm bảo
tính ngẫu nhiên (stochastic)

▪ Quy tắc cập nhật của SGD:

𝑤 ← 𝑤 − ∇𝑤෢𝐿(𝑤; 𝑥𝑖, 𝑦𝑖)


𝐿෠ (𝑤; 𝑥𝑖, 𝑦𝑖) là hàm mất mát nếu chỉ có một cặp dữ liệu thứ i
16
Mini-batch Gradient Descent
▪ Minibatch gradient descent (mini-batch GD)
• Sử dụng 1<k<N điểm dữ liệu để cập nhật ở mỗi vòng lặp.

• Xáo trộn ngẫu nhiên dữ liệu rồi chia toàn bộ dữ liệu thành các mini-batch,
mỗi mini-batch có k điểm dữ liệu.
- Ở mỗi vòng lặp, một mini-batch được lấy ra đển tính toán gradient và
cập nhật tham số
- Duyệt hết toàn bộ dữ liệu, kết thúc một epoch

• One epoch ~ (N/k) iteration. Giá trị k được gọi là kích thước batch

17
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Classification
▪ Classification: predicting a discrete-valued target
• binary classification: predicting a binary-valued target

▪ Examples of binary classification


• predict whether a patient has a disease
(covid or noncovid; benign and malignant tumor),
• given the presence or absence of various symptoms
• classify e-mails as spam or non-spam
• ….
Classification examples
▪ Example: Disease class prediction
Supervised classification problem: Predict the disease class (discrete value) of
patient given existing medical data features (tumor size).

Is the tumor benign/malign?


Supervised classification predicts benign.
Classification examples
▪ Examples of binary classification tasks:
Email: Spam (1) or not spam (0)
Online financial transaction: Fraudulent (1) or legitimate (0)

▪ From binary to multi-class classification:


Email: Spam (0), work (1), friends (2), family (3)
Medical diseases: Benign (0), malign I (1), malign II (2), malign III (3)
Classification formulation

Slide credit: X. Bresson


Model representation
Linear classifier
▪ Linear classifier:
• Classify data into labels based on a linear combination of inputs (i.e., dùng
đường thẳng để phân chia các nhóm dữ liệu)

• Common linear classifiers: Perceptron, logistic regression, SVM, LDA,


Linear classifier
▪ As a neuron:

▪ Some activation functions (g):


Perceptron-neuron
▪ Perceptron gần với neuron sinh học
Perceptron
▪ Perceptron: Mô hình toán của một neuron
▪ Đầu vào (tín hiệu từ các neurons khác): x1, x2,…xD
▪ Trọng số (các dendrities): w1, w2,…wD

▪ Hàm kích hoạt tuyến tính: a= w0 +w1x1+w2x2 +…+wDxD


chính là đầu ra của perceptron

(với bias x0=1)


Perceptron
▪ Perceptron view
Input

Weights
x1
w1

x2
w2
Output: sgn(wx + b)
x3
w3
.
.
.
wD
xD
Perceptron
▪ Phân loại
• Cho tập training data
𝑥𝑖 , 𝑦𝑖 , 𝑖 = 1, … , 𝑛 ,𝑦𝑖 ∈ {−1,1}

• Giả thuyết phân loại: 𝑓𝑤 (𝑥) = sgn(𝑤 𝑇 𝑥)


Hàm dự đoán thường có thêm hệ số điều chỉnh bias- (giúp cho mô
hình linh hoạt hơn):

𝑓𝑤 𝑥 = sgn(𝑤 𝑇 𝑥 + 𝑏)

Có thể được viết dưới dạng khác nếu đặt 𝑤 ′ = 𝑤; 𝑏 và 𝑥 ′ = [𝑥; 1]


Perceptron
• Hàm mất mát (0-1 Loss):
𝑛
1
𝐿෠ 𝑓𝑤 = ෍ 𝕀[sgn 𝑤 𝑇 𝑥𝑖 ≠ 𝑦𝑖 ]
𝑛
𝑖=1
Đếm số mẫu bị phân loại sai, và tối thiểu hóa số lượng đó
I(x) or 1(x): indicator function, takes a value of 1 if its argument is true

• Khó thực hiện tối ưu


(0-1 loss is a poor choice for optimization)
Thuật toán học Perceptron
❑Perceptron Algorithm
• Khởi tạo ngẫu nhiên cho các trọng số

• Đối với mỗi mẫu training (𝑥𝑖 , 𝑦𝑖 ):

Nếu phép dự đoán hiện tại sgn(𝑤 𝑇 𝑥𝑖 ) chưa khớp với 𝑦𝑖 ,


yi ≠ sgn(w T xi )
ta quay lại cập nhật trọng số:
𝑤 ← 𝑤 + 𝜂 𝑦𝑖 𝑥𝑖

𝜂 là tốc độ học (learning rate)


Trong thuật toán học perceptron thường chọn 𝜂=1
Perceptron Algorithm
• Hàm dự đoán đầu ra của perceptron:
𝑙𝑎𝑏𝑒𝑙 𝐱 = sgn(𝒘𝑇 𝐱)

▪ Thuật toán học perceptron (Perceptron Algorithm) chỉ có phù hợp cho bài
toán phân loại khi dữ liệu là hoàn toàn tách biệt tuyến tính

32
Perceptron vs Linear regression
Perceptron Perceptron Linear regression
(dạng thu gọn) (dạng thu gọn)

Input Output Input Output Input Output


layer layer layer layer layer layer

Hàm kích hoạt:


Perceptron: 𝑦 = sgn 𝑧
Linear regression: 𝑦 = 𝑧

33
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Classification
▪ Last time: binary classification, perceptron algorithm
• Limitations of the perceptron
✓ no guarantees if data aren't linearly separable
✓ how to generalize to multiple classes?
✓ linear model - no obvious generalization to multilayer
neural networks
Not linearly separable
▪ Design choices so far
• Task: regression, binary classification, multiclass classification
• Model/Architecture: linear, log-linear
• Loss function: squared error, 0-1 loss, cross-entropy,
hinge loss (tự đọc support vector machine)
• Optimization algorithm: direct solution, gradient descent, perceptron
Linear classifier
Input Weights
x1
w1

x2
w2
Output: sgn(wx + b)
x3
w3 Output: sigmoid(wx + b)
.
.
Thay hàm sgn bằng hàm sigmoid
.
wD
xD
Linear classifier
Linear classifier
Logistic regression
Sigmoid function
• Hàm dự đoán bị chặn (bounded) trong khoảng [0 1]

• Mượt (smooth)

1
𝜎 𝑤𝑇𝑥 =
1 + exp(−𝑤 𝑇 𝑥)
39
Logistic regression
❑ Tính chất của hàm Sigmoid

40
Logistic regression
▪ Giả sử xác suất để một điểm dữ liệu x rơi vào lớp thứ nhất là 𝜎 𝑤 𝑇 𝑥
và rơi vào lớp còn lại là 1 − 𝜎 𝑤 𝑇 𝑥

1
𝑃𝑤 𝑦 = 1 𝑥 = 𝜎 𝑤 𝑇 𝑥 =
1+exp(−𝑤 𝑇 𝑥)
𝑃𝑤 𝑦 = −1 𝑥 = 1 − 𝜎 𝑤 𝑇 𝑥
1+exp −𝑤 𝑇 𝑥 −1 exp(−𝑤 𝑇 𝑥) 1
= = =
1+exp −𝑤 𝑇 𝑥 1+exp(−𝑤 𝑇 𝑥) exp 𝑤 𝑇 𝑥 +1
= 𝜎 −𝑤 𝑇 𝑥

▪ Hàm sigmoid có tính đối xứng: 1 − 𝜎 𝑎 = 𝜎 −𝑎


Logistic regression
❑ Hàm Sigmoid cho phân loại: logistic regression

▪ Thay đầu ra (hàm kích hoạt) của phân loại tuyến tính bằng hàm
sigmoid 𝜎 𝑤 𝑇 𝑥

▪ Bài toán : tìm tham số mô hình w để tối thiểu hàm mất mát

Hàm mất mát dạng này có nhược điểm: không đảm bảo hội tụ tới
nghiệm toàn cục khi dùng gradient descent (nhạy với giá trị ban đầu)

➢ Xây dựng hàm mất mát dựa trên sự ước lượng hợp lý cực đại 42
Logistic regression
❑ Ước lượng hợp lý cực đại MLE
(Maximum likelihood estimation)
▪ Cho tập training data 𝑥𝑖 , 𝑦𝑖 , 𝑖 = 1, … , 𝑛
▪ Đặt 𝑃𝜃 𝑦 𝑥 , 𝜃 ∈ Θ là phân bố xác suất với tham số 𝜃
▪ Áp dụng ước lượng sự hợp lý cực đại: Maximum (conditional) likelihood , giá trị
tốt nhất của trọng số để giúp cực đại hóa sự hợp lý của toàn bộ tập dữ liệu
𝜃𝑀𝐿 = argmax𝜃 ෑ 𝑃𝜃 (𝑦𝑖 |𝑥𝑖 )
𝑖

▪ Không thay đổi mục tiêu ban đầu, ta có thể cực đại hóa log của hàm hợp lý
𝜃𝑀𝐿 = argmax𝜃 σ𝑖 log 𝑃𝜃 (𝑦𝑖 |𝑥𝑖 )

▪ Do các bài toán tối ưu thường biểu diễn dưới dạng cực tiểu hóa. Bài toán
cực đại hóa log của hàm hợp lý trên tương đương với cực tiểu hóa hàm đối
log hợp lý (Negative Log-Likelihood-NLL):
𝜃𝑀𝐿 = argmin𝜃 {− σ𝑖 log 𝑃𝜃 (𝑦𝑖 |𝑥𝑖 )}

Note:The log-likelihood turns products into sums


Logistic regression
❑ Cực tiểu hóa hàm đối log hợp lý (Negative Log-Likelihood-NLL):
𝜃𝑀𝐿 = argmin𝜃 {− σ𝑖 log 𝑃𝜃 (𝑦𝑖 |𝑥𝑖 )}

❖Giả sử với phân phối chuẩn 𝑃𝜃 𝑦 𝑥 = Normal(𝑦; 𝑓𝜃 𝑥 , 𝜎 2 )


2
1 𝑦 − 𝑓𝜃 𝑥
log 𝑃𝜃 𝑦𝑖 𝑥𝑖 = log exp −
2𝜋𝜎 2 2𝜎 2
1 2 1
= − 2 𝑦 − 𝑓𝜃 𝑥 − log 𝜎 − log(2𝜋)
2𝜎 2
1
Do 𝜎 là hằng số, ta bỏ qua 𝜎 và số hạng hằng số, − log 𝜎 − log(2𝜋)
2
Tham số tối ưu đạt được khi cực tiểu hóa hàm mục tiêu sau:
2
𝜃𝑀𝐿 = argmin𝜃 σ𝑖 𝑦𝑖 − 𝑓𝜃 𝑥𝑖

➢ Đây chính là hàm mục tiêu đã xét trong linear regression (tham số 𝜃 là w và b)
Logistic regression
❑ Xây dựng loss cho Logistic regression
▪ Cho tập training data 𝑥𝑖 , 𝑦𝑖 , 𝑖 = 1, … , 𝑛 từ phân bố D
▪ Tìm w để tối thiểu hóa hàm:

෠𝐿 𝑤 = − 1 σ𝑛𝑖=1 log 𝑃𝑤 𝑦𝑖 𝑥𝑖
𝑛

❖ Áp dụng cực tiểu hóa hàm đối log hợp lý (Negative Log-Likelihood-NLL) với
hàm sigmoid:
𝜃𝑀𝐿 = argmin𝜃 {− σ𝑖 log 𝑃𝜃 (𝑦𝑖 |𝑥𝑖 )}

45
Logistic regression
1
▪ Đã biết: 𝑃𝑤 𝑦 = 1 𝑥 = 𝜎 𝑤 𝑇 𝑥 =
1+exp(−𝑤 𝑇 𝑥)
𝑃𝑤 𝑦 = −1 𝑥 = 1 − 𝜎 𝑤 𝑇 𝑥

▪ Hàm mất mát của logistic regression


𝑛
1
෠𝐿 𝑤 = − ෍ log 𝑃𝑤 𝑦𝑖 𝑥𝑖
𝑛
𝑖=1
1 1
= − σ𝑦𝑖=1 log 𝜎 𝑤 𝑇 𝑥𝑖 − σ𝑦𝑖=0 log 1 − 𝜎(𝑤 𝑇 𝑥𝑖 )
𝑛 𝑛

▪ Có thể viết dưới dạng khác (gọn hơn):


𝑛
1
෠𝐿 𝑤 = − ෍ log 𝑃𝑤 𝑦𝑖 𝑥𝑖
𝑛
𝑖=1
1
= − σ𝑛𝑖=1 [𝑦𝑖 log 𝜎 𝑤 𝑇 𝑥𝑖 + (1 − 𝑦𝑖 )log 1 − 𝜎(𝑤 𝑇 𝑥𝑖 ) ]
𝑛

Đây gọi là Binary Cross Entropy (BCE) hay Logs Loss.


46
Logistic regression: Gradient descent
• Hàm dự đoán
• Tham số

• Hàm mất mát (loss)

• Bài toán tối ưu

• Gradient descent:

47
Logistic regression: Gradient descent

48
Logistic regression: Gradient descent

49
Logistic regression: Gradient descent

50
Mô hình với regularization
• Để tránh hiện tượng overfitting, thường dùng thêm hàm hiệu chỉnh
regularization (để giới hạn giá trị của tham số)

• Gradient descent:

51
Logistic regression/classification
▪ Decision boundary
Logistic regression/classification
▪ Decision boundary in higher dimensional spaces (d=2 features):
Code Test

54
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Multiclass classification
Multiclass classification
▪ Classification tasks with more than two categories
Softmax
▪ Ta có biểu thức softmax
exp(𝑧1 ) exp(𝑧𝐶 )
y=softmax 𝑧1 , … , 𝑧𝐶 = σ𝑗 exp(𝑧𝑗 )
, … , σ𝑗 exp(𝑧𝑗 )

vector gồm các thành phần, 𝑧1 , … , 𝑧𝐶 , được biểu diễn qua một vector của
các xác suất tương ứng

▪ Với phân loại C lớp, ta có thể dùng softmax. Khi đó hàm kích hoạt ai
cần tìm có dạng:
exp 𝑧𝑖
𝑎𝑖 =
σ𝑗 exp 𝑧𝑗
exp 𝑤𝑦𝑇𝑖 𝑥𝑖
𝑎𝑖 = 𝑃𝑊 𝑦𝑖 𝑥𝑖 =
σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖
Softmax regression
▪ Hàm mất mát theo Entropy chéo (Cross-entropy loss)
• Tương tự trong bài toán logistic regression, ta lấy negative log likelihood loss
của softmax:
exp 𝑤𝑦𝑇𝑖 𝑥𝑖
𝑙 𝑊, 𝑥𝑖 , 𝑦𝑖 = − log 𝑃𝑊 𝑦𝑖 𝑥𝑖 = −log
σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖
• Có thể coi đó như cross-entropy giữa phân bố thực sự/ “thực nghiệm”
(empirical) 𝑃෠ 𝑘 𝑥𝑖 = 𝕀[𝑘 = 𝑦𝑖 ] và phân bố dự đoán/ “ước lượng” (estimated)
𝑃𝑊 (𝑘|𝑥𝑖 ):
− ෍ 𝑃෠ 𝑘 𝑥𝑖 log 𝑃𝑊 (𝑘|𝑥𝑖 )
𝑘

Liên hệ: cross-entropy giữa hai vector rời rạc p và q: :


Cross-entropy loss
Cách khác để dẫn ra công thức cross-entropy :

▪ Recall binary cross entropy (BCE) loss for logistic regression:


1
binary-cross-entropy = − 𝑁 σ𝑁
𝑖=1 [𝑡𝑖 log 𝑝𝑖 + (1 − 𝑡𝑖 )log 1 − 𝑝𝑖) ]
with 𝑝𝑖 = 𝜎 𝑤 𝑇 𝑥𝑖
▪ For k classes (multiclass):

with 𝑦𝑖 = softmax 𝑤 𝑇 𝑥𝑖
Softmax regression
▪ SGD của cross-entropy loss
• Tối thiểu hóa hàm mất mát: dùng Stochastic Gradient descent (SGD)

exp 𝑤𝑦𝑇𝑖 𝑥𝑖
𝑙 𝑊, 𝑥𝑖 , 𝑦𝑖 = − log 𝑃𝑊 𝑦𝑖 𝑥𝑖 = −log
σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖
= −𝑤𝑦𝑇𝑖 𝑥𝑖 + log ෍ exp 𝑤𝑗𝑇 𝑥𝑖
𝑗
• Gradient w.r.t. 𝑤𝑦𝑖 :
exp 𝑤𝑦𝑇𝑖 𝑥𝑖 𝑥𝑖
−𝑥𝑖 + = (𝑃𝑊 𝑦𝑖 𝑥𝑖 − 1)𝑥𝑖
σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖
• Gradient w.r.t. 𝑤𝑘 , 𝑘 ≠ 𝑦𝑖 :
exp 𝑤𝑘𝑇 𝑥𝑖 𝑥𝑖
𝑇
= 𝑃𝑊 𝑘 𝑥𝑖 𝑥𝑖
σ𝑗 exp 𝑤𝑗 𝑥𝑖
Softmax regression
▪ SGD của cross-entropy loss

• Gradient w.r.t. 𝑤𝑦𝑖 : (𝑃𝑊 𝑦𝑖 𝑥𝑖 − 1)𝑥𝑖

• Gradient w.r.t. 𝑤𝑘 , 𝑘 ≠ 𝑦𝑖 : 𝑃𝑊 𝑘 𝑥𝑖 𝑥𝑖

• Update rule:
• For 𝑦𝑖 :
𝑤𝑦𝑖 ← 𝑤𝑦𝑖 + 𝜂 1 − 𝑃𝑊 𝑦𝑖 𝑥𝑖 𝑥𝑖
• For 𝑘 ≠ 𝑦𝑖 :
𝑤𝑘 ← 𝑤𝑘 − 𝜂𝑃𝑊 𝑘 𝑥𝑖 𝑥𝑖
Softmax regression
▪ Mô hình hồi quy softmax dưới dạng neural network:

63
Softmax regression
▪ Ví dụ phân loại dùng Softmax

▪ Sau khi mô hình đã được huấn luyện (trained):


• Nhãn (label) của mỗi điểm dữ liệu mới được tính là vị trí của thành phần
score có giá trị lớn nhất trong score vector

𝒛 = 𝑾𝑇 𝒙
64
Softmax regression
Minh họa tính hàm Loss của Softmax
• Hàm mất mát của Softmax regression:
exp 𝑤𝑦𝑇𝑖 𝑥𝑖
𝐿𝑖 = 𝑙 𝑊, 𝑥𝑖 , 𝑦𝑖 = − log 𝑃𝑊 𝑦𝑖 𝑥𝑖 = −log
σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖
• Đặt 𝑠𝑦𝑖 = 𝑤𝑦𝑇𝑖 𝑥𝑖 ; 𝑠𝑗 = σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖

• Giả sử đã có score vector:

𝒛 = 𝑾𝑇𝒙

65
Minh họa tính hàm Loss của Softmax

66
Minh họa tính hàm Loss của Softmax

67
Minh họa tính hàm Loss của Softmax

68
Minh họa tính hàm Loss của Softmax

69
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Demo
Demo 1: Lec3_Lab01_LinearRegression_np.ipynb

Demo 2: Lec3_Lab02_Logistic_Classification.ipynb
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
▪ Autograd (next lecture)
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 11:
Backpropagation and
Automatic Differentiation
Van-Truong Pham, PhD
School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents

▪ Chain rule
▪ Computational graph
▪ Backpropagation
▪ Automatic differentiation
▪ Autograd
▪ Python demo
Contents

▪ Chain rule
▪ Computational graph
▪ Backpropagation
▪ Automatic differentiation
▪ Autograd
▪ Python demo
Chain rule
Given: g(f) and f(x)

• Scalar chain rule

where g ◦ f is a function composition

• Vector chain rule

where we define the gradient as a row vector


Chain rule
• Define the variable y as the output of f(x) and the variable z as the output of
g(y), then we can write in Leibniz notation,

More precisely
Chain rule
Chain rule
Chain rule
Contents

▪ Chain rule
▪ Computational graph
▪ Backpropagation
▪ Automatic differentiation
▪ Autograd
▪ Python demo
Computational graph
▪ A computational graph is a directed graph where the nodes correspond to
operations or variables.
▪ The values that are fed into the nodes and come out of the nodes are called tensors
Computational graph
▪ An example of computational graph
f(x)=x1+x2+x3+x4
z1= x1*x2
z2= x3 * x4
x1 f(x)=z1+z2

z1= x1*x2
x2

f=z1+z2
x3

z2= x3 * x4
x4
Computational graph
▪ Forward propagation:
Given: f(x)=x1+x2+x3+x4
x1=2
x2=3 z1= x1*x2
x3=1 z2= x3 * x4
x4=4
f(x)=z1+z2
x1 2

3 z1= x1*x2
x2

f=z1+z2
x3 1

z2= x3 * x4
4
x4
Computational graph
▪ Forward propagation:
z1=2*3=6 f(x)=x1+x2+x3+x4
x1=2
x2=3 z2=1 * 4=4 z1= x1*x2
x3=1 f=z1+z2=10 z2= x3 * x4
x4=4
x1 2 f(x)=z1+z2

3 z1= x1*x2 6
x2
10
f=z1+z2
x3 1
4

z2= x3 * x4
4
x4
Computational graph
▪ Backward propagation: 𝜕𝑓 𝐱
=
𝜕𝑓 𝜕𝑧1
= 1 ∗ 𝑥2 =3 f(x)=x1+x2+x3+x4
𝜕𝑥1 𝜕𝑧1 𝜕𝑥1
Derivative of f with respect to x? 𝜕𝑓 𝐱 𝜕𝑓 𝜕𝑧1 z1= x1*x2
= = 1 ∗ 𝑥1 =2
𝜕𝑥2 𝜕𝑧1 𝜕𝑥2
z2= x3 * x4
𝜕𝑓 𝐱 𝜕𝑓 𝜕𝑧2
= = 1 ∗ 𝑥4 =4
𝜕𝑥3 𝜕𝑧2 𝜕𝑥3 f(x)=z1+z2
x1 2 𝜕𝑓 𝐱
=
𝜕𝑓 𝜕𝑧2
= 1 ∗ 𝑥3 =1 x1=2 z1=2*3=6
𝜕𝑥4 𝜕𝑧2 𝜕𝑥4
3 x2=3 z2=1 * 4=4
x3=1 f=z1+z2=10
3 z1= x1*x2 6 x4=4
x2
2 1
10
f=z1+z2
x3 1 𝜕𝑓
4 =1
1 𝜕𝑧1
4
𝜕𝑓
z2= x3 * x4 =1
4 𝜕𝑧2
x4 1
Green numbers: Forward propagation
Red numbers: Backward propagation
Contents

▪ Chain rule
▪ Computational graph
▪ Backpropagation
▪ Automatic differentiation
▪ Autograd
▪ Python demo
Backpropagation Example 1
▪ Ví dụ đơn giản về Backpropagation

16 2017
Source: CS231n
Backpropagation Example 1

17 2017
Source: CS231n
Backpropagation Example 1

18 2017
Source: CS231n
Backpropagation Example 1

19 2017
Source: CS231n
Backpropagation Example 1

20 2017
Source: CS231n
Backpropagation Example 1

21 2017
Source: CS231n
Backpropagation Example 1

22 2017
Source: CS231n
Backpropagation Example 1

23 2017
Source: CS231n
Backpropagation Example 1

24 2017
Source: CS231n
Backpropagation Example 1

25 2017
Source: CS231n
Backpropagation Example 1

26 2017
Source: CS231n
Backpropagation Example 1

27 2017
Source: CS231n
Backpropagation

28 2017
Source: CS231n
Backpropagation

29 2017
Source: CS231n
Backpropagation

30 2017
Source: CS231n
Backpropagation

31 2017
Source: CS231n
Backpropagation

32 2017
Source: CS231n
Backpropagation

33 2017
Source: CS231n
Backpropagation Example 2

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Local Upstream
gradient * gradient

1/𝑥 ′ = −1/𝑥 2
1
− ∗ 1 = −0.53
1.372
Source: Stanford 231n
Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Local Upstream
gradient * gradient

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Local Upstream
gradient * gradient

exp −1 ∗ −0.53 = −0.20

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Local Upstream
gradient * gradient

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Local Upstream
gradient * gradient

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Local Upstream
gradient * gradient

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

-0.60

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

-0.40

-0.60

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

0.40

-0.40

-0.60

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

0.40

-0.40

-0.60

Source: Stanford 231n


Backpropagation Example 2
1
𝑓 𝑥, 𝑤 =
1 + exp − 𝑤0 𝑥0 + 𝑤1 𝑥1 + 𝑤2

0.40 Can simplify computation graph

-0.40

-0.60

Sigmoid gate 𝜎 𝑥
𝜎′ 𝑥 = 𝜎 𝑥 1 − 𝜎 𝑥
𝜎 1 1 − 𝜎 1 = 0.73 ∗ 1 − 0.73 = 0.20

Source: Stanford 231n


Contents

▪ Chain rule
▪ Computational graph
▪ Backpropagation
▪ Automatic differentiation
▪ Autograd
▪ Python demo
Automatic differentiation
▪ Automatic differentiation as cached chain rule

• Consider a function G(x) := g(f(x)), with intermediate variable y and final output z
Automatic differentiation
▪ Automatic differentiation as cached chain rule
• Given a function G(w) := g(f(e(w))), with intermediate variables x, y and final output z.

We can cache the chain rule from the left (forward) or the right (reverse).
Automatic differentiation
▪ Automatic differentiation: Tính vi phân tự động
• Với các mô hình phức tạp, nhiều biến, việc tự tính toán đạo hàm thường tốn
thời gian
• Pytorch cung cấp gói tính vi phân tự động autograd
• Mỗi khi đưa dữ liệu chạy qua mô hình, cơ chế autograd xây dựng một đồ thị
và theo dõi xem dữ liệu nào kết hợp với các phép tính nào để tạo ra kết quả.
• Với đồ thị này autograd có thể lan truyền ngược gradient lại theo ý muốn.
• Lan truyền ngược (backpropagation) là truy ngược lại đồ thị tính toán và điền
vào đó các giá trị đạo hàm riêng theo từng tham số
Contents

▪ Chain rule
▪ Computational graph
▪ Backpropagation
▪ Automatic differentiation
▪ Autograd
▪ Python demo
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
A simplified workflow in supervised learning

• Creating dataset
• Creating a neural network (model)
• Defining a loss function
• Loading samples (data loader)
• Predicting with the model
• Comparison of the prediction and the target (loss)
• Backpropagation: calculating gradients from the error
• Updating the model (optimizer)
• Checking the loss: if it is low enough, stop training
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
Major deep learning frameworks
▪ Why do we need Deep learning frameworks?

• Speed:
✓ Fast GPU/CPU implementation of matrix multiplication, convolutions and
backpropagation
• Automatic differentiations:
✓ Pre-implementation of the most common functions and their gradients.
• Reuse:
✓ Easy to reuse other people’s models
• Less error prone:
✓ The more code you write yourself, the more errors.

Source: David Völgyes


Major deep learning frameworks
▪ Major frameworks
pytorch (developed by Facebook)
Tensorflow (developed by Google)
Caffe (developed by Facebook)
MXNet
MS Cognitive Toolkit (CNTK)
Chainer
Remark: all of them are open source.

▪ Popularity, late 2019


Industry is still dominated by Tensorflow / Keras
But 70-75% of the academic papers are in PyTorch
Major projects change to PyTorch
Major deep learning frameworks
▪ Readings
• Pytorch tutorials: https://pytorch.org/tutorials/
• Deep Learning with PyTorch: A 60 Minute Blitz
• https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html
• Pytorch cheat sheet: https://pytorch.org/tutorials/beginner/ptcheat.html
• Broadcasting: https://pytorch.org/docs/stable/notes/broadcasting.html
• Awesome PyTorch list: https://github.com/bharathgs/Awesome-PyTorch-list
• It is a collection of hundred of links, including tutorials, research papers,
libraries, etc.
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
PyTorch
• Python Application Programming Interface (API)
• Can use CPU, GPU (CUDA only)
• Supports common platforms: Windows, iOS, Linux
• PyTorch is a thin framework which lets you work closely with programming
the neural network
• Focus on the machine learn part not the framework itself
• Pythonic control flow
✓ Flexible
✓ Cleaner and more intuitive code
✓ Easy to debug
• Python debugger
✓ With PyTorch we can use the python debugger
PyTorch packages
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
Torch. tensor class
▪ PyTorch ’s tensors are very similar to NumPy’s ndarrays
▪ but they have a device, 'cpu', 'cuda', or 'cuda:X'
▪ they might require gradients
t = torch.tensor([1,2,3], device='cpu’, requires_grad=False,dtype=torch.float32)
t2 = t.to(torch.device('cuda'))
t3 = t.cuda() # use shorthand
t4 = t.cpu()
▪ Conversion in numpy and in PyTorch:
new_array = old_array.astype(np.int8) # numpy array
new_tensor = old_tensor.to(torch.int8) # torch tensor

https://pytorch.org/docs/stable/tensors.html
Torch. tensor class
Numpy-PyTorch functions
▪ Creating arrays / tensor:
• eye: creating diagonal matrix / tensor
• zeros: creating tensor filled with zeros
• ones: creating tensor filled with ones
• linspace: creating linearly increasing values
• arange: linearly increasing integers
PyTorch functions, dimensionality
x.size() #* return tuple-like object of dimensions, old codes
x.shape # return tuple-like object of dimensions, numpy style
x.ndim # number of dimensions, also known as .dim()
x.view(a,b,...) #* reshapes x into size (a,b,...)
x.view(-1,a) #* reshapes x into size (b,a) for some b
x.reshape(a,b,...) # equivalent with .view()
x.transpose(a,b) # swaps dimensions a and b
x.permute(*dims) # permutes dimensions; missing in numpy
x.unsqueeze(dim) # tensor with added axis; missing in numpy
x.unsqueeze(dim=2) # (a,b,c) tensor -> (a,b,1,c) tensor; missing in numpy
torch.cat(tensor_seq, dim=0) # concatenates tensors along dim
Indexing
▪ Standard numpy indexing works:
Memory: Sharing vs Copying
• Copy Data: • Share Data
torch.Tensor() torch.as_tensor()
torch.tensor() torch.from_numpy()
torch.clone() torch.view()
type casting torch.reshape()

• How to test it?


create a tensor
copy/clone/view it
modify an element
compare the elements
Creating instances of torch.Tensor without data
Interacting with numpy

Remarks:
arrays / tensors must be on the same device.
only detached arrays can be converted to numpy
if data types are not the same, casting might be needed (v1.1 or older)
E.g. adding an integer and a float tensor together.
Torch.tensor functionality
• Common tensor operations:
reshape
max/min
shape/size
etc
• Arithmetic operations
Abs / round / sqrt / pow /etc
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
Autograd: A toy example
Autograd: A toy example
Autograd: A toy example
Autograd Example 1
▪ Thực hiện tính vi phân tự động cho thuật toán có computation graph dưới đây:

f(x)=x1+x2+x3+x4
z1= x1*x2
z2= x3 * x4
x1 f(x)=z1+z2

z1= x1*x2
x2

f=z1+z2
x3

z2= x3 * x4
x4
Autograd Example 1
f(x)=x1+x2+x3+x4
x1 2
z1= x1*x2
z2= x3 * x4
3 z1= x1*x2 f(x)=z1+z2
x2

f=z1+z2
x3 1

z2= x3 * x4
4
x4
Autograd Example 1
x1 2 f(x)=x1+x2+x3+x4
z1= x1*x2
z2= x3 * x4
3 z1= x1*x2 6
x2 f(x)=z1+z2

10
f=z1+z2
x3 1
4

z2= x3 * x4
4 x1=2 z1=2*3=6
x4 x2=3 z2=1 * 4=4
x3=1 f=z1+z2=10
x4=4
Autograd Example 1
▪ Backward propagation: 𝜕𝑓 𝐱
=
𝜕𝑓 𝜕𝑧1
= 1 ∗ 𝑥2 =3 f(x)=x1+x2+x3+x4
𝜕𝑥1 𝜕𝑧1 𝜕𝑥1
Derivative of f with respect to x? 𝜕𝑓 𝐱 𝜕𝑓 𝜕𝑧1 z1= x1*x2
= = 1 ∗ 𝑥1 =2
𝜕𝑥2 𝜕𝑧1 𝜕𝑥2
z2= x3 * x4
𝜕𝑓 𝐱 𝜕𝑓 𝜕𝑧2
= = 1 ∗ 𝑥4 =4
𝜕𝑥3 𝜕𝑧2 𝜕𝑥3 f(x)=z1+z2
x1 2 𝜕𝑓 𝐱
=
𝜕𝑓 𝜕𝑧2
= 1 ∗ 𝑥3 =1 x1=2 z1=2*3=6
𝜕𝑥4 𝜕𝑧2 𝜕𝑥4
3 x2=3 z2=1 * 4=4
x3=1 f=z1+z2=10
3 z1= x1*x2 6 x4=4
x2
2 1
10
f=z1+z2
x3 1 𝜕𝑓
4 =1
1 𝜕𝑧1
4
𝜕𝑓
z2= x3 * x4 =1
4 𝜕𝑧2
x4 1
Autograd Example 1
Autograd Example 1
Autograd Example 1
Autograd Example 1
Autograd Example 2
▪ Linear Regression
• Tạo một tập điểm dữ liệu, giả sử phân bố theo đường tuyến tính y=ax+b.
• Ta cộng nhiễu vào để các điểm đó lệch đi một đoạn so với đường thẳng chuẩn
Autograd Example 2
• Ta cộng nhiễu vào để các điểm đó lệch đi một đoạn so với đường thẳng chuẩn

• Các điểm (đã được cộng nhiễu) coi như dữ liệu của tập training
Autograd Example 2
• Training:
Autograd Example 2
• Prediction:

Lec3_Lab03_autograd.ipynb
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
See: next lectures
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 12 :
Neural networks

Van-Truong Pham, PhD


School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents

▪ Introduction
▪ Fundamentals of neural networks
▪ Backpropagation for NN training
▪ Example
▪ Python demo
Contents

▪ Introduction
▪ Fundamentals of neural networks
▪ Backpropagation for NN training
▪ Example
▪ Python demo
Introduction
Artificial Neural Network
▪ Commonly refered as Neural Network (NN)
▪ Basic principles:
• One neuron can perform a simple decision.
• Many connected neurons can make more complex decisions.
Characteristics of a NN
▪ Network configuration
• How are the neurons inter-connected?
• We typically use layers of neurons (input, output, hidden).
▪ Individual neuron parameters
• Weights associated with inputs.
• Activation function.
• Decision thresholds.
Learning paradigms
▪ We can define the network configuration.
▪ How do we define neuron weights and decision thresholds?
• Learning step.
• We train the NN to classify what we want.
• (Supervised learning): We need to have access to a set of training data
for which we know the correct class/answer

▪ We want to obtain an optimal solution given a set of


observations.
• A cost function (loss) measures how close our solution is to
the optimal solution.
• Objective of our learning step:
• Minimize the loss.
Backpropagation
Algorithm
Loss Functions for NNs
▪ Regression:
Use the same loss as Linear Regression (quadratic i.e. mean squared error)

▪ Classification:
• Use the same loss as Logistic Regression (sigmoid for binary classification)
• Cross-entropy (i.e. negative log likelihood)

• This requires probabilities, so we add an additional “softmax” layer at the end of


our network.
Neural Network (NN)
▪ Neural networks (NNs) learn a mapping fw from input data feature x to
output vector y:
Simple neural network
▪ One input layer and one output layer:
Simple neural network
▪ One input layer, one hidden layer and one output layer:

The middle layer of nodes is called the hidden


layer, because its values are not observed in
the training set.
Deep neural network
▪ Neural network with multiple layers (a.k.a. deep learning)
Forward pass
▪ The NN activations yl, l=1,2,…,L are computed from left to right, from input data x
to output prediction fw(x). This is called the forward pass:
Feedforward neural networks
▪ The NN architectures without loop connections (i.e. cycles) are called feedforward NNs.
Examples are fully connected neural networks and convolutional neural networks.

▪ The neural network architectures with loop connections (i.e. cycles)


are called recurrent neural networks:
Contents

▪ Introduction
▪ Fundamentals of neural networks
▪ Backpropagation for NN training
▪ Example
▪ Python demo
Multilayer neural network
▪ Multilayer neural network: MLP (Multilayer perceptron)
▪ MLP is a class of feedforward artificial neural network
Input layer
▪ Input neurons
The number of features your neural network uses to make its predictions.
The input vector needs one input neuron per feature.
For images, this is the dimensions of your image (28*28=784 in case of MNIST).

First layer Output layer


……
𝒚

Input 𝒙 ℎ𝑙 ℎ𝐿
Input layer
▪ For MNIST, input is the dimensions of the image (28*28=784)
Hidden layers
▪ Hidden Layers and Neurons per Hidden Layers:

• Neuron nhận thông tin (các kết hợp tuyến tính) từ tầng trước đó
• Đầu ra của tầng này được đưa vào tầng tiếp theo

ℎ𝑙 ℎ𝑙+1
Hidden layers

• Đầu vào của các hidden layer: z


• Số unit trong layer thứ l (không tính bias): d (l)
• Đầu ra của mỗi unit: a (activation function): (
a(l ) = f W (l )T a(l −1) + b(l ) )
Activation functions
Hidden layers
• In general, using the same number of neurons for all hidden layers will suffice.
• first layer can learn lower-level features;
subsequent layers can learn higher order features.
Output layer
▪ Output neurons: The number of predictions you want to make.

• For regression: For regression tasks, this can be one value (e.g. housing price).
• For binary classification: we use one output neuron per positive class
(the output represents the probability of the positive class)
• For multi-class classification: we have one output neuron per class, and use the
softmax activation function on the output layer
Output layer
• For multi-class classification: use softmax activation function on the output layer
Output layer
First layer Output layer


……
𝒚

Input 𝒙 ℎ𝑙 ℎ𝐿
Output layer
• Dạng regression: 𝑦 = 𝑤 𝑇 ℎ + 𝑏


Output layer
First layer Output layer


……
𝒚

Input 𝒙 ℎ𝑙 ℎ𝐿
Output layer

• Multi-dimensional regression:
𝑦 = 𝑊𝑇ℎ + 𝑏
𝑦


Output layer

• Phân loại nhị phân (Binary classification): Output layer


𝑦 = 𝜎(𝑤 𝑇 ℎ + 𝑏)
• Tương ứng với thực hiện hồi quy
logistic trên biến ℎ
1
𝜎 𝑤𝑇𝑥 =
1 + exp(−𝑤 𝑇 𝑥)
𝑦


Output layer

• Phân loại đa lớp (Multi-class classification):


𝑦 = softmax 𝑧 với 𝑧 = 𝑊 𝑇 ℎ + 𝑏 Output layer

• Tương ứng với multi-class


logistic regression (softmax)
trên lớp ẩn (cuối) ℎ 𝑧 𝑦

exp 𝑤𝑦𝑇𝑖 𝑥𝑖
softmax(𝑤𝑦𝑇𝑖 𝑥𝑖 ) =
σ𝑗 exp 𝑤𝑗𝑇 𝑥𝑖


Output layer

29
Contents

▪ Introduction
▪ Fundamentals of neural networks
▪ Backpropagation for NN training
▪ Example
▪ Python demo
Training a neural network
First layer Output layer


……
𝒚

Input 𝒙 …
z (l −1) a(l −1) z (l ) a( l ) a( L ) yˆ = a( L )
ℎ𝑙 ℎ𝐿
▪ Đầu ra dự đoán: Đầu ra của MLP ứng với một đầu vào x :
a(1) = x
z (l +1) = W (l )T a(l ) + b(l +1) , l = 1, 2, ,L
( ) (
a(l +1) = f z (l +1) = f W (l )a(l ) + b(l +1) ) Forward pass
yˆ = a( L )
➢ Quá trình training/learning của mạng neuron/MLP thực hiện như thế nào?
→ Backpropagation & gradient descent 31
Forward pass
▪ Quá trình lan truyền thuận (Forward pass) : a(1) = x
(mục tiêu: tính hàm kích hoạt đầu ra a tại mỗi lớp)
z (l +1) = W (l )a(l ) + b(l +1) , l = 1, 2, ,L
( ) (
a(l +1) = f z (l +1) = f W (l )a(l ) + b(l +1) )
yˆ = a( L )
• Giả sử J(W,b,X,Y) là hàm mất mát của bài toán

N N
1 1
J ( W, b, X, Y ) = y y ( L) 2
− yˆ n = − an
2
n 2 n
N n =1 N n =1
2

W, b: trọng số giữa các layers và bias của mỗi layer

X,Y: cặp dữ liệu huấn luyện

• Việc tính toán trực tiếp các giá trị đạo hàm là phức tạp: vì hàm mất mát không trực tiếp
phụ thuộc vào W, b

• Phương pháp (phổ biến nhất) backpropagation: tính đạo hàm ngược từ layer cuối cùng
đến layer đầu tiên, dựa trên quy tắc chuỗi (chain rule- đạo hàm của hàm số hợp)

➢ Vấn đề: làm thế nào để biết hàm error của mỗi hidden layer? 32
Backpropagation
• Đạo hàm của hàm mất mát theo chỉ một thành phần của ma trận trọng số của
output layer:
( L)
J J z j ( L ) ( L −1)
( L)
= ( L) ( L)
= e ai
wij z j wij
j

J
Trong đó: e j ( L) =
z j ( L )

( L −1) z j ( L )
ai = ( L)  z j ( L ) = w j ( L )T a( L −1) + b j ( L )
wij

• Tương tự, đạo hàm của hàm mất mát theo bias của layer cuối cùng:
( L)
J J z j ( L)
b ( L) = = = e
b j ( ) z j ( ) b j ( )
L L L j
j

33
Backpropagation
• Bằng quy nạp ngược từ cuối
(l )
J J z j ( l ) ( l −1) J (l )
W ( l ) = = = e j ai
= e
(l ) (l ) (l )
b j (l )
j
wij z j wij
(l )
J a j  J z (l +1) 
d( )
l +1
J
Với ej (l )
=
z j (l )
=
a j (l ) z j (l )
=   (l +1) k (l )  f  z j (l )
 z a j 
( )
k =1
 k
d( )
l +1

=  ( e
k =1
(
k
l +1)
) ( )
w jk (l +1) f  z j (l )

( l +1)
J
( ) ( )
d
→ = 
wij ( ) k =1
l
ek
( l +1)
w jk
( l +1)
f  z j (l ) Hàm kích hoạt
(Nên chọn sao cho dễ lấy đạo hàm)

phụ thuộc sai số e (giữa đầu ra và dự đoán) lớp trước và đạo hàm của hàm kích
hoạt theo đầu ra của lớp hiện tại
J
• Cập nhật hệ số: theo gradient descent: wk  wk − 
wk

Trong thực thi, b thường được chèn trong W: W (l )  W (l ) − W ( l )


34
Backpropagation: summary
1. Bước forward: Với một giá trị đầu vào x, tính giá trị đầu ra của mạng. Trong quá trình
tính toán, lưu lại các giá trị a(l) tại mỗi layer.

( )
a(l ) = f (l ) z (l ) ; z (l ) = W (l )T a(l −1) + b(l )
2. Với mỗi unit thứ j ở output layer, tính:
J J J
e j ( L) = ( L)
; = e ( L ) ( L −1)
ai ; = e ( L)
( L)
z j wij b j ( L )
j j

3. Với l=L-1, L-2, …,1, tính : ( ) ( )


e j (l ) = w jk (l +1)e k (l +1) . f  z j (l )

J ( l ) ( l −1) J (l )
4. Cập nhật đạo hàm cho từng hệ số: = e a ; = e
wij (l ) b j (l )
j i j

J J
wij (l )  wij (l ) −  (l )
; b j (l )  b j (l ) − 
wij b j (l )
35
Contents

▪ Introduction
▪ Fundamentals of neural networks
▪ Backpropagation for NN training
▪ Example
▪ Python demo
Probability vector for multi-class
▪ Minh họa cho ảnh đầu vào x, và đầu ra y là xác suất để bức ảnh thuộc vào
một trong K lớp

▪ Biểu diễn vector xác suất cho multi-class

Output layer

Số lượng neuron đầu ra


bằng số lượng các lớp, ví
dụ K=3, tương ứng với
{cat, dog, car}

a1 = x a2 a3 ŷ

37
Probability vector for multi-class
▪ Minh họa cho ảnh đầu vào x, và đầu ra y là xác suất để bức ảnh thuộc vào
một trong K lớp
Ví dụ dùng mạng với hai lớp ẩn

Đầu ra mã hóa xác suất nhóm cat

Đầu ra mã hóa xác suất nhóm dog

Đầu ra mã hóa xác suất nhóm car

a1 = x a2 a3 ŷ 0.15 
 
Ví dụ đầu ra với K=3 được : yˆ = pw ( x) = 0.80 
z (l ) = W (l )T a (l −1) + b(l ) , l = 2, ,L 0.05 

( ) (
a (l ) = f z (l ) = f W (l )T a (l −1) + b(l ) ) Có 80% khả năng bức ảnh là dog
38
(bias trick)
Backpropagation algorithm
▪ Ví dụ: Thuật toán huấn luyện mạng 3 layers để phân loại ảnh với 10 classes
n1 = d = 400; n2 = 25; n3 = K = 10

Neuron đầu ra mã hóa xác


suất ảnh thuộc vào lớp
(ví dụ dog)

pw ( x )
yˆ = pw ( x)

39
Forward pass
▪ Bước Forward:
l = 1, 2, ,L
Forward Pass

a l +1 = f (W l a l )

Hàm kích hoạt,


ví dụ sigmoid

• Chu trình forward a 3 = f (W 2 a 2 )

a1 → a 2 → a 3 a 2 = f (W 1a1 )

a1 = x

được lưu để dùng


cho bước tiếp theo al +1 = f (W l al + bl +1 )
(backward) 40
Bias b được gộp trong các ma trận trọng số W1, W2
Backward pass
▪ Bước Backward:
e3 = a 3 − yˆ
For l = 2, 1
J l +1 l
W l = = e a;
w l

W l  W l − W l

el = (W ) el +1 . f  ( a l )
T

e3 = a 3 − yˆ

• Chu trình Backward: W 2 = e3 a 2


W 2  W 2 − W 2
e3 → W 2 → W 2 → e 2 → W 1 → W 1
e 2 = (W 2 ) e3 . f  ( a 2 )
T

W 1 = e 2 a1
W 1  W 1 − W 1 41
Backward Pass
Modern backpropagation
▪ Backpropagation is the backbone of the learning algorithm, but it may
not be easy to implement efficiently.

▪ Modern implementations are TensorFlow (Google) and PyTorch


(Facebook) that perform automatically backpropagation and weight
update - no need to implement backprog!

▪ TensorFlow and PyTorch are amazing libraries to build and train neural
network architectures, and they are optimized for GPUs.

42
Contents

▪ Introduction
▪ Fundamentals of neural networks
▪ Backpropagation for NN training
▪ Example
▪ Python demo
Python/Pytorch Tutorials
▪ Major deep learning frameworks
▪ PyTorch packages
▪ Pytorch
• Torch.tensor
• Computational graph
• Automatic differentiation (torch.autograd)
• Data loading and preprocessing (torch.utils)
• Useful functions (torch.nn.functional)
• Creating the model (torch.nn)
• Optimizers (torch.optim)
• Save/load models
Demo

45
Demo

a1 = x
l = 1, 2, ,L
a l +1 = f (W l a l )
Hàm kích hoạt sigmoid
a =x
1

a 2 = f (W 1a1 )
a 3 = f (W 2 a 2 ) 46
Demo

e3 = a 3 − yˆ

W 2 = e3 a 2
W 2  W 2 − W 2
Regularization e = (W
2
)
2 T
e3 . f  ( a 2 )
W 1 = e 2 a1
W 1  W 1 − W 1

47
Demo

a1 = x
a 2 = f (W 1a1 )
a 3 = f (W 2 a 2 )

48
Lec4_Lab01_vanilla_nn.ipynb

Lec4_Lab02_train_vanilla_nn.ipynb

Lec4_Lab03_minibatch_training.ipynb

Lec4_Lab04_mlp_demo.ipynb
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 13 :
Convolutional Neural Networks (CNN)

Van-Truong Pham, PhD


School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolution
▪ Biểu thức toán của convolution:

▪ Dạng rời rạc (discrete):

4
2D Convolution
▪ Tích chập hai chiều

5
2D Convolution
▪ Tích chập hai chiều

6
2D Convolution
▪ Tích chập hai chiều

7
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Kernel
▪ The thing we convolve by is called a kernel, or filter
▪ What does this convolution kernel do?
Kernel

▪ What does this convolution kernel do?


Kernel

▪ What does this convolution kernel do?


Kernel

▪ What does this convolution kernel do?


Filters
▪ Mỗi convolutional layer gồm nhiều filter, dùng để thực
hiện phép tính tích chập

Beak detector

A filter
Filters
▪ Mỗi kernel cho ta một image filter khác nhau
Filters
Đây là các tham số học của mạng

1 -1 -1
1 0 0 0 0 1 -1 1 -1 Filter 1
0 1 0 0 1 0 -1 -1 1
0 0 1 1 0 0
1 0 0 0 1 0 -1 1 -1
-1 1 -1 Filter 2
0 1 0 0 1 0
0 0 1 0 1 0 -1 1 -1



6 x 6 image
Mỗi filter dò một miền nhỏ
(ví dụ kích thước 3 x 3).
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1 Dot
product
0 1 0 0 1 0 3
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1 Dot
product
0 1 0 0 1 0 3 -1
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1 Dot
product
0 1 0 0 1 0 3 -1 -3
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
If stride=2

1 0 0 0 0 1
0 1 0 0 1 0 3 -3
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
If stride=2

1 0 0 0 0 1
0 1 0 0 1 0 3 -3 -2
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
-1 1 -1
-1 1 -1 Filter 2
-1 1 -1
stride=1
Lặp lại cho mỗi filter
1 0 0 0 0 1
0 1 0 0 1 0 3 -1 -3 -1
-1 -1 -1 -1
0 0 1 1 0 0
1 0 0 0 1 0 -3 1 0 -3
-1 -1 -2 1
0 1 0 0 1 0 Feature
0 0 1 0 1 0 -3 -3 Map0 1
-1 -1 -2 1

6 x 6 image 3 -2 -2 -1
-1 0 -4 3

Hai ảnh có kích cỡ 4x4


Tạo ma trận 2 x 4 x 4
For RGB image

11 -1-1 -1-1 -1-1 11 -1-1


1 -1 -1 -1 1 -1
-1 1 -1 -1-1 11 -1-1
-1-1 11 -1-1 Filter 1 -1 1 -1 Filter 2
-1-1 -1-1 11 -1-1-1 111 -1-1-1
-1 -1 1
Color image
1 0 0 0 0 1
1 0 0 0 0 1
0 11 00 00 01 00 1
0 1 0 0 1 0
0 00 11 01 00 10 0
0 0 1 1 0 0
1 00 00 10 11 00 0
1 0 0 0 1 0
0 11 00 00 01 10 0
0 1 0 0 1 0
0 00 11 00 01 10 0
0 0 1 0 1 0
0 0 1 0 1 0
For RGB image
For RGB image
For RGB image
For RGB image
For RGB image
Padding
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
▪ Ta đã có đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

• Convoution with Filter 1 1 -1 -1


-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1
0 1 0 0 1 0 3 -1 -3 -1
0 0 1 1 0 0
1 0 0 0 1 0 -3 1 0 -3
0 1 0 0 1 0
0 0 1 0 1 0 -3 -3 0 1

6 x 6 image 3 -2 -2 -1
▪ Ta đã có đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

• Convoution with Filter 2


-1 1 -1
-1 1 -1 Filter 2
stride=1 -1 1 -1

1 0 0 0 0 1
0 1 0 0 1 0 3 -1 -3 -1
-1 -1 -1 -1
0 0 1 1 0 0
1 0 0 0 1 0 -3 1 0 -3
-1 -1 -2 1
0 1 0 0 1 0
0 0 1 0 1 0 -3 -3 0 1
-1 -1 -2 1

6 x 6 image 3 -2 -2 -1
-1 0 -4 3
▪ Ta đã có đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

3 -1 -3 -1
-1 -1 -1 -1
-3 1 0 -3
-1 -1 -2 1

1 0 0 0 0 1 -3 -3 0 1
-1 -1 -2 1
0 1 0 0 1 0 Conv
3 -2 -2 -1
0 0 1 1 0 0 -1 0 -4 3
1 0 0 0 1 0
0 1 0 0 1 0 Max
0 0 1 0 1 0 Pooling

6 x 6 image
Pooling

33
Max Pooling
▪ Thực hiện Pooling với đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

1 -1 -1 -1 1 -1
-1 1 -1 Filter 1 -1 1 -1 Filter 2
-1 -1 1 -1 1 -1

3 -1 -3 -1 -1 -1 -1 -1

-3 1 0 -3 -1 -1 -2 1

-3 -3 0 1 -1 -1 -2 1

3 -2 -2 -1 -1 0 -4 3
Why Pooling?
▪ Giảm chiều không thay đổi đối tượng trong ảnh

bird
bird

Subsampling

Giúp kích cỡ ảnh giảm đi

fewer parameters to characterize the image


Max Pooling

New image
1 0 0 0 0 1 but smaller
0 1 0 0 1 0 Conv
3 0
0 0 1 1 0 0 -1 1
1 0 0 0 1 0
0 1 0 0 1 0 Max 3 1
0 3
0 0 1 0 1 0 Pooling
2 x 2 image
6 x 6 image
Each filter
is a channel
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolutional networks
▪ Convolutional networks have two kinds of layers:
detection layers (or convolution layers), and pooling layers

▪ Convolution layer has a set of filters. Its output is a set of feature


maps, each one obtained by convolving the image with a filter
Convolutional networks
▪ It’s common to apply a linear rectification nonlinearity:
yi=max(zi,0)

▪ Why?
• Convolution is a linear operation. Therefore, we need a nonlinearity, otherwise
2 convolution layers would be no more powerful than 1
• Two edges in opposite directions shouldn’t cancel
• Makes the gradients sparse, which helps optimization.
Convolutional networks

▪ Why pooling?
Convolutional networks
• Because of pooling, higher-layer filters can cover a larger region of the input
than equal-sized filters in the lower layers
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolution v.s. Fully Connected
▪ Tương tác giữa các nút thưa (sparse) so với lớp kết nối đầy đủ
(Fully connected layer)

Còn gọi là
Fully connected
43
Fully Connected Layer
Example: 200x200 image
40K hidden units
~2B parameters!!!

- Spatial correlation is local


- Waste of resources + we have not enough
training samples anyway.. 44
Slide Credit: Marc'Aurelio Ranzato
Locally Connected Layer

Example: 200x200 image


40K hidden units
Filter size: 10x10
4M parameters

Note: This parameterization is good when


input image is registered (e.g., face
recognition). 45
Slide Credit: Marc'Aurelio Ranzato
Locally Connected Layer
STATIONARITY? Statistics is similar at
different locations

Example: 200x200 image


40K hidden units
Filter size: 10x10
4M parameters

Note: This parameterization is good when


input image is registered (e.g., face
recognition). 46
Slide Credit: Marc'Aurelio Ranzato
Convolutional Layer

Share the same parameters across different


locations (assuming input is stationary):
Convolutions with learned kernels

47
Slide Credit: Marc'Aurelio Ranzato
Convolution v.s. Fully Connected
1 0 0 0 0 1 1 -1 -1 -1 1 -1
0 1 0 0 1 0 -1 1 -1 -1 1 -1
0 0 1 1 0 0 -1 -1 1 -1 1 -1
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0
convolution
image

x1
1 0 0 0 0 1
0 1 0 0 1 0 x2
Fully- 0 0 1 1 0 0
1 0 0 0 1 0
connected



0 1 0 0 1 0
0 0 1 0 1 0
x36
1 -1 -1 Filter 1 1 1
-1 1 -1 2 0
-1 -1 1 3 0
4: 0 3


1 0 0 0 0 1
0 1 0 0 1 0 0
0 0 1 1 0 0 8 1
1 0 0 0 1 0 9 0
0 1 0 0 1 0 10: 0


0 0 1 0 1 0
1 0
6 x 6 image
3 0
14
fewer parameters! 15 1 Only connect to 9
16 1 inputs, not fully
connected

1 -1 -1 1: 1
-1 1 -1 Filter 1 2: 0
-1 -1 1 3: 0
4: 0 3


1 0 0 0 0 1
0 1 0 0 1 0 7: 0
0 0 1 1 0 0 8: 1
1 0 0 0 1 0 9: 0 -1
0 1 0 0 1 0 10: 0


0 0 1 0 1 0
1 0
6 x 6 image
3: 0
14:
Fewer parameters 15: 1
16: 1 Shared weights
Even fewer parameters

Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolutional neural network (CNN)
▪ Kiến trúc mạng cơ bản (LeNet5)

52
Convolutional neural network (CNN)

53
Neural networks for images

image
Neural networks for images
feature map

learned
weights

image
Neural networks for images
another feature map

another
set of
learned
weights

image
Convolution as feature extraction
bank of K filters K feature maps

.
.
.

image feature map


Convolutional layer

K feature maps

Spatial resolution:
K filters (roughly) the same if
stride of 1 is used,
reduced by 1/S if
stride of S is used

image convolutional layer


Convolutional layer
L feature
maps in the
K feature maps next layer

FxFxK
filter
L filters

convolutional layer
image + ReLU
Convolutional layer

http://cs231n.github.io/convolutional-networks/#conv
Max pooling layer
K feature maps,
K feature maps resolution 1/S

max
value

F x F pooling filter, Backward pass: gradient from next


stride S layer is passed back only to the unit
Usually: F=2 or 3, S=2 with max value
Neural networks for images

Fully connected layer


Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Summary: CNN pipeline
Feature maps

Spatial pooling

Non-linearity

Convolution .
(Learned) .
.

Input Image
Input Feature Map
Source: R. Fergus, Y. LeCun
Summary: CNN pipeline
Feature maps

Spatial pooling

Non-linearity

Convolution
(Learned)

Input Image

Source: Stanford 231n


Summary: CNN pipeline
Feature maps

Max
Spatial pooling (or Avg)

Non-linearity

Convolution
(Learned)

Input Image

Source: R. Fergus, Y. LeCun


Summary: CNN pipeline
Feature maps

Max
Spatial pooling (or Avg)

Non-linearity

Convolution
(Learned)

Input Image
Summary: CNN pipeline

Softmax layer:
exp(w c × x)
P(c | x) = C

å exp(w k × x)
k=1
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Mạng CNN

cat dog ……
Convolution

Pooling
Can
Fully Connected repeat
Feedforward network
Convolution many
times

Pooling

Flattened
Vai trò của Pooling

3 0
-1 1 Convolution

3 1
0 3
Pooling
A new image Can
repeat
Convolution many
Smaller than the original
times
image
The number of channels Pooling

is the number of filters


Mạng CNN

cat dog ……
Convolution

Pooling

Fully Connected A new image


Feedforward network
Convolution

Pooling

Flattened A new image


Vai trò của Flatten: 3

1
3 0
-1 1 3

3 1 -1
0 3 Flattened

1 Fully Connected
Feedforward network

3
Only modified the network structure and input
CNN in Keras format (vector -> 3-D tensor)

input

Convolution
1 -1 -1
-1 1 -1
-1 1 -1
-1 1 -1 … There are
25 3x3
-1 -1 1
-1 1 -1 … Max Pooling
filters.
Input_shape = ( 28 , 28 , 1)

28 x 28 pixels 1: black/white, 3: RGB Convolution

3 -1 3 Max Pooling

-3 1
Only modified the network structure and input
CNN in Keras format (vector -> 3-D array)

Input
1 x 28 x 28

Convolution
How many parameters for
each filter? 9 25 x 26 x 26

Max Pooling
25 x 13 x 13

Convolution
How many parameters 225=
for each filter? 50 x 11 x 11
25x9
Max Pooling
50 x 5 x 5
Only modified the network structure and input
CNN in Keras format (vector -> 3-D array)

Input
1 x 28 x 28

Output Convolution

25 x 26 x 26
Fully connected Max Pooling
feedforward network
25 x 13 x 13

Convolution
50 x 11 x 11

Max Pooling
1250 50 x 5 x 5
Flattened
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Demo: DL (1)
▪ Trên Google Colab

lenet.ipynb
from d2l import tensorflow as d2l
import tensorflow as tf

def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='sigmoid'
,
padding='same'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Conv2D(filters=16, kernel_size=5,
activation='sigmoid'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120, activation='sigmoid'),
tf.keras.layers.Dense(84, activation='sigmoid'),
tf.keras.layers.Dense(10)])
from d2l import tensorflow as d2l
import tensorflow as tf

def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='sigmoid',
padding='same'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Conv2D(filters=16, kernel_size=5,
activation='sigmoid'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120, activation='sigmoid'),
tf.keras.layers.Dense(84, activation='sigmoid'),
tf.keras.layers.Dense(10)])
Fully Connected
Feedforward network
▪ CNN: Đầu vào của Fully connected là các feature maps
cuối. Số lượng input nodes phụ thuộc vào số lượng filter:
1x5x5x16=400 units
(và size của ảnh sau pooling cuối cùng)

▪ Với MLP: đầu vào của Fully connected là raw data.


Nếu ảnh 1x28x28 cần 784 units
Demo: DL (2)
▪ Trên Google Colab

alexnet.ipynb
alexnet

def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=96, kernel_size=11, strides=4,
activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
tf.keras.layers.Conv2D(filters=256, kernel_size=5, padding='same',
activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
tf.keras.layers.Conv2D(filters=384, kernel_size=3, padding='same',
activation='relu'),
tf.keras.layers.Conv2D(filters=384, kernel_size=3, padding='same',
activation='relu'),
tf.keras.layers.Conv2D(filters=256, kernel_size=3, padding='same',
activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
# Output layer. Since we are using Fashion-MNIST, the number of
# classes is 10, instead of 1000 as in the paper
tf.keras.layers.Dense(10)
])
vgg Demo: DL (3)
from d2l import tensorflow as d2l
import tensorflow as tf

def vgg_block(num_convs, num_channels):


blk = tf.keras.models.Sequential()
for _ in range(num_convs):
blk.add(tf.keras.layers.Conv2D(num_chan
nels,kernel_size=3,
padding='sa
me',activation='relu'))
blk.add(tf.keras.layers.MaxPool2D(pool_size
=2, strides=2))
return blk

def vgg(conv_arch):
net = tf.keras.models.Sequential()
# The convulational part
for (num_convs, num_channels) in conv_arch:
net.add(vgg_block(num_convs, num_channels))
# The fully-connected part
net.add(tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10)]))
return net
net = vgg(conv_arch)
Convolution
2D Convolution
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 13 :
Convolutional Neural Networks (CNN)

Van-Truong Pham, PhD


School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolution
▪ Biểu thức toán của convolution:

▪ Dạng rời rạc (discrete):

4
2D Convolution
▪ Tích chập hai chiều

5
2D Convolution
▪ Tích chập hai chiều

6
2D Convolution
▪ Tích chập hai chiều

7
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Kernel
▪ The thing we convolve by is called a kernel, or filter
▪ What does this convolution kernel do?
Kernel

▪ What does this convolution kernel do?


Kernel

▪ What does this convolution kernel do?


Kernel

▪ What does this convolution kernel do?


Filters
▪ Mỗi convolutional layer gồm nhiều filter, dùng để thực
hiện phép tính tích chập

Beak detector

A filter
Filters
▪ Mỗi kernel cho ta một image filter khác nhau
Filters
Đây là các tham số học của mạng

1 -1 -1
1 0 0 0 0 1 -1 1 -1 Filter 1
0 1 0 0 1 0 -1 -1 1
0 0 1 1 0 0
1 0 0 0 1 0 -1 1 -1
-1 1 -1 Filter 2
0 1 0 0 1 0
0 0 1 0 1 0 -1 1 -1



6 x 6 image
Mỗi filter dò một miền nhỏ
(ví dụ kích thước 3 x 3).
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1 Dot
product
0 1 0 0 1 0 3
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1 Dot
product
0 1 0 0 1 0 3 -1
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1 Dot
product
0 1 0 0 1 0 3 -1 -3
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
If stride=2

1 0 0 0 0 1
0 1 0 0 1 0 3 -3
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
1 -1 -1
-1 1 -1 Filter 1
-1 -1 1
If stride=2

1 0 0 0 0 1
0 1 0 0 1 0 3 -3 -2
0 0 1 1 0 0
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0

6 x 6 image
-1 1 -1
-1 1 -1 Filter 2
-1 1 -1
stride=1
Lặp lại cho mỗi filter
1 0 0 0 0 1
0 1 0 0 1 0 3 -1 -3 -1
-1 -1 -1 -1
0 0 1 1 0 0
1 0 0 0 1 0 -3 1 0 -3
-1 -1 -2 1
0 1 0 0 1 0 Feature
0 0 1 0 1 0 -3 -3 Map0 1
-1 -1 -2 1

6 x 6 image 3 -2 -2 -1
-1 0 -4 3

Hai ảnh có kích cỡ 4x4


Tạo ma trận 2 x 4 x 4
For RGB image

11 -1-1 -1-1 -1-1 11 -1-1


1 -1 -1 -1 1 -1
-1 1 -1 -1-1 11 -1-1
-1-1 11 -1-1 Filter 1 -1 1 -1 Filter 2
-1-1 -1-1 11 -1-1-1 111 -1-1-1
-1 -1 1
Color image
1 0 0 0 0 1
1 0 0 0 0 1
0 11 00 00 01 00 1
0 1 0 0 1 0
0 00 11 01 00 10 0
0 0 1 1 0 0
1 00 00 10 11 00 0
1 0 0 0 1 0
0 11 00 00 01 10 0
0 1 0 0 1 0
0 00 11 00 01 10 0
0 0 1 0 1 0
0 0 1 0 1 0
For RGB image
For RGB image
For RGB image
For RGB image
For RGB image
Padding
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
▪ Ta đã có đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

• Convoution with Filter 1 1 -1 -1


-1 1 -1 Filter 1
-1 -1 1
stride=1

1 0 0 0 0 1
0 1 0 0 1 0 3 -1 -3 -1
0 0 1 1 0 0
1 0 0 0 1 0 -3 1 0 -3
0 1 0 0 1 0
0 0 1 0 1 0 -3 -3 0 1

6 x 6 image 3 -2 -2 -1
▪ Ta đã có đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

• Convoution with Filter 2


-1 1 -1
-1 1 -1 Filter 2
stride=1 -1 1 -1

1 0 0 0 0 1
0 1 0 0 1 0 3 -1 -3 -1
-1 -1 -1 -1
0 0 1 1 0 0
1 0 0 0 1 0 -3 1 0 -3
-1 -1 -2 1
0 1 0 0 1 0
0 0 1 0 1 0 -3 -3 0 1
-1 -1 -2 1

6 x 6 image 3 -2 -2 -1
-1 0 -4 3
▪ Ta đã có đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

3 -1 -3 -1
-1 -1 -1 -1
-3 1 0 -3
-1 -1 -2 1

1 0 0 0 0 1 -3 -3 0 1
-1 -1 -2 1
0 1 0 0 1 0 Conv
3 -2 -2 -1
0 0 1 1 0 0 -1 0 -4 3
1 0 0 0 1 0
0 1 0 0 1 0 Max
0 0 1 0 1 0 Pooling

6 x 6 image
Pooling

33
Max Pooling
▪ Thực hiện Pooling với đầu ra của lớp conv (với 2 filters) đã thực hiện trước đó

1 -1 -1 -1 1 -1
-1 1 -1 Filter 1 -1 1 -1 Filter 2
-1 -1 1 -1 1 -1

3 -1 -3 -1 -1 -1 -1 -1

-3 1 0 -3 -1 -1 -2 1

-3 -3 0 1 -1 -1 -2 1

3 -2 -2 -1 -1 0 -4 3
Why Pooling?
▪ Giảm chiều không thay đổi đối tượng trong ảnh

bird
bird

Subsampling

Giúp kích cỡ ảnh giảm đi

fewer parameters to characterize the image


Max Pooling

New image
1 0 0 0 0 1 but smaller
0 1 0 0 1 0 Conv
3 0
0 0 1 1 0 0 -1 1
1 0 0 0 1 0
0 1 0 0 1 0 Max 3 1
0 3
0 0 1 0 1 0 Pooling
2 x 2 image
6 x 6 image
Each filter
is a channel
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolutional networks
▪ Convolutional networks have two kinds of layers:
detection layers (or convolution layers), and pooling layers

▪ Convolution layer has a set of filters. Its output is a set of feature


maps, each one obtained by convolving the image with a filter
Convolutional networks
▪ It’s common to apply a linear rectification nonlinearity:
yi=max(zi,0)

▪ Why?
• Convolution is a linear operation. Therefore, we need a nonlinearity, otherwise
2 convolution layers would be no more powerful than 1
• Two edges in opposite directions shouldn’t cancel
• Makes the gradients sparse, which helps optimization.
Convolutional networks

▪ Why pooling?
Convolutional networks
• Because of pooling, higher-layer filters can cover a larger region of the input
than equal-sized filters in the lower layers
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolution v.s. Fully Connected
▪ Tương tác giữa các nút thưa (sparse) so với lớp kết nối đầy đủ
(Fully connected layer)

Còn gọi là
Fully connected
43
Fully Connected Layer
Example: 200x200 image
40K hidden units
~2B parameters!!!

- Spatial correlation is local


- Waste of resources + we have not enough
training samples anyway.. 44
Slide Credit: Marc'Aurelio Ranzato
Locally Connected Layer

Example: 200x200 image


40K hidden units
Filter size: 10x10
4M parameters

Note: This parameterization is good when


input image is registered (e.g., face
recognition). 45
Slide Credit: Marc'Aurelio Ranzato
Locally Connected Layer
STATIONARITY? Statistics is similar at
different locations

Example: 200x200 image


40K hidden units
Filter size: 10x10
4M parameters

Note: This parameterization is good when


input image is registered (e.g., face
recognition). 46
Slide Credit: Marc'Aurelio Ranzato
Convolutional Layer

Share the same parameters across different


locations (assuming input is stationary):
Convolutions with learned kernels

47
Slide Credit: Marc'Aurelio Ranzato
Convolution v.s. Fully Connected
1 0 0 0 0 1 1 -1 -1 -1 1 -1
0 1 0 0 1 0 -1 1 -1 -1 1 -1
0 0 1 1 0 0 -1 -1 1 -1 1 -1
1 0 0 0 1 0
0 1 0 0 1 0
0 0 1 0 1 0
convolution
image

x1
1 0 0 0 0 1
0 1 0 0 1 0 x2
Fully- 0 0 1 1 0 0
1 0 0 0 1 0
connected



0 1 0 0 1 0
0 0 1 0 1 0
x36
1 -1 -1 Filter 1 1 1
-1 1 -1 2 0
-1 -1 1 3 0
4: 0 3


1 0 0 0 0 1
0 1 0 0 1 0 0
0 0 1 1 0 0 8 1
1 0 0 0 1 0 9 0
0 1 0 0 1 0 10: 0


0 0 1 0 1 0
1 0
6 x 6 image
3 0
14
fewer parameters! 15 1 Only connect to 9
16 1 inputs, not fully
connected

1 -1 -1 1: 1
-1 1 -1 Filter 1 2: 0
-1 -1 1 3: 0
4: 0 3


1 0 0 0 0 1
0 1 0 0 1 0 7: 0
0 0 1 1 0 0 8: 1
1 0 0 0 1 0 9: 0 -1
0 1 0 0 1 0 10: 0


0 0 1 0 1 0
1 0
6 x 6 image
3: 0
14:
Fewer parameters 15: 1
16: 1 Shared weights
Even fewer parameters

Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Convolutional neural network (CNN)
▪ Kiến trúc mạng cơ bản (LeNet5)

52
Convolutional neural network (CNN)

53
Neural networks for images

image
Neural networks for images
feature map

learned
weights

image
Neural networks for images
another feature map

another
set of
learned
weights

image
Convolution as feature extraction
bank of K filters K feature maps

.
.
.

image feature map


Convolutional layer

K feature maps

Spatial resolution:
K filters (roughly) the same if
stride of 1 is used,
reduced by 1/S if
stride of S is used

image convolutional layer


Convolutional layer
L feature
maps in the
K feature maps next layer

FxFxK
filter
L filters

convolutional layer
image + ReLU
Convolutional layer

http://cs231n.github.io/convolutional-networks/#conv
Max pooling layer
K feature maps,
K feature maps resolution 1/S

max
value

F x F pooling filter, Backward pass: gradient from next


stride S layer is passed back only to the unit
Usually: F=2 or 3, S=2 with max value
Neural networks for images

Fully connected layer


Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Summary: CNN pipeline
Feature maps

Spatial pooling

Non-linearity

Convolution .
(Learned) .
.

Input Image
Input Feature Map
Source: R. Fergus, Y. LeCun
Summary: CNN pipeline
Feature maps

Spatial pooling

Non-linearity

Convolution
(Learned)

Input Image

Source: Stanford 231n


Summary: CNN pipeline
Feature maps

Max
Spatial pooling (or Avg)

Non-linearity

Convolution
(Learned)

Input Image

Source: R. Fergus, Y. LeCun


Summary: CNN pipeline
Feature maps

Max
Spatial pooling (or Avg)

Non-linearity

Convolution
(Learned)

Input Image
Summary: CNN pipeline

Softmax layer:
exp(w c × x)
P(c | x) = C

å exp(w k × x)
k=1
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Mạng CNN

cat dog ……
Convolution

Pooling
Can
Fully Connected repeat
Feedforward network
Convolution many
times

Pooling

Flattened
Vai trò của Pooling

3 0
-1 1 Convolution

3 1
0 3
Pooling
A new image Can
repeat
Convolution many
Smaller than the original
times
image
The number of channels Pooling

is the number of filters


Mạng CNN

cat dog ……
Convolution

Pooling

Fully Connected A new image


Feedforward network
Convolution

Pooling

Flattened A new image


Vai trò của Flatten: 3

1
3 0
-1 1 3

3 1 -1
0 3 Flattened

1 Fully Connected
Feedforward network

3
Only modified the network structure and input
CNN in Keras format (vector -> 3-D tensor)

input

Convolution
1 -1 -1
-1 1 -1
-1 1 -1
-1 1 -1 … There are
25 3x3
-1 -1 1
-1 1 -1 … Max Pooling
filters.
Input_shape = ( 28 , 28 , 1)

28 x 28 pixels 1: black/white, 3: RGB Convolution

3 -1 3 Max Pooling

-3 1
Only modified the network structure and input
CNN in Keras format (vector -> 3-D array)

Input
1 x 28 x 28

Convolution
How many parameters for
each filter? 9 25 x 26 x 26

Max Pooling
25 x 13 x 13

Convolution
How many parameters 225=
for each filter? 50 x 11 x 11
25x9
Max Pooling
50 x 5 x 5
Only modified the network structure and input
CNN in Keras format (vector -> 3-D array)

Input
1 x 28 x 28

Output Convolution

25 x 26 x 26
Fully connected Max Pooling
feedforward network
25 x 13 x 13

Convolution
50 x 11 x 11

Max Pooling
1250 50 x 5 x 5
Flattened
Contents

▪ Convolution
▪ Kernel
▪ Pooling
▪ Convolutional networks
▪ Convolution vs. Fully connected (FC)
▪ Convolutional neural network (CNN)
▪ CNN pipeline
▪ FC layers
▪ Python demo
Demo: DL (1)
▪ Trên Google Colab

lenet.ipynb
from d2l import tensorflow as d2l
import tensorflow as tf

def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='sigmoid'
,
padding='same'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Conv2D(filters=16, kernel_size=5,
activation='sigmoid'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120, activation='sigmoid'),
tf.keras.layers.Dense(84, activation='sigmoid'),
tf.keras.layers.Dense(10)])
from d2l import tensorflow as d2l
import tensorflow as tf

def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='sigmoid',
padding='same'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Conv2D(filters=16, kernel_size=5,
activation='sigmoid'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120, activation='sigmoid'),
tf.keras.layers.Dense(84, activation='sigmoid'),
tf.keras.layers.Dense(10)])
Fully Connected
Feedforward network
▪ CNN: Đầu vào của Fully connected là các feature maps
cuối. Số lượng input nodes phụ thuộc vào số lượng filter:
1x5x5x16=400 units
(và size của ảnh sau pooling cuối cùng)

▪ Với MLP: đầu vào của Fully connected là raw data.


Nếu ảnh 1x28x28 cần 784 units
Demo: DL (2)
▪ Trên Google Colab

alexnet.ipynb
alexnet

def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=96, kernel_size=11, strides=4,
activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
tf.keras.layers.Conv2D(filters=256, kernel_size=5, padding='same',
activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
tf.keras.layers.Conv2D(filters=384, kernel_size=3, padding='same',
activation='relu'),
tf.keras.layers.Conv2D(filters=384, kernel_size=3, padding='same',
activation='relu'),
tf.keras.layers.Conv2D(filters=256, kernel_size=3, padding='same',
activation='relu'),
tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
# Output layer. Since we are using Fashion-MNIST, the number of
# classes is 10, instead of 1000 as in the paper
tf.keras.layers.Dense(10)
])
vgg Demo: DL (3)
from d2l import tensorflow as d2l
import tensorflow as tf

def vgg_block(num_convs, num_channels):


blk = tf.keras.models.Sequential()
for _ in range(num_convs):
blk.add(tf.keras.layers.Conv2D(num_chan
nels,kernel_size=3,
padding='sa
me',activation='relu'))
blk.add(tf.keras.layers.MaxPool2D(pool_size
=2, strides=2))
return blk

def vgg(conv_arch):
net = tf.keras.models.Sequential()
# The convulational part
for (num_convs, num_channels) in conv_arch:
net.add(vgg_block(num_convs, num_channels))
# The fully-connected part
net.add(tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10)]))
return net
net = vgg(conv_arch)
Convolution
2D Convolution
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 14 :
DL for computer vision
Image Classification
Van-Truong Pham, PhD
School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
Recurrent
Neural Net
Boosting
Convolutional
Neural Net

Neural Net Perceptron


SVM

Deep Autoencoder
(sparse/denoising) Neural Net
Autoencoder Sparse Coding
SP GMM
Deep Belief Net Restricted BM

BayesNP Disclaimer: showing only a subset


4
of the known methods
Slide Credit: Marc'Aurelio Ranzato, Yann LeCun
SHALLOW
Recurrent
Neural Net
Boosting
Convolutional
Neural Net

Neural Net Perceptron


SVM

Deep Autoencoder
(sparse/denoising) Neural Net
Autoencoder Sparse Coding
SP GMM
Deep Belief Net Restricted BM
DEEP

BayesNP
5
Slide Credit: Marc'Aurelio Ranzato, Yann LeCun
SHALLOW
Recurrent
Neural Net
Boosting
Convolutional
Neural Net

Neural Net Perceptron


SVM
SUPERVISED
Deep UNSUPERVISED
Autoencoder
(sparse/denoising) Neural Net
Autoencoder Sparse Coding
SP GMM
Deep Belief Net Restricted BM
DEEP

BayesNP
6
Slide Credit: Marc'Aurelio Ranzato, Yann LeCun
SHALLOW
Recurrent
Neural Net
Boosting
Convolutional
Neural Net

Neural Net Perceptron


SVM
SUPERVISED
Deep UNSUPERVISED
Autoencoder
(sparse/denoising) Neural Net
Autoencoder Sparse Coding
SP
PROBABILISTIC GMM
Deep Belief Net Restricted BM
DEEP

BayesNP
7
Slide Credit: Marc'Aurelio Ranzato, Yann LeCun
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
“Shallow” vs Deep Learning
• “Shallow” models

hand-crafted “Simple” Trainable


Feature Extractor Classifier
fixed learned

• Deep models
Trainable Trainable Trainable
Feature- Feature- Feature-
Transform / Transform / Transform /
Classifier Classifier Classifier

Learned Internal Representations


Slide Credit: Marc'Aurelio Ranzato, Yann LeCun
Feature Engineering (traditional ML)

SIFT

SIFT (Scale Invariant Feature Transform) Local Binary Patterns

Histogram of Oriented Gradients


10
Feature Extractor
Feature Engineering (traditional ML)
▪ Ví dụ hệ thống OM classification/diagnosis
(Nhận dạng và hỗ trợ chẩn đoán viêm tai giữa OM (otitis media))
• Viêm tai giữa là bệnh thường gặp, 70% ở trẻ em dưới 2 tuổi
• OM làm cho trẻ quấy khóc, biếng ăn, ảnh hưởng thính lực, sức khỏe. Đồng
thời ảnh hưởng công việc và thời gian của cha mẹ
❑ Phân loại OM
▪ Chronic otitis media (COM) (viêm mãn tính) :
- Perforation of tympanic membrane (thủng màng nhĩ)
- Cholesteatoma (mãn tính nguy hiểm)

▪ Acute otitis media (AOM) (viêm cấp tính):


- Upper respiratory infection (suy hô hấp cấp)
- Pus in the middle ear (chảy mủ tai giữa)

▪ Otitis media with effusion (OME) (viêm tiết dịch):


- Non-infected fluid in the middle ear (chất lỏng tích tụ bên trong)
-Inhibiting vibration tympanic membrane (ức chế sự rung động của màng nhĩ)
Feature Engineering (traditional ML)
▪ OM classification/diagnosis

OM Data

Feature extraction

HSV HOG LBP SSIM

Multiple Features Sparse Reconstruction

Sparse Sparse Sparse Sparse


coefficients coefficients coefficients coefficients

Multiple Feature
Combination
Reconstruction
Error

OM Classifier

Ref: Thi-Thao Tran, Te-Yung Fang, Van-Truong Pham, Chen Lin, Pa-Chun Wang, Men-Tzung Lo, "Development
of an Automatic Diagnostic Algorithm for Pediatric Otitis Media," Otology & Neurotology, vol 39 (8), 2018.
Feature Engineering (traditional ML)
• Traditional pattern recognition models use hand-crafted
features and relatively simple trainable classifier.

hand-crafted “Simple”
feature Trainable output
extractor Classifier

• This approach has the following limitations:


• It is very tedious and costly to develop hand-crafted
features
• The hand-crafted features are usually highly dependents
on one application, and cannot be transferred easily to
other applications.
Deep Learning
• Deep learning (a.k.a. representation learning) seeks to learn
rich hierarchical representations (i.e. features) automatically
through multiple stage of feature learning process.

Low-level Mid-level High-level Trainable


features features features classifier output

Feature visualization of convolutional net trained on ImageNet


(Zeiler and Fergus, 2013)
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
Deep learning
▪ Deep learning refers to a class of learning algorithms
▪ They are based on the use of a specific kind of classifier: neural networks
▪ Deep = high number of hidden layers:
• Learn a larger number of parameters!
▪ It has been possible since we have:
• Access to big amounts of (training) data
• Increased computational capabilities (e.g., GPUs)
CNN example

• Convolutional layers, followed by nonlinear activation and subsampling


• Output of hidden layers (feature maps) = features learnt by the CNN
• Before classification, fully connected layers (as in “standard” NN)
Learning hierarchical representations

Low-level Mid-level High-level Trainable


output
features features features classifier

Increasing level of abstraction

• Hierarchy of representations with increasing level of abstraction.


Each stage is a kind of trainable nonlinear feature transform
• Image recognition
• Pixel → edge → texton → motif → part → object
• Text
• Character → word → word group → clause → sentence → story
Automatically learnt features

Retain most information (edge detectors)

Towards more abstract representation

Encode high level concepts

Sparser representations:
Detect less (more abstract) features

https://towardsdatascience.com/applied-deep-learning-part-4-
convolutional-neural-networks-584bc134c1e2
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
DL in computer vision

21
CNN-based Computer Vision

22
Image Classification

23
Object Localization

24
Object Detection

25
Object Detection

26
Image Segmentation

Deconv: deconvolutional layer

(transposed convolutional layer).


27
Image Segmentation

28
Image detection vs. segmentation
Object Detection/Localization Segmentation

29
Image Captioning

30
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
Image classification
• It is a specific area of machine learning
• Supervised learning
• Unsupervised learning
• Reinforcement learning
• Idea (supervised learning): learn how to make decisions,
perform a task, from examples

dog cat dog or cat?


Traditional classification

➢ How to extract information from the raw data?


Classification with deep learning

➢ End-to-end learning
• Can be directly applied to the raw signal,
without computing first ad hoc features
• Features are learnt automatically, by convolutional neural networks
Ad hoc là một cụm từ tiếng Latin có nghĩa đen là "cho điều này / vì điều này". Nó thường biểu thị một giải pháp
được thiết kế cho một vấn đề hoặc nhiệm vụ cụ thể, không khái quát hóa và không nhằm mục đích có thể thích
nghi với các mục đích khác (so sánh với một tiên nghiệm).
Successful biomedical application

• Diabetic retinopathy detection


• Tumor detection from MRI, CT, X-
rays, etc
• Skin lesion classification from clinical
and dermoscopic images
• Heart sound classification: normal
vs. abnormal, murmur classification
• Parkinson’s disease detection from
voice recording.
• Otitis media
• Myocardial infarction analysis
• Snore sound analysis.
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
CNN success story: ILSVRC 2012
▪ ImageNet database: 14 triệu ảnh được dán nhãn, 20 ngàn loại
ILSVRC 2012: top rankers

N Error-5 Algorithm Team Authors


1 0.153 Deep Conv. Neural Network Univ. of Toronto Krizhevsky et al
2 0.262 Features + Fisher Vectors + ISI Gunji et al
Linear classifier
3 0.270 Features + FV + SVM OXFORD_VGG Simonyan et al
4 0.271 SIFT + FV + PQ + SVM XRCE/INRIA Perronin et al
5 0.300 Color desc. + SVM Univ. of van de Sande et al
Amsterdam

http://www.image-net.org/challenges/LSVRC/2012/results.html
ILSVRC 2013: top rankers

N Error-5 Algorithm Team Authors


1 0.117 Deep Convolutional Neural Clarifi Zeiler
Network
2 0.129 Deep Convolutional Neural Nat.Univ Min LIN
Networks Singapore
3 0.135 Deep Convolutional Neural NYU Zeiler
Networks Fergus
4 0.135 Deep Convolutional Neural Andrew Howard
Networks
5 0.137 Deep Convolutional Neural Overfeat Pierre Sermanet et al
Networks NYU

http://www.image-net.org/challenges/LSVRC/2013/results.php

ConvNet
ImageNet Classifications 2013
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
AlexNet

• Winner of ILSVRC 2012


• Marked the beginning of recent deep learning revolution

A. Krizhevsky, I. Sutskever, and G. Hinton. "ImageNet


Classification with Deep Convolutional Neural." In NIPS, pp. 1-9.
2014.
VGG-16

• Very small filters (3x3)


• Deeper than AlexNet:16 layers
K. Simonyan and A. Zisserman, “Very deep convolutional
networks for large-scale image recognition,” in Proc. Int.
Conf. Learn. Representations, 2015.
Revolution of Depth

The deeper the better!


44
Revolution of Depth
❑ Mạng ResNet [He et.al, 2015]: 152 layers
▪ Xuất phát từ vấn đề vanishing gradient
• Quá trình huấn luyện phụ thuộc vào
backpropagation. Do vậy giá trị gradient giảm
dần ở mỗi gate

→Rất khó để có thể huấn luyện nhiều hơn 10 lớp

▪ Giải pháp giúp tránh được vấn đề


vanishing gradient:

Residual NN

45
K. He, X. Zhang, S. Ren, and J. Sun, Deep Residual Learning for Image Recognition, CVPR 2016 (Best Paper)
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
ResNet

From: https://www.codeproject.com/Articles/1248963/Deep-Learning-using-Python-plus-Keras-Chapter-Re

• Increase the number of layers by introducing a residual


connection
• Blocks are actually learning residual functions: easier!

K. He, X. Zhang, S. Ren, and J. Sun. "Deep residual learning for


image recognition." In Proceedings of the IEEE conference on
computer vision and pattern recognition, pp. 770-778. 2016.
ResNet

A building block
ResNet
➢ Thuật toán
- Gọi x và y lần lượt là đầu vào và đầu ra của layer, 𝐻(𝑥) là đầu ra mong
muốn và 𝐹(𝑥) là đầu ra ban đầu khi chưa có shortcut. Ta có:
𝑦 =𝐹 𝑥 +𝑥
𝐹 𝑥 = 𝑊2 𝜎(𝑊1 𝑥)

- Do đó để 𝑦 = 𝐻 𝑥 , layer cần xấp xỉ hàm 𝐹 𝑥 = 𝐻 𝑥 − 𝑥. Điều này được


tác giả dự đoán là dễ thực hiện hơn so với việc xấp xỉ trực tiếp hàm 𝐻(𝑥)
khi không sử dụng shortcut. Nhất là khi 𝐻(𝑥) là identity mapping, 𝐹 𝑥 = 0
nên thuật toán huấn luyện chỉ cần đưa các trọng số của layer về 0.

⇒ Shortcut giúp việc huấn luyện các mạng sâu trở nên dễ dàng hơn mà
không làm tăng số lượng tham số của mạng
ResNet
➢ Cấu trúc mạng
ResNet
ResNet variant: DenseNets
▪ Motivation:
ResNets: hàm nhận dạng và đầu ra được kết hợp bằng phép tính tổng,
điều này có thể cản trở luồng thông tin trong mạng.

• Dense connectivity.
Để cải thiện hơn nữa luồng thông tin giữa các lớp: các kết nối trực
tiếp từ bất kỳ lớp nào đến tất cả các lớp tiếp theo.

• Mạng DenseNet là một bước phát triển tiếp theo của DL trong
Computer vision. Kiến trúc DenseNet gần giống ResNet nhưng có
một vài điểm khác biệt. DenseNet gồm các khối Dense-block và
transition layer.

52
DenseNets
• DenseNet gồm các khối Dense-block và transition layer.

G. Huang, Z. Liu, and L. van der Maaten, Densely Connected Convolutional Networks, CVPR 2017
(Best Paper Award)
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
Transfer learning
Transfer learning
▪ Sử dụng các kiến trúc đã được huấn luyện sẵn, áp dụng cho bài toán mới
▪ Kỹ thuật học truyền tải (transfer learning), mang kiến thức đã học
được từ tập dữ liệu gốc áp dụng sang tập dữ liệu mục tiêu.
▪ Tinh chỉnh (fine tuning): kỹ thuật thông dụng trong học truyền tải
Ví dụ: Các đặc tính đã được học từ 1.5 triệu bức ảnh trong tập dữ liệu ImageNet có rất
nhiều thông tin về bối cảnh và ngữ nghĩa (contextual & sematic information)

56
Fine tuning
▪ Tiền huấn luyện một mô hình mạng nơ‐ron, tức là mô hình
gốc, trên tập dữ liệu gốc (chẳng hạn tập dữ liệu
ImageNet).
▪ Tạo mô hình mạng nơ‐ron mới gọi là mô hình mục tiêu:
sao chép tất cả các thiết kế cũng như các tham số của mô
hình gốc, ngoại trừ tầng đầu ra.

▪ Thêm vào một tầng đầu ra cho mô hình mục tiêu mà kích
thước của nó là số lớp của dữ liệu mục tiêu, và khởi tạo
ngẫu nhiên các tham số mô hình của tầng này.

▪ Huấn luyện mô hình mục tiêu trên tập dữ liệu mục


tiêu.Chúng ta sẽ huấn luyện tầng đầu ra từ đầu, trong khi
các tham số của tất cả các tầng còn lại được tinh chỉnh từ
các tham số của mô hình gốc.
Fine tuning
Contents
▪ Introduction
▪ “Shallow” vs Deep Learning
▪ Deep learning
▪ DL in computer visions
▪ Image classification
▪ CNN success story
▪ Some CNN variants
▪ ResNet
▪ Transfer learning
▪ Python demo
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 15 :
Detection & Segmentation

Van-Truong Pham, PhD


School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
CNN review
▪ Convolutional Neural Networks (CNN)

✓ Convolutional networks make the assumption of locality, and


hence are more powerful
✓ The fewer number of connections and weights make convolutional
layers relatively cheap (vs full connect) in terms of memory and
compute power needed.
3
https://www.mathworks.com/videos/introduction-to-deep-learning-what-are-convolutional-neural-networks--1489512765771.html
https://leonardoaraujosantos.gitbooks.io/artificial-inteligence/content/convolutional_neural_networks.html
CNN review
• Convolution Layer

➢ Padding = 0
➢ Strides = 1 W - Input volume size
Output Size = (5−3+2∗0)/1+1 = 3 F – Receptive field size (Filter Size)
kernel P - Zero padding used on the border
0 1 2
2 2 0 S - Stride
0 1 2
Output Size = (W−F+2P)/S+1

4
http://deeplearning.net/software/theano/tutorial/conv_arithmetic.html
https://sites.google.com/site/nttrungmtwiki/home/it/data-science---python/tensorflow/tensorflow-and-deep-learning-part-3?tmpl=%2Fsystem%2Fapp%2Ftemplates%2Fprint%2F&showPrintDialog=1
CNN review
▪ The use of convolutional networks is on classification tasks
where the output to typical image is a single class label.

▪ In many visual tasks, especially in biomedical image


processing, the desired output should include localization

A class label is supposed to be assigned to each pixel.


5
https://www.saagie.com/blog/object-detection-part1
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks
Computer vision tasks

Credit: cs231n
Computer vision tasks
Computer vision tasks
Computer vision tasks
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
Image Segmentation
• Objective: partition an image/signal in multiple
segments, sets of pixels/samples
• Similar to classification, but a label is assigned to each
pixel of the image
• Used for understanding and interpretation:
• Highlight region of interest
• Compute volume
• Surgery planning
Image Segmentation

22
DL-based Image Segmentation
▪ Cấu trúc chung : gồm encoder và decoder

➢ Encoder: dùng để giảm kích thước của ảnh bằng việc sử dụng các
lớp convolutions và các lớp poolings
Thường chỉ là một mạng CNN thông thường nhưng bỏ đi những fully
connected layers cuối cùng. Ta có thể dùng những mạng có sẵn trong
phần encoder như VGG16, VGG19, …

➢ Decoder: dùng để phục hồi lại kích thước ban đầu của ảnh, được xây
dựng tùy vào các kiến trúc mạng

▪ Mạng điển hình: FCN (Fully convolutional network) và U-Net


Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
Fully Convolutional Network (FCN)

➢ Goal: to predict class at every pixel

➢ Transfer existing classification models to dense prediction tasks


Jonathan Long, Evan Shelhamer, Trevor Darrell,
“Fully Convolutional Networks for Semantic Segmentation”, CVPR 2015.
FCN motivation

a classification network

“tabby
cat”
FCN motivation

becoming fully convolutional

Slide credit: Jonathan Long


FCN motivation

becoming fully convolutional


FCN motivation

upsampling output

Slide credit: Jonathan Long


FCN
FCN: end-to-end, pixels-to-pixels network

upsampling
pixelwise
conv, pool,
output + loss
nonlinearity

Slide credit: Jonathan Long


FCN
❑ Skip layers

interp + sum

interp + sum
end-to-end, joint
learning
of semantics and
location
dense
output
FCN
❑ Skip layers
▪ Trong kiến trúc FCN, có ba cách để xây dựng phần decoder tạo thành ba loại FCN khác nhau
là FCN32, FCN16, FCN8.

➢ FCN32: sau khi đến lớp pooling cuối cùng (ví dụ lớp pooling thứ 5) ta chỉ cần
upsample về kích thước ban đầu
➢ FCN16: tại lớp pooling thứ 5 ta nhân 2 lần để được kích thước bằng với kích
thước của lớp pooling thứ 4, sau đó add hai lớp vào với nhau rồi upsample lên
bằng với kích thước ảnh ban đầu.
➢ FCN8: ta kết nối tới lớp pooling thứ 3 ->add với (pool5x2+pool 4)-> upsample
về kích thước ảnh ban đầu.
FCN
Results on subset of validation set of PASCAL VOC 2011

Fixed = only fine tuning in final layer


FCN

skip layer refinement

input image stride 32 stride 16 stride 8 ground truth

no skips 1 skip 2 skips


FCN variants
▪ U-Net

▪ Attention U-Net

▪ Seg-Net

▪ Nested U-Net

▪ DeepLab
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
U-net
▪ Trong kiến trúc mạng Unet ta xây dựng phần decoder gần như
đối xứng với encoder.
▪ Trong phần decoder ngoài việc upsample ta còn thực hiện kết nối
đối xứng với các layer phần encoder cho đến tận layer cuối cùng
Việc kết nối đối xứng với phần encoder sẽ giúp ta phục hồi lại
thông tin đã mất tại các lớp pooling

Input Output segmentation map


image

Encoder Decoder
U-net
▪ Adapted from Ronneberger et al. 2015: U-shape architecture

Skip
connection

Encoder Decoder
▪ Contracting part (encoder)
• Composes of convolutional and max-pooling layers
▪ Expanding part (decoder)
• Consists of upsampling and convolutional layers.
▪ Skip connection between Encoder and Decoder: fusing, retain information
U-net

Output
Input segmentation map
image (here 2 classes)
tile background and
foreground
Concatenation with
high-resolution features
from contracting
Output Size (second conv) path Create high-resolution
segmentation map
= (570 – 3 +2*0)/1 + 1 = 568
Increase the “What”
Reduce the “Where”
→ 568 x 568

W - Input volume size


Output Size (first conv) F – Receptive field size (Filter Size)
= (572 – 3 +2*0)/1 + 1 = 570 P - Zero padding used on the border
→ 570 x 570 S - Stride
Output Size = (W−F+2P)/S+1
http://deeplearning.net/software/theano/tutorial/conv_arithmetic.html
• A light version of Unet (8M), shorter than the original (31M), the last
layer not used
Example with image size: 480x480, output: 6 classess
double_conv(3,64) nn.Conv2d(64,n_class,1)

conv1 double_conv(128+64,64)
cat([x, conv1]

double_conv(64,128)
conv2 double_conv(128+256,128)
cat([x, conv2]
double_conv(128,256)
conv3 double_conv(256+512,256)
cat([x, conv3]
double_conv(256,512)

Not used
def double_conv(in, out):
return nn.Sequential(
nn.Conv2d(in_channels,out,3,padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(out,out,3,padding=1),
nn.ReLU(inplace=True)
)
def __init__(self, n_class):
super().__init__() self.upsample = nn.Upsample(scale_factor=2,
mode='bilinear', align_corners=True)
self.dconv_down1 = double_conv(3, 64)
self.dconv_down2 = double_conv(64, 128) self.dconv_up3 = double_conv(256 + 512, 256)
self.dconv_down3 = double_conv(128, 256) self.dconv_up2 = double_conv(128 + 256, 128)
self.dconv_down4 = double_conv(256, 512) self.dconv_up1 = double_conv(128 + 64, 64)
self.maxpool = nn.MaxPool2d(2) self.conv_last = nn.Conv2d(64, n_class, 1)

x = self.upsample(x)
def forward(self, x): x = torch.cat([x, conv3], dim=1)
conv1 = self.dconv_down1(x) x = self.dconv_up3(x)
x = self.maxpool(conv1) x = self.upsample(x)
conv2 = self.dconv_down2(x) x = torch.cat([x, conv2], dim=1)
x = self.maxpool(conv2) x = self.dconv_up2(x)
conv3 = self.dconv_down3(x) x = self.upsample(x)
x = self.maxpool(conv3) x = torch.cat([x, conv1], dim=1)
x = self.dconv_up1(x)
x = self.dconv_down4(x) out = self.conv_last(x)
return out
• A light version of Unet (8M), shorter than the original (31M), the last
layer not used
Example with image size: 480x480, output: 6 classess

Not used
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net and variants
▪ Object Detection
▪ RCNN and variants
▪ Python demo
Attention U-net
Attention U-net for Brain tumor segmentation

Input Ground Predictions


images truths Overlap
SegNet
Loss functions for image segmentation
▪ Binary Cross Entropy (BCE)
−1 n
LBCE =  ( yi log yˆi + (1 − yi ) log (1 − yˆi ) )
n i =1
y : ground truth
ŷ : prediction
▪ Dice loss
2 i yˆi yi
LDice = 1 − Dice = 1 −
 i
yi +  ˆ
y
i i

Recall: Sa: automatically segmented region


2Sam
Dice = = Sm: manually segmented region
( Sa + Sm ) Sam: intersection between the two

−2 i yˆi yi
▪ Dice loss (other form): LDice =
 i
yi +  i yˆi
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
Object Detection
Object Detection
▪ Object detection is the task of detecting instances of
objects of a certain class within an image or video.

▪ The state-of-the-art methods can be categorized into


two main types: one-stage methods and two stage-
methods.

• One-stage methods prioritize inference speed, and


example models include YOLO, SSD and RetinaNet.
• Two-stage methods prioritize detection accuracy, and
example models include Faster R-CNN, Mask R-CNN and
Cascade R-CNN.
Object Detection

51
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ R-CNN and variants
▪ Python demo
R-CNN
▪ The R-CNN detector first generates region proposals using an algorithm
such as Edge Boxes
▪ The proposal regions are cropped out of the image and resized. Then,
the CNN classifies the cropped and resized regions.
▪ Finally, the region proposal bounding boxes are refined by a support
vector machine (SVM) that is trained using CNN features.

➢ Training and inference (detection): very slow

Ref: Girshick, R., J. Donahue, T. Darrell, and J. Malik. "Rich Feature Hierarchies for Accurate
Object Detection and Semantic Segmentation." CVPR '14 Proceedings of the 2014 IEEE
Conference on Computer Vision and Pattern Recognition. Pages 580-587. 2014
Fast R-CNN
▪ As in the R-CNN detector , the Fast R-CNN detector also uses an
algorithm like Edge Boxes to generate region proposals
▪ Unlike the R-CNN detector, which crops and resizes region proposals, the
Fast R-CNN detector processes the entire image
▪ Whereas an R-CNN detector must classify each region, Fast R-CNN
pools CNN features corresponding to each region proposal
▪ Fast R-CNN is more efficient than R-CNN, because in the Fast R-CNN
detector, the computations for overlapping regions are shared.

Ref: Girshick, Ross. "Fast r-cnn." Proceedings of the IEEE International Conference on
Computer Vision. 2015
Faster R-CNN
▪ The Faster R-CNN detector adds a region proposal network (RPN) to
generate region proposals directly in the network instead of using an
external algorithm like Edge Boxes
▪ The RPN uses Anchor Boxes for Object Detection. Generating region
proposals in the network is faster and better tuned to your data.

Ref: Ren, Shaoqing, Kaiming He, Ross Girshick, and Jian Sun. "Faster R-CNN: Towards
Real-Time Object Detection with Region Proposal Networks." Advances in Neural
Information Processing Systems . Vol. 28, 2015.
R-CNN and variants
Object Detection
Object Detection
Contents

▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
More about object
detection
R-CNN
▪ Đầu tiên, các mô hình R‐CNN sẽ chọn một số vùng đề xuất từ ảnh (ví dụ, các
khung neo cũng là một phương pháp lựa chọn)
▪ Gán nhãn hạng mục và khung chứa (ví dụ, các giá trị độ dời) cho các vùng này.
▪ Tiếp đến, các mô hình này sử dụng CNN để thực hiện lượt truyền xuôi nhằm
trích xuất đặc trưng từ từng vùng đề xuất.
▪ Sau đó, ta sử dụng các đặc trưng của từng vùng được đề xuất để dự đoán hạng
mục và khung chứa.
R-CNN
R-CNN
R-CNN

Tìm kiếm chọn lọc trên ảnh đầu vào để lựa chọn các vùng đề xuất tiềm năng (Uijlings et
al.,2013). Các vùng đề xuất thông thường sẽ có nhiều tỷ lệ với hình dạng và kích thước
khác nhau. Hạng mục và khung chứa nhãn gốc sẽ được gán cho từng vùng đề xuất.
R-CNN

Sử dụng một mạng CNN đã qua tiền huấn luyện, ở dạng rút gọn, đặt trước tầng đầu ra. Mạng
này biến đổi từng vùng đề xuất thành các đầu vào có chiều phù hợp với mạng và thực hiện
các lượt truyền xuôi để trích xuất đặc trưng từ các vùng đề xuất tương ứng.
R-CNN

Các đặc trưng và nhãn hạng mục của từng vùng đề xuất được kết hợp thành
một mẫu để huấn luyện các máy vector hỗ trợ cho phép phân loại vật thể. Ở
đây, mỗi máy vector hỗ trợ được sử dụng để xác định một mẫu có thuộc về một
hạng mục nào đó hay không.
R-CNN

Các đặc trưng và khung chứa được gán nhãn của mỗi
vùng đề xuất được kết hợp thành một
mẫu để huấn luyện mô hình hồi quy tuyến tính, để phục
vụ dự đoán khung chứa nhãn gốc.
R-CNN

Mặc dù mô hình R‐CNN sử dụng các mạng CNN đã được tiền huấn luyện để trích
xuất các đặc trưng ảnh một cách hiệu quả, điểm hạn chế chính yếu đó là tốc độ
chậm. Với hàng ngàn vùng đề xuất từ một ảnh, ta cần tới hàng ngàn phép tính
truyền xuôi từ mạng CNN để phát hiện vật thể. Khối lượng tính toán nặng nề khiến
các mô hình R‐CNN không được sử dụng rộng rãi trong các ứng dụng thực tế.
Fast R-CNN
▪ Hạn chế của R‐CNN đó là việc trích xuất đặc trưng cho từng vùng đề xuất một
cách độc lập. Do các vùng đề xuất này có độ chồng lặp cao, việc trích xuất đặc
trưng một cách độc lập sẽ dẫn đến một số lượng lớn các phép tính lặp lại.

▪ Fast R‐CNN cải thiện R‐CNN bằng cách chỉ thực hiện lượt truyền xuôi qua mạng
CNN trên toàn bộ ảnh.
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Fast R-CNN
Faster R-CNN
▪ Để có kết quả phát hiện đối tượng chính xác, Fast R‐CNN thường đòi hỏi
tạo ra nhiều vùng đề xuất khi tìm kiếm chọn lọc.

▪ Faster R‐CNN thay thế tìm kiếm chọn lọc bằng mạng đề xuất vùng. Mạng
này làm giảm số vùng đề xuất, trong khi vẫn đảm bảo phát hiện chính xác
đối tượng.
Faster R-CNN
1. Dùng một tầng tích chập 3x3 với đệm bằng 1 để biến đổi đầu ra của CNN và
đặt số kênh đầu ra bằng c. Bằng cách này, mỗi phần tử trong ánh xạ đặc
trưng mà CNN trích xuất ra từ bức ảnh là một đặc trưng mới có độ dài bằng c.

2. Lấy mỗi phần tử trong ánh xạ đặc trưng làm tâm để tạo ra nhiều khung neo có
kích thước và tỷ lệ khác nhau, sau đó gán nhãn cho chúng.

3. Lấy những đặc trưng của các phần tử có độ dài c ở tâm khung neo để phân
loại nhị phân (là vật thể hay là nền) và dự đoán khung chứa tương ứng cho
các khung neo.

4. Sau đó, sử dụng triệt phi cực đại (non‐maximum suppression) để loại bỏ các
khung chứa có kết quả giống nhau của hạng mục “vật thể”. Cuối cùng, ta xuất
ra các khung chứa dự đoán là các vùng đề xuất rồi đưa vào tầng gộp RoI.
Faster R-CNN
Faster R-CNN
Faster R-CNN
Mask R-CNN
▪ Nếu dữ liệu huấn luyện được gán nhãn với các vị trí ở cấp độ từng
điểm ảnh trong bức hình, thì mô hình Mask R‐CNN có thể sử dụng
hiệu quả các nhãn chi tiết này để cải thiện độ chính xác của việc
phát hiện đối tượng.
Mask R-CNN
▪ Mask R‐CNN là một sự hiệu chỉnh của Faster R‐CNN. Mask R‐CNN thay thế
tầng tổng hợp RoI bằng tầng căn chỉnh RoI (RoI alignment layer).

▪ Điều này cho phép sử dụng phép nội suy song tuyến tính (bilinear interpolation)
để giữ lại thông tin không gian trong ánh xạ đặc trưng, làm cho Mask R‐CNN
trở nên phù hợp hơn với các dự đoán cấp điểm ảnh.

▪ Lớp căn chỉnh RoI xuất ra các ánh xạ đặc trưng có cùng kích thước cho mọi
RoI. Điều này không những dự đoán các lớp và khung chứa của RoI,mà còn
cho phép chúng ta bổ sungmộtmạng nơ‐ron tích chập đầy đủ (fully
convolutional network) để dự đoán vị trí cấp điểm ảnh của các đối tượng.
Mask R-CNN
Object Detection
Object Detection
Object Detection
Object Detection
Object Detection
Hanoi University of Science and Technology
Department of Automatic Control

Computer Vision
Lecture 9:
Machine learning background
(part 1)
Van-Truong Pham, PhD
School of Electrical Engineering
Hanoi University of Science and Technology
Site: https://see.hust.edu.vn/pvtruong
Materials
1. Ebook/sách giấy 'Machine Learning cơ bản’, Vũ Hữu Tiệp, 2018.
https://machinelearningcoban.com/
2. Ebook 'Dive into Deep Learning’, Zhang et al., 2020.
https://d2l.aivivn.com/intro_vn.html

3. Ebook ‘Modern Computer Vision with PyTorch’, Ayyadevara, 2020


https://github.com/PacktPublishing/Modern-Computer-Vision-with-PyTorch
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Machine learning
▪ A computer program is said to learn from experience E with respect to
some class of tasks T and performance measure P if its performance at
tasks in T, as measured by P, improves with experience E
------ Tom Mitchell,1997
Tạm dịch: “Máy tính được gọi là học từ kinh nghiệm (dữ liệu) E với tác vụ (dự đoán,
phân lớp, gom nhóm) T và được đánh giá bởi độ đo (độ chính xác) P nếu máy tính khiến
tác vụ T này cải thiện được độ chính xác P thông qua dữ liệu E cho trước.”

▪ Machine learning approach: program an algorithm to


automatically learn from data, or from experience

▪ Some reasons you might want to use a learning algorithm:


• hard to code up a solution by hand (e.g. vision, speech)
• system needs to adapt to a changing environment (e.g. spam
detection)
• want the system to perform better than the human programmers.
5
Ví dụ: phân loại ảnh
▪ Mục tiêu (Task T):
Xác định xem bức ảnh là trong nhà (indoor) hay ngoài trời (outdoor)

▪ Thước đo hiệu quả của phương pháp (performance measure P):


Xác suất phân loại sai
▪ Cần dữ liệu (kinh nghiệm E): các bức ảnh với nhãn (lớp)

6
Ví dụ: phân loại ảnh

7
Phân loại ảnh

8
Các phương pháp học
▪ Types of machine learning

• Supervised learning: have labeled examples of the correct behavior

• Unsupervised learning: no labeled examples - instead, looking for


interesting patterns in the data

• Reinforcement learning: learning system receives a reward


signal, tries to learn to maximize the reward signal.
Slides credited: Roger Grosse
Học không giám sát vs. học có giám sát

▪ Không cho nhãn hay lớp mục tiêu ▪ Cho nhãn hay lớp mục tiêu

▪ Cần tìm ra đặc tính của cấu trúc dữ


liệu cần xét

▪ Thường dùng các phương pháp


phân cụm Clustering (k-means,
▪ PCA, ...)
Học không giám sát vs. học có giám sát

18
Học có giám sát
▪ Cho tập dữ liệu và nhãn (thuộc tính của dữ liệu), xây dựng thuật toán học để dự
đoán nhãn cho dữ liệu mới (chưa từng quan sát trước đó)

y = f(x)
input
output classification
function
• Học: cho một tập dữ liệu đào tạo (training set) với nhãn {(x1,y1), …, (xN,yN)},
ước lượng các tham số của hàm dự đoán f
• Kiểm nghiệm/Thử: Áp dụng f cho một test example x và cho giá trị đầu ra
dự đoán y = f(x)

19
Học có giám sát
Học Nhãn
Training data

Mô hình
Đặc tính Đào tạo
học

Kiểm nghiệm Mô hình


học
Đặc tính Dự đoán

Test
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Linear module
▪ Một mô đun tuyến tính Linear module (linear neuron): biểu diễn quan hệ giữa
đầu vào và đầu ra (ví dụ giữa dữ liệu x và nhãn y)

weight vector

y = å wi xi = wT x
i y
estimate of the Input vector
desired output
Linear
neuron
w1 w2 ... wn

x1 x2 xn
Linear module
▪ Ví dụ điểm tổng kết học phần Grade=0.3*9+0.7*8=8.3
w = ( wmidterm , w finalexam )
x = ( xmidterm , x finalexam ) 
y =  wi xi = w T x 0.3 0.7
i

 x  9  9 8
x= 1=  Midterm Final exam
 x2  8 
 w  0.3 
w= 1=  Grade = wmidterm xmidterm + w final exam x final exam
 w 2  0.7 
LTM1: wmidterm = 0.3; w final exam = 0.7
 x1  THHT : wmidterm = 0.5; w final exam = 0.5
y = w x =  w1 w 2   
T

 x2 
9 
=  0.3 0.7    = 0.3*9 + 0.7 *8 = 8.3
8
Linear module
w = ( wmidterm , w finalexam , bbonus )
Grade=0.3*9+0.7*8+0.5=8.8
x = ( xmidterm , x finalexam ,1)
y =  wi xi = w T x
i

0.3 0.7 0.5


 x1  9 
x =  x2  = 8 
9 8
1  1  Điểm
Midterm Final exam
 w1  0.3  thưởng/phạt
Grade = wmidterm xmidterm + w final exam x final exam + bbonus
w =  w 2  = 0.7 
b  0.5  wmidterm = 0.3; w final exam = 0.7; bbonus = 0.5
 x1  9 
y = w T x =  w1 w 2 b   x2  =  0.3 0.7 0.5 8  = 0.3*9 + 0.7 *8 + 0.5 = 8.8
1  1 
(bias trick) Phân loại: Grade>=4: Pass (binary classifier)
A+, A,B+, B,….
Bias trick
Doing a matrix multiplication and then adding a bias vector (left) is
equivalent to adding a bias dimension with a constant of 1 to all input vectors
and extending the weight matrix by 1 column - a bias column (right)
Linear module
▪ Module nhiều đầu vào, nhiều đầu ra, có bias  x1 
x 
 y1  b1   2
y =  y2  ; b = b2  x =  x3 
x1 w11 b1  
w31 w21  y3  b3   x4 
w12 y1 x 
x2  5
w32 w22 w15 b2
x3 y2

x4 w25 y3
b3
x5 w35
Input Weights Output

Fully connected (FC)


Linear module
x1 w11 b1
w31 w21
x2 w12 y1
w32 w22 w15 b2
x3 y2

x4 w25 y3
b3
x5 w35
Input Weights
Linear module
▪ Module nhiều đầu vào, nhiều đầu ra, không có bias
 x1 
 y1  x 
 2
y =  y2 
x1 w11 x =  x3 
w21  
w31 w12 y1  y3   x4 
x2
w22 w15 x 
w32  5
x3 y2

x4 w25 y3

x5 w35
Input Weights Output
Linear module
▪ Module không có bias x1 w11
w21
w31 w12 y1
x2
w22 w15
w32
x3 y2

x4 w25 y3

x5 w35
Input Weights Output
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Linear regression
• Task: predict scalar-valued targets, e.g. stock prices, house
prices,… (“regression")
• Architecture: function of the inputs (here “linear")

• Problem Setup:

▪ Want to predict a scalar t as a function of a scalar x


▪ Given a dataset of pairs {(x(i),y(i)}, with i=1 N
▪ The x(i) are called inputs, and the y(i) are called targets/output
31
Linear regression
• Example: house prices
Supervised regression problem: Predict the price (continuous value)
of houses given existing data features/properties (house size).
Linear regression
• Example: house prices
Linear regression
• Example: house prices
• Given the training data (point):
The simplest model representation
to regress the data: straight line
Fit a straight line to the
data

• Now we can predict the price for a house of size xtest=125m2

Supervised regression predicts 265K$.


Linear regression

𝑦 = 𝑤𝑥 + 𝑏
x
35
Linear regression
• Trong thực tế thường thay b bằng w0 (tiện cho bias trick)

𝑓𝑤 𝑥
x
𝑓𝑤 𝑥 = 𝑤0 + 𝑤1𝑥

𝑤 = (𝑤0, 𝑤1) : tham số mô hình


36
Linear regression
• Hàm dự đoán (dạng đơn giản): 𝑓𝑤 𝑥 = 𝑤0 + 𝑤1𝑥
𝑤 = (𝑤0, 𝑤1) : tham số mô hình
Ảnh hưởng của các giá trị tham số khác nhau tới việc dự đoán:

➢ Bài toán: xây dựng hàm mất mát sao cho có thể tìm được đường
thẳng (thông qua các hệ số w) phù hợp với tất cả các dữ liệu.
Linear regression
• Squared error y
1
𝐿෠ (y,y*)= (y-y*)2 residuals
2

y-y* is residual,
and we want to make this small
x
• Loss function:
Averaged over all training examples 𝑓𝑤 𝑥𝑖
𝑛 yi
1
𝐿෠ 𝑤 = ෍(𝑓𝑤 (𝑥𝑖 ) − 𝑦𝑖 )2
𝑛 𝑦𝑖 − 𝑓𝑤 𝑥𝑖
𝑖=1

x
xi
38
Linear regression
𝑛
1 𝑓𝑤 𝑥𝑖
෠𝐿 𝑤 = ෍(𝑓 (𝑥 ) − 𝑦 )2 yi
𝑤 𝑖 𝑖
𝑛
𝑖=1
với: n là tổng số mẫu trong tập dữ liệu 𝑦𝑖 − 𝑓𝑤 𝑥𝑖

𝑓𝑤 𝑥 = 𝑤0 + 𝑤1𝑥 x
xi
▪ Tìm các tham số 𝑤0, 𝑤1 thông qua bài toán tối thiểu
hóa hàm mất mát
𝑛
1
min ෍(𝑓𝑤 (𝑥𝑖 ) − 𝑦𝑖 )2
𝑤 = (𝑤 , 𝑤 ) 𝑛
0 1
𝑖=1

Hàm mất mát bình phương


Mean Squared Error (MSE) 39
Linear regression

40
Linear regression
• Example: house prices
• Given the training data (point):
The simplest model representation
to regress the data: straight line
𝑛
1 y=w0+w1x
min ෍(𝑓𝑤 (𝑥𝑖 ) − 𝑦𝑖 )2
𝑤 = (𝑤0, 𝑤1) 𝑛
𝑖=1

Once optimal 𝑤0, 𝑤1 found,

• we can predict the price for a house of size xtest=125m2 , for example
Linear regression model predicts:

𝑦test = 𝑤0 + 𝑤1𝑥 test ytest

y=w0+w1x

➢ Keys: find optimal 𝑤0, 𝑤1 via optimization


xtest
Linear regression
• Hàm dự đoán
• Tham số

• Hàm mất mát

• Bài toán tối ưu

▪ Optimization: cập nhật tham số w bằng cách tối thiểu hóa hàm loss
𝑛
• Loss function 1
෍(𝑓𝑤 (𝑥𝑖 ) − 𝑦𝑖 )2
𝑛
𝑖=1

• Viết dưới dạng vector:


𝑛
1
𝐿෠ 𝑓𝑤 = ෍(𝑤 𝑇 𝑥𝑖 − 𝑦𝑖 )2 = 𝑿𝒘 − 𝒀 2
2
𝑛
𝑖=1

➢ Tại sao nên vector hóa, nhất là trong tính toán? 42


Slides credit: Roger Grosse
Optimization
• Loss function
𝑛
1
෠𝐿 𝑤 = ෍(𝑓 (𝑥 ) − 𝑦 )2
𝑤 𝑖 𝑖
𝑛 𝑓𝑤 𝑥 = 𝑤0 + 𝑤1𝑥
𝑖=1

• Viết dưới dạng vector:


𝑛
1
෠𝐿 𝑓𝑤 = ෍(𝑤 𝑇 𝑥𝑖 − 𝑦𝑖 )2 = 𝑿𝒘 − 𝒀 2
2
𝑛
𝑖=1
Optimization
• Recall
Optimization
𝑛
1
𝐿෠ 𝑓𝑤 = ෍(𝑤 𝑇 𝑥𝑖 − 𝑦𝑖 )2 = 𝑿𝒘 − 𝒀 2
2
𝑛
𝑖=1
Tìm gradient theo 𝑤 (w.r.t.-with respect to 𝑤) :
Lưu ý gradient của hàm số f(x) theo x ký hiệu là ∇𝑥 f(x)

2
∇𝑤 𝑿𝒘 − 𝒀 2 = ∇𝑤 𝑿𝒘 − 𝒀 𝑇 𝑿𝒘 − 𝒀
= ∇𝑤 𝒘𝑻 𝑿𝑻 𝑿𝒘 − 𝟐𝒘𝑻 𝑿𝑻 𝒀 + 𝒀𝑻 𝒀
= 2𝑿𝑻 𝑿𝒘 − 𝟐𝑿𝑻 𝒀
• Đặt gradient bằng 0 để lấy cực tiểu:
𝑿𝑻 𝑿𝒘 = 𝑿𝑻 𝒀
𝒘 = (𝑿𝑻 𝑿)−𝟏 𝑿𝑻 𝒀

➢ Nếu ma trận 𝑋 𝑇 𝑋 khả nghịch, ta có 𝑤 = (𝑋 𝑇 𝑋)−1 𝑋 𝑇 𝑌

Nếu 𝑋 𝑇 𝑋 không khả nghịch, nghiệm đặc biệt có thể thực hiện dựa vào giả nghịch
đảo (pseudo inverse)

➢ Phương pháp giải trực tiếp không linh hoạt: thường dùng gradient descent…
Contents

▪ Machine learning in computer vision


▪ Linear module
▪ Linear regression
▪ Gradient descent
▪ Linear classifier
▪ Logistic regression
▪ Softmax
▪ Python demo
Next: part 2

You might also like