Lecture 8-Đã G P
Lecture 8-Đã G P
Image Segmentation
Outline
❖ Fundamentals
❖ Isolated point detection
❖ Edge detection
❖ Segmentation based on thresholding
❖ Analytic element detection by Hough transform
Fundamentals
❖ 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
❖ 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');
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
❖ 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)
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
❖ 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
3000
2500
2000
1500
1000
500
❖ 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
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(:)';
%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’);
❖ 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
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𝑋 𝑇 𝑌
• Gradient descent:
7
Gradient descent (GD)
▪ Đạo hàm riêng theo tham số
8
Gradient descent (GD)
• Đạo hàm riêng theo
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:
11
Gradient descent (GD)
Gradient descent với nhiều biến
• Hàm dự đoán
• Tham số
• Hàm dự đoán
• 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
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)
• 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)
• 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
Weights
x1
w1
x2
w2
Output: sgn(wx + b)
x3
w3
.
.
.
wD
xD
Perceptron
▪ Phân loại
• Cho tập training data
𝑥𝑖 , 𝑦𝑖 , 𝑖 = 1, … , 𝑛 ,𝑦𝑖 ∈ {−1,1}
𝑓𝑤 𝑥 = 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)
33
Contents
x2
w2
Output: sgn(wx + b)
x3
w3 Output: sigmoid(wx + 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
= 𝜎 −𝑤 𝑇 𝑥
▪ 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 𝑃𝜃 (𝑦𝑖 |𝑥𝑖 )}
➢ Đâ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 − 𝜎 𝑤 𝑇 𝑥
• 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
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 𝑃𝑊 (𝑘|𝑥𝑖 )
𝑘
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. 𝑤𝑘 , 𝑘 ≠ 𝑦𝑖 : 𝑃𝑊 𝑘 𝑥𝑖 𝑥𝑖
• 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
𝒛 = 𝑾𝑇 𝒙
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 𝑤𝑗𝑇 𝑥𝑖
𝒛 = 𝑾𝑇𝒙
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
Demo 2: Lec3_Lab02_Logistic_Classification.ipynb
Contents
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)
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
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
Local Upstream
gradient * gradient
Local Upstream
gradient * gradient
Local Upstream
gradient * gradient
Local Upstream
gradient * gradient
-0.60
-0.40
-0.60
0.40
-0.40
-0.60
0.40
-0.40
-0.60
-0.40
-0.60
Sigmoid gate 𝜎 𝑥
𝜎′ 𝑥 = 𝜎 𝑥 1 − 𝜎 𝑥
𝜎 1 1 − 𝜎 1 = 0.73 ∗ 1 − 0.73 = 0.20
▪ 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.
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()
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
▪ 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
▪ Classification:
• Use the same loss as Logistic Regression (sigmoid for binary classification)
• Cross-entropy (i.e. negative log likelihood)
▪ 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).
……
𝒚
…
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
• 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
ℎ
Output layer
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
• 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
( )
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
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
Output layer
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
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
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 )
a1 → a 2 → a 3 a 2 = f (W 1a1 )
a1 = x
W l W l − W l
el = (W ) el +1 . f ( a l )
T
e3 = a 3 − yˆ
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.
▪ 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)
▪ 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:
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
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
▪ 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 đó
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 đó
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
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
▪ 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!!!
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
.
.
.
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
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
▪ 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
Max
Spatial pooling (or Avg)
Non-linearity
Convolution
(Learned)
Input Image
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
cat dog ……
Convolution
Pooling
Pooling
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)
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)
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(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)
▪ 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:
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
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
▪ 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 đó
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 đó
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
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
▪ 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!!!
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
.
.
.
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
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
▪ 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
Max
Spatial pooling (or Avg)
Non-linearity
Convolution
(Learned)
Input Image
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
cat dog ……
Convolution
Pooling
Pooling
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)
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)
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(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
Deep Autoencoder
(sparse/denoising) Neural Net
Autoencoder Sparse Coding
SP GMM
Deep Belief Net Restricted BM
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
BayesNP
6
Slide Credit: Marc'Aurelio Ranzato, Yann LeCun
SHALLOW
Recurrent
Neural Net
Boosting
Convolutional
Neural Net
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
• Deep models
Trainable Trainable Trainable
Feature- Feature- Feature-
Transform / Transform / Transform /
Classifier Classifier Classifier
SIFT
OM Data
Feature extraction
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
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
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
➢ 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
http://www.image-net.org/challenges/LSVRC/2012/results.html
ILSVRC 2013: top rankers
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
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
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 𝑥)
⇒ 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.
Computer Vision
Lecture 15 :
Detection & Segmentation
▪ 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)
➢ 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.
▪ 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
▪ Introduction
▪ Common computer Vision Tasks
▪ Image Segmentation
▪ Fully Convolutional Networks (FCNs)
▪ U-Net
▪ Object Detection
▪ RCNN and variants
▪ Python demo
Fully Convolutional Network (FCN)
a classification network
“tabby
cat”
FCN motivation
upsampling output
upsampling
pixelwise
conv, pool,
output + loss
nonlinearity
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
▪ 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
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
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
−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.
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.
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
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
▪ Không cho nhãn hay lớp mục tiêu ▪ Cho nhãn hay lớp mục tiêu
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
Test
Contents
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
x4 w25 y3
b3
x5 w35
Input Weights Output
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
• Problem Setup:
𝑦 = 𝑤𝑥 + 𝑏
x
35
Linear regression
• Trong thực tế thường thay b bằng w0 (tiện cho bias trick)
𝑓𝑤 𝑥
x
𝑓𝑤 𝑥 = 𝑤0 + 𝑤1𝑥
➢ 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
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
• we can predict the price for a house of size xtest=125m2 , for example
Linear regression model predicts:
y=w0+w1x
▪ 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
2
∇𝑤 𝑿𝒘 − 𝒀 2 = ∇𝑤 𝑿𝒘 − 𝒀 𝑇 𝑿𝒘 − 𝒀
= ∇𝑤 𝒘𝑻 𝑿𝑻 𝑿𝒘 − 𝟐𝒘𝑻 𝑿𝑻 𝒀 + 𝒀𝑻 𝒀
= 2𝑿𝑻 𝑿𝒘 − 𝟐𝑿𝑻 𝒀
• Đặt gradient bằng 0 để lấy cực tiểu:
𝑿𝑻 𝑿𝒘 = 𝑿𝑻 𝒀
𝒘 = (𝑿𝑻 𝑿)−𝟏 𝑿𝑻 𝒀
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