Python
An Introduction
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
 Programming Languages
 Python Environment
 Basic Data Types
 Functions
 Conditions
 Loops
 Common Errors
Outline
References
 Books
Year 2022 Python 101 - 2020 Beyond the Basic Stuff with Python
https://www.dropbox.com/sh/x69
9xsfs8wnadny/AACMcdVGxen1l
4yNWwQzoF-Xa?dl=0
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
Encode/Represent
Numbers
1, -2 …
-1.2, 2.7 …
Text
a, b, c
Hello
…
Objects
Real World
Year 2022 2
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
A way to represent numbers using bits
With three bits
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
8 different
cases
Positive numbers
0, 7
8, 15
Negative numbers
−1, −8
…
Mixed
−3, 4
Year 2022 3
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
A way to represent numbers using bits
With three bits
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
8 different
cases
Positive numbers Negative numbers
0, 7
8, 15
−1, −8
…
Mixed
−3, 4
How to distinguish the cases?
Year 2022 4
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
A way to represent numbers using bits
With three bits
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
8 different
cases
+ Metadata
Type 1
Positive numbers
0, 7
Type 2
Negative numbers
−1, −8
Type 3
Mixed
−3, 4
Year 2022 5
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
A way to represent numbers using bits
With eight bits
256
different
cases
+ Metadata
Type 1
unsigned char
0, 255
Type 2
char
−127, 128
Syntax for programmer
char a_number = 6;
0 0 0 0 0 1 1 0
Year 2022 6
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
How to represent floating-point numbers?
3.14
3 . 14
a set
of bits
a set
of bits
With 4 bytes
(32 bits)
float
With 8 bytes
(64 bits)
double
Syntax for programmer
float a_number = 3.14;
double another_number = 2.71;
Year 2022 7
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
How to represent/store text using bits?
Need a mapping table!
Year 2022 8
AI VIETNAM
All-in-One Course
Programming Languages
 What should a programming language provide?
How to represent/store text using bits?
Syntax for programmer
char a_number = ‘A’;
A mapping table
0 1 0 0 0 0 0 1
Decimal: 65
Year 2022 9
AI VIETNAM
All-in-One Course
https://commons.wikimedia.org/wiki/File:ASCII-Table-wide.svg
Year 2022 10
Programming Languages
 What should a programming language provide?
Numbers
1, -2 …
-1.2, 2.7 …
Text
a, b, c
Hello
…
Objects
Real World
Encode/Represent
…, 1, 2, 3 …
1.4, 2.7, …
‘A’
‘1’
char int
float
double
What’s more???
Year 2022 11
AI VIETNAM
All-in-One Course
Programming Languages
 C++ and Python
C++ example Python example 12
AI VIETNAM
All-in-One Course
 Programming Languages
 Python Environment
 Basic Data Types
 Functions
 Conditions
 Loops
 Common Errors
Outline
Introduction
 Python history
1
AI VIETNAM
All-in-One Course
Year 2022 13
Introduction
 Python ecosystem
2
AI VIETNAM
All-in-One Course
Year 2022 14
Introduction
 Top Programming Languages (2021)
AI VIETNAM
All-in-One Course
https://spectrum.ieee.org/top-
programming-languages/
Year 2022
Introduction
 First Python program
AI VIETNAM
All-in-One Course
Create a .py file
Write Python code
Run the file
Demo
Year 2022
Introduction
 Virtual environment
AI VIETNAM
All-in-One Course
sudo apt-get install -y python3-venv
python3 -m venv a_name
source a_name/bin/activate
Python
Environment
Python 3.6
Tensorflow 1.4
Python 3.6
Tensorflow 2.1
Python 3.8
Pytorch
Year 2022 17
Introduction
 First Python program
 Using Google Colab
6
AI VIETNAM
All-in-One Course
https://colab.research.google.com/notebooks/intro.ipynb#recent=true
Demo
Year 2022 18
Introduction
 First Python program
 Using Anaconda + Jupyter Notebook
AI VIETNAM
All-in-One Course
Demo
Year 2022
conda create -n test_env2 python=3.9
conda activate an_env
conda deactivate
Setting up environment
To check packages installed
pip list
Open the jupyter program
jupyter notebook
To install a package
pip install package_name
Some common commands
Introduction
 Install new package
pip install matplotlib
Variable
4
AI VIETNAM
All-in-One Course
variable_name = variable_value
Variable values
1, 2, 3, 0, -1, -2
Integer
1.5, 0.5, -3.21, 1.0
Float
'Joe', 'Schmoe', "Joe", "Schmoe"
String
True, False
Boolean
21
Year 2022
Variable
4
AI VIETNAM
All-in-One Course
variable_name = variable_value
variable_name
Should has a meaning
Cannot use keywords
Example
Demo
22
Built-in Functions
AI VIETNAM
All-in-One Course
print(parameters)
type(parameter)
Built-in Functions
AI VIETNAM
All-in-One Course
input(promt)
4
24
Year 2022
Built-in Functions
AI VIETNAM
All-in-One Course
int() float()
Type Conversion
4
Demo 25
Year 2022
Random and Math Modules
4
AI VIETNAM
All-in-One Course
https://docs.python.org/3/library/math.html
Demo
26
Year 2022
Random and Math Modules
4
AI VIETNAM
All-in-One Course
https://docs.python.org/3/library/random.html
Demo
27
Year 2022
Basic Operators
AI VIETNAM
All-in-One Course
4
Demo 28
Year 2022
Example
4
AI VIETNAM
All-in-One Course
𝐹 =
9𝐶
5
+ 32
Celsius to Fahrenheit conversion
𝐶 = 𝐹 − 32
5
9
Celsius to Fahrenheit conversion
29
Year 2022
Example
Circumference and
area of common shapes
4
AI VIETNAM
All-in-One Course
Demo
30
Year 2022
Questions
AI VIETNAM
All-in-One Course
?
Year 2022
Functions
4
AI VIETNAM
All-in-One Course
Define function name
Lowercase with underscores
and begin with a verb
Determine function parameters
Input data help the function done
Do docstring
Explain and describe the function
Output of the function
Notes for function construction
Indentation
Use 4 spaces for indentation
parentheses colon
keyword
General structure of a function
indentation
Demo (rectangle) 31
Year 2022
Functions
AI VIETNAM
All-in-One Course
Define function name
Lowercase with underscores,
usually begin with a verb
Determine function parameters
Input data help the function done
Do docstring
Explain and describe the function
Output of the function
compute_rectangle_area
Name
height, width
Parameter
area
Output
4
32
Functions
 Default values
4
AI VIETNAM
All-in-One Course
Default values
33
Year 2022
Sigmoid Function
AI VIETNAM
All-in-One Course
𝑦 = 𝜎(𝑢) =
1
1 + 𝑒−𝑢
𝑢 ∈ −∞ + ∞
𝑦 ∈ 0 1
∀𝑢1𝑢2 ∈ 𝑎 𝑏 và 𝑢1 ≤ 𝑢2
→ 𝜎(𝑢1) ≤ 𝜎(𝑢1)
𝒖
+∞
−∞
𝑢1 𝑢2
𝒚
𝑦1
𝑦2
Sigmoid function
Property
34
Year 2022
Activation Functions
sigmoid 𝑥 =
1
1 + 𝑒−𝑥
tanh 𝑥 =
𝑒𝑥 − 𝑒−𝑥
𝑒𝑥 + 𝑒−𝑥
35
S-shaped curves
Map x values into small ranges
Overflow and Underflow
 Why?
AI VIETNAM
All-in-One Course
Year 2022 36
Overflow and Underflow
AI VIETNAM
AI Insight Course
Softmax function
𝑧1 = 1.0
𝑧2 = 3.0
Softmax
𝑓(𝑧1) = 0.12
𝑓(𝑧2) = 0.88
Input Probability
𝑧1 = 1.0
𝑧2 = 2.0 Softmax
𝑓(𝑧1) = 0.09
𝑓(𝑧2) = 0.24
Input Probability
𝑧3 = 3.0 𝑓(𝑧3) = 0.67
𝑃𝑖 = 𝑓 𝑧𝑖 =
𝑒𝑧𝑖
σ𝑗 𝑒𝑧𝑗
0 ≤ 𝑓 𝑧𝑖 ≤ 1
෍
𝑖
𝑓 𝑧𝑖 = 1
Year 2022 37
Softmax function
𝑓 𝑥𝑖 =
𝑒𝑥𝑖
σ𝑗 𝑒𝑥𝑗
0 ≤ 𝑓 𝑥𝑖 ≤ 1
෍
𝑖
𝑓 𝑥𝑖 = 1
Formula
𝑥1 = 1.0
𝑥2 = 2.0 Softmax
𝑓(𝑥1) = 0.09
𝑓(𝑥2) = 0.24
Input Probability
𝑥3 = 3.0 𝑓(𝑥3) = 0.67
Chuyển các giá trị của một vector thành các giá trị xác suất
Implementation
(straightforward)
Softmax function
𝑓 𝑥𝑖 =
𝑒𝑥𝑖
σ𝑗 𝑒𝑥𝑗
0 ≤ 𝑓 𝑥𝑖 ≤ 1
෍
𝑖
𝑓 𝑥𝑖 = 1
Formula
𝑥1 = 1.0
𝑥2 = 2.0 Softmax
𝑓(𝑥1) = 0.09
𝑓(𝑥2) = 0.24
Input Probability
𝑥3 = 3.0 𝑓(𝑥3) = 0.67
Giá trị nan vì
𝑒𝑥 vượt giới
hạn lưu trữ của
biến
Chuyển các giá trị của một vector thành các giá trị xác suất
Hàm mũ tăng rất
nhanh khi x tăng
𝑒𝑥
𝑥
𝑒𝑥 ∈ [1, +∞)
𝑥 ∈ [0, +∞)
Implementation
(straightforward)
39
Softmax function (stable)
𝑓 𝑥𝑖 =
𝑒(𝑥𝑖−𝑚)
σ𝑗 𝑒(𝑥𝑗−𝑚)
(Stable) Formula
𝑚 = max(𝒙) 𝑥1 = 1.0
𝑥2 = 2.0
X
𝑥3 = 3.0
Softmax
𝑓(𝑥1) = 0.09
𝑓(𝑥2) = 0.24
Probability
𝑓(𝑥3) = 0.67
𝑥1 = −2.0
𝑥2 = −1.0
X-m
𝑥3 = 0
𝑒𝑥
𝑥
𝑒𝑥 ∈ (0, 1)
𝑥 ∈ (−∞, 0)
Implementation (stable)
 Programming Languages
 Python Environment
 Basic Data Types
 Functions
 Conditions
 Loops
 Common Errors
Outline
Condition
 Comparison operators
4
AI VIETNAM
All-in-One Course
41
Year 2022
Condition
 if condition
4
AI VIETNAM
All-in-One Course
Khối code K1
Điều
kiện if
Khối code trong if
Khối code K2
True
False
keyword
indentation
colon
42
Year 2022
Condition
if
condition
4
AI VIETNAM
All-in-One Course
ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
43
Year 2022
Condition
 if-else condition
4
AI VIETNAM
All-in-One Course
Khối code (K1)
Điều
kiện if
Khối code trong if
Khối Code (K2)
True
False
Khối code trong else
keyword
indentation
colon
44
Year 2022
Condition
 if-else condition
4
AI VIETNAM
All-in-One Course
if
condition ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
Demo
45
Year 2022
Condition
 if-elif-else condition
AI VIETNAM
All-in-One Course
Khối code (K1)
Điều
kiện if
Khối code trong if
Khối Code (K2)
True
False
Khối code trong elif
Điều
kiện elif
Khối code trong else
True
False
colon
indentation
Year 2022
Condition
 if-elif-else condition
4
AI VIETNAM
All-in-One Course
47
FuzzyEncoding 𝑥, 𝑦, 𝑇 =
5,
4,
3,
2,
1,
if 𝑥 + 𝑇 ≤ 𝑦
if 𝑥 < 𝑦 < 𝑥 + 𝑇
if 𝑥 = 𝑦
if 𝑦 < 𝑥 < 𝑦 + 𝑇
if 𝑦 + 𝑇 ≤ 𝑥
Year 2022
5 4 3 2 1
T
LTP 𝑥, 𝑦 = ቐ
0 if 𝑥 = 𝑦
1 if 𝑥 > 𝑦
−1 if 𝑥 < 𝑦
If-Else Condition and Math (1)
if 𝑎 = 0 then 𝑦 = 𝑏2
if 𝑎 = 𝐾 then 𝑦 = 𝑏
Input: 𝑎 and 𝑏
𝑦 =
𝑎
𝐾
𝑏 +
𝐾 − 𝑎
𝐾
𝑏2
Input: 𝑎 and 𝑏
AI VIETNAM
All-in-One Course
48
Year 2022
If-Else Condition and Math (2)
if 𝑎 > 0 then
𝑦 = 𝑏2
if 𝑎 < 0 then
𝑦 = 𝑏
Input: 𝑎 and 𝑏
𝑦 =
𝑏2 + 𝑏
2
+
𝑏2 − 𝑏
2
𝑎
𝑎
Input: 𝑎 and 𝑏
AI VIETNAM
All-in-One Course
49
Year 2022
If-Else Condition and Math (3)
Input: 𝑎 and 𝑏
if 𝑎 = 0 then 𝑦 = 𝑏2
if 𝑎 = 1 then 𝑦 = 𝑏
if 𝑎 = 2 then 𝑦 = 𝑏
Input: 𝑎 and 𝑏
Convert 𝑎 into a one-hot vector 𝒗
𝑦 = 𝒗 ∙ 𝒖
𝒖 = [𝑏2
𝑏 𝑏]
𝒗 = [1 0 0]
𝒗 = [0 1 0]
𝒗 = [0 0 1]
AI VIETNAM
All-in-One Course
50
Year 2022
Questions
AI VIETNAM
All-in-One Course
?
Year 2022
For Loop
4
AI VIETNAM
All-in-One Course
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
colon
indentation
keyword
String
Tuple
List
Dictionary
range()
Iterables
51
Year 2022
For Loop
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
4
52
For Loop
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
4
0, 1, 2, 3, 4
range(start=0, stop, step=1)
range(start=0, stop=5, step=1)
0, 1, 2, 3, 4
range(5)
Demo 53
For Loop
AI VIETNAM
All-in-One Course
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
break
break keyword
4
Demo 54
For Loop
AI VIETNAM
All-in-One Course
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
continue
continue keyword
Demo
4
55
Example
 Simulation of coin tossing
AI VIETNAM
All-in-One Course
Event: bất kì sự kiện gì xảy ra
Experiment: sự thử nghiệm cho ra kết quả
Sample space: tập hợp tất cả các kết quả có thể xảy ra của một experiment
Random variable: biến ngẫu nhiên, mô tả outcome của một event
Tiền xu có 2 mặt
(head và tail)
Sample space 𝑆 = Head, Tail
Experiment: ném đồng xu
Event: Gọi A là event mà kết quả của một lần ném là head
𝑃(𝐴) Xác suất để event A xảy ra
Xác suất để kết quả của một lần ném là head
A={head}
S={head, tail}
𝑃 𝐴 =
𝐴
𝑆
=
1
2
Xác suất
𝑃(event) =
event
𝑆
4
56
Year 2022
Example
 Simulation of coin tossing
AI VIETNAM
All-in-One Course
Count #tails
Count #heads
Check if the two
numbers are similar
Demo 57
Year 2022
Example: PI Estimation
 PI estimation
4
AI VIETNAM
All-in-One Course
hình từ
wikipedia
circle_area 𝐴𝑐= 𝜋𝑟2
circle radius 𝑟 = 1
square_area 𝐴𝑠 = 𝑠2
square side 𝑠 = 2
𝐴𝑠
𝐴𝑐
≈
𝑁𝑠
𝑁𝑐
𝑠2
𝜋𝑟2 ≈
𝑁𝑠
𝑁𝑐
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠
𝑁𝑠 is #random samples within the square
generated according to uniform distribution
𝑁𝑐 is #random samples within the circle
generated according to uniform distribution
58
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
(hình từ wikipedia)
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠
Random numbers ∈ [-1,1]
Check if a point is
within the circle
59
Year 2022
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
(hình từ wikipedia)
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠 https://www.mathsisfun.com/algebra/distance-2-points.html
60
Year 2022
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
(hình từ wikipedia)
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠
61
Year 2022
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
62
𝑃𝐼 ≈ 4 ෍
𝑖=1
𝑛
−1 𝑖+1
2𝑖 − 1
Gregory-Leibniz Series
Nilakantha Series
𝑃𝐼 ≈ 3 + 4 ෍
𝑖=0
𝑛
−1𝑖
2𝑖 + 2 2𝑖 + 3 2𝑖 + 4
Year 2022
Example
 Euler's number
4
https://www.mathsisfun.com/numbers/e-eulers-number.html
𝑒 ≈ 1 +
1
𝑛
𝑛
AI VIETNAM
All-in-One Course
63
Year 2022
Example
 Euler's number
𝑒 = 2.71828
Formula
1) Compute factorial
2) Compute sum
4
64
Year 2022
Example
 Euler's number
65
Year 2022
Example: Quadratic Root
 Compute quadratic root for the number N
4
AI VIETNAM
All-in-One Course
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
Compute 9
𝑁 = 9
𝑠𝑒𝑡 𝑥0 =
9
2
= 4.5
𝑛 = 0
𝑛 = 0
𝑥1 =
𝑥0 +
𝑁
𝑥0
2
=
4.5 +
9
4.5
2
=
6.5
2
= 3.25
𝑛 = 1
𝑥2 =
𝑥1 +
𝑁
𝑥1
2
=
3.25 +
9
3.25
2
=
6.019
2
= 3.009
𝑛 = 2
𝑥3 =
𝑥2 +
𝑁
𝑥2
2
=
3.009 +
9
3.009
2
= 3.00001
66
Year 2022
Example: Quadratic Root
 Compute quadratic root for the number N
AI VIETNAM
All-in-One Course
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
67
Questions
AI VIETNAM
All-in-One Course
?
Year 2022
While Loop
4
AI VIETNAM
All-in-One Course
Condition
Thực thi các câu lệnh
trong while
False
True
Code trước while
Code sau while
colon
indentation
keyword
68
Year 2022
While Loop
4
AI VIETNAM
All-in-One Course
Condition
Thực thi các câu lệnh
trong while
False
True
Code trước while
Code sau while
69
Year 2022
While Loop
𝑖 = 0 𝑖 < 5 ?
yes
𝑖 = 0 + 1 = 1
print(0)
𝑖 < 5 ?
yes
𝑖 = 1 + 1 = 2
print(1) 𝑖 < 5 ?
𝑖 < 5 ?
yes
𝑖 = 2 + 1 = 2
print(2)
𝑖 < 5 ?
yes
𝑖 = 3 + 1 = 4
print(3) 𝑖 < 5 ?
𝑖 < 5 ?
yes
𝑖 = 4 + 1 = 5
print(4)
𝑖 < 5 ?
no print(′Phần code này
khi đã thoát while′)
4
70
Year 2022
While Loop
while-True-break
4
AI VIETNAM
All-in-One Course
71
Year 2022
Exercises
4
AI VIETNAM
All-in-One Course
72
Pascal's Triangle
Level = 5
0, 1, 1, 2, 3, 5, 8, 13, 21
+
Length = 9
Fibonacci Sequence
https://www.mathsisfun.com
Year 2022
Exercises
4
AI VIETNAM
All-in-One Course
73
Year 2022
𝑠𝑖𝑛 𝑥 ≈ ෍
𝑛=0
∞
−1 𝑛
𝑥 2𝑛+1
2𝑛 + 1 !
= 𝑥 −
𝑥3
3!
+
𝑥5
5!
−
𝑥7
7!
+
𝑥9
9!
− ⋯
𝑐𝑜𝑠 𝑥 ≈ ෍
𝑛=0
∞
−1 𝑛
𝑥2𝑛
2𝑛 !
= 1 −
𝑥2
2!
+
𝑥4
4!
−
𝑥6
6!
+
𝑥8
8!
−
𝑥10
10!
+ ⋯
𝑒𝑥 ≈ ෍
𝑛=0
∞
𝑥𝑛
𝑛!
= 1 +
𝑥1
1!
+
𝑥2
2!
+
𝑥3
3!
+
𝑥4
4!
+
𝑥5
5!
+ ⋯
𝑠𝑖𝑛ℎ 𝑥 ≈ ෍
𝑛=0
∞
𝑥 2𝑛+1
2𝑛 + 1 !
= 𝑥 +
𝑥3
3!
+
𝑥5
5!
+
𝑥7
7!
+
𝑥9
9!
+ ⋯
𝑐𝑜𝑠ℎ 𝑥 ≈ ෍
𝑛=0
∞
𝑥2𝑛
2𝑛 !
= 1 +
𝑥2
2!
+
𝑥4
4!
+
𝑥6
6!
+
𝑥8
8!
+
𝑥10
10!
+ ⋯
Exercises
4
AI VIETNAM
All-in-One Course
74
PI estimation
E estimation
Simulation of
coin tossing
Compute quadratic root for the number N
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
Year 2022
Recursive
4
AI VIETNAM
All-in-One Course
75
PI estimation
E estimation
Simulation of
coin tossing
Compute quadratic root for the number N
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
Year 2022
Common Errors
 Error 1
AI VIETNAM
All-in-One Course
76
Year 2022
Common Errors
 Error 2
AI VIETNAM
All-in-One Course
77
Year 2022
Common Errors
 Error 3
AI VIETNAM
All-in-One Course
78
Year 2022
Common Errors
 Error 4
AI VIETNAM
All-in-One Course
79
Year 2022
Common Errors
 Error 5
AI VIETNAM
All-in-One Course
80
Year 2022
Common Errors
 Error 6
AI VIETNAM
All-in-One Course
81
Year 2022
Common Errors
 Error 7
AI VIETNAM
All-in-One Course
82
Year 2022
Common Errors
 Error 8
AI VIETNAM
All-in-One Course
83
Year 2022
Common Errors
 Error 9
AI VIETNAM
All-in-One Course
84
Year 2022
Common Errors
 Error 10
AI VIETNAM
All-in-One Course
85
Year 2022
Common Errors
 Error 11
AI VIETNAM
All-in-One Course
86
Year 2022
Common Errors
 Error 12
AI VIETNAM
All-in-One Course
87
Year 2022
Common Errors
 Error 13
AI VIETNAM
All-in-One Course
88
Year 2022
Common Errors
 Error 14
AI VIETNAM
All-in-One Course
89
Year 2022
Common Errors
 Error 15
AI VIETNAM
All-in-One Course
90
Year 2022
Common Errors
 Error 16
AI VIETNAM
All-in-One Course
91
Year 2022
Common Errors
 Error 17
AI VIETNAM
All-in-One Course
92
Year 2022
Common Errors
 Error 18
AI VIETNAM
All-in-One Course
93
Year 2022
Common Errors
 Error 19
AI VIETNAM
All-in-One Course
94
Year 2022
Common Errors
 Error 20
AI VIETNAM
All-in-One Course
95
Year 2022
Common Errors
 Error 21
AI VIETNAM
All-in-One Course
96
Year 2022
Python
A Deeper Step
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
 Conditions
 Loops
 String
 File
Outline
Condition
 Comparison operators
1
AI VIETNAM
All-in-One Course
Year 2022
Condition
 if condition
2
AI VIETNAM
All-in-One Course
Khối code K1
Điều
kiện if
Khối code trong if
Khối code K2
True
False
keyword
indentation
colon
Year 2022
Condition
if
condition
3
AI VIETNAM
All-in-One Course
ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
Year 2022
Condition
 if-else condition
4
AI VIETNAM
All-in-One Course
Khối code (K1)
Điều
kiện if
Khối code trong if
Khối Code (K2)
True
False
Khối code trong else
keyword
indentation
colon
Year 2022
Condition
 if-else condition
5
AI VIETNAM
All-in-One Course
if
condition ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
Demo
Year 2022
Condition
 if-elif-else condition
AI VIETNAM
All-in-One Course
Khối code (K1)
Điều
kiện if
Khối code trong if
Khối Code (K2)
True
False
Khối code trong elif
Điều
kiện elif
Khối code trong else
True
False
colon
indentation
Year 2022
Condition
 if-elif-else condition
7
AI VIETNAM
All-in-One Course
FuzzyEncoding 𝑥, 𝑦, 𝑇 =
5,
4,
3,
2,
1,
if 𝑥 + 𝑇 ≤ 𝑦
if 𝑥 < 𝑦 < 𝑥 + 𝑇
if 𝑥 = 𝑦
if 𝑦 < 𝑥 < 𝑦 + 𝑇
if 𝑦 + 𝑇 ≤ 𝑥
Year 2022
5 4 3 2 1
T
LTP 𝑥, 𝑦 = ቐ
0 if 𝑥 = 𝑦
1 if 𝑥 > 𝑦
−1 if 𝑥 < 𝑦
If-Else Condition and Math (1)
if 𝑎 = 0 then 𝑦 = 𝑏2
if 𝑎 = 𝐾 then 𝑦 = 𝑏
Input: 𝑎 and 𝑏
𝑦 =
𝑎
𝐾
𝑏 +
𝐾 − 𝑎
𝐾
𝑏2
Input: 𝑎 and 𝑏
AI VIETNAM
All-in-One Course
Year 2022 8
If-Else Condition and Math (2)
if 𝑎 > 0 then
𝑦 = 𝑏2
if 𝑎 < 0 then
𝑦 = 𝑏
Input: 𝑎 and 𝑏
𝑦 =
𝑏2 + 𝑏
2
+
𝑏2 − 𝑏
2
𝑎
𝑎
Input: 𝑎 and 𝑏
AI VIETNAM
All-in-One Course
Year 2022 9
If-Else Condition and Math (3)
Input: 𝑎 and 𝑏
if 𝑎 = 0 then 𝑦 = 𝑏2
if 𝑎 = 1 then 𝑦 = 𝑏
if 𝑎 = 2 then 𝑦 = 𝑏
Input: 𝑎 and 𝑏
Convert 𝑎 into a one-hot vector 𝒗
𝑦 = 𝒗 ∙ 𝒖
𝒖 = [𝑏2
𝑏 𝑏]
𝒗 = [1 0 0]
𝒗 = [0 1 0]
𝒗 = [0 0 1]
AI VIETNAM
All-in-One Course
10
Year 2022
 Conditions
 Loops
 String
 File
Outline
Motivation
 Observation
Year 2021
AI VIETNAM
AI Course 2021
Features Label
Feature Label
House price data Advertising data
For Loop
4
AI VIETNAM
All-in-One Course
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
colon
indentation
keyword
String
Tuple
List
Dictionary
range()
Iterables
11
Year 2022
For Loop
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
4
12
For Loop
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
4
0, 1, 2, 3, 4
range(start=0, stop, step=1)
range(start=0, stop=5, step=1)
0, 1, 2, 3, 4
range(5)
Demo 13
For Loop
AI VIETNAM
All-in-One Course
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
break
break keyword
4
Demo 14
For Loop
AI VIETNAM
All-in-One Course
Đã duyệt
phần tử
cuối cùng?
Thực thi các câu lệnh
trong for
True
False
Code trước for
Code sau for
continue
continue keyword
Demo
4
15
Example
 Simulation of coin tossing
AI VIETNAM
All-in-One Course
Event: bất kì sự kiện gì xảy ra
Experiment: sự thử nghiệm cho ra kết quả
Sample space: tập hợp tất cả các kết quả có thể xảy ra của một experiment
Random variable: biến ngẫu nhiên, mô tả outcome của một event
Tiền xu có 2 mặt
(head và tail)
Sample space 𝑆 = Head, Tail
Experiment: ném đồng xu
Event: Gọi A là event mà kết quả của một lần ném là head
𝑃(𝐴) Xác suất để event A xảy ra
Xác suất để kết quả của một lần ném là head
A={head}
S={head, tail}
𝑃 𝐴 =
𝐴
𝑆
=
1
2
Xác suất
𝑃(event) =
event
𝑆
4
16
Year 2022
Example
 Simulation of coin tossing
AI VIETNAM
All-in-One Course
Count #tails
Count #heads
Check if the two
numbers are similar
Demo 17
Year 2022
Example: PI Estimation
 PI estimation
4
AI VIETNAM
All-in-One Course
hình từ
wikipedia
circle_area 𝐴𝑐= 𝜋𝑟2
circle radius 𝑟 = 1
square_area 𝐴𝑠 = 𝑠2
square side 𝑠 = 2
𝐴𝑠
𝐴𝑐
≈
𝑁𝑠
𝑁𝑐
𝑠2
𝜋𝑟2 ≈
𝑁𝑠
𝑁𝑐
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠
𝑁𝑠 is #random samples within the square
generated according to uniform distribution
𝑁𝑐 is #random samples within the circle
generated according to uniform distribution
18
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
(hình từ wikipedia)
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠
Random numbers ∈ [-1,1]
Check if a point is
within the circle
19
Year 2022
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
(hình từ wikipedia)
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠 https://www.mathsisfun.com/algebra/distance-2-points.html
20
Year 2022
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
(hình từ wikipedia)
𝜋 ≈
𝑠2
𝑁𝑐
𝑁𝑠
21
Year 2022
Example
 PI estimation
4
AI VIETNAM
All-in-One Course
22
𝑃𝐼 ≈ 4 ෍
𝑖=1
𝑛
−1 𝑖+1
2𝑖 − 1
Gregory-Leibniz Series
Nilakantha Series
𝑃𝐼 ≈ 3 + 4 ෍
𝑖=0
𝑛
−1𝑖
2𝑖 + 2 2𝑖 + 3 2𝑖 + 4
Year 2022
Example
 Euler's number
4
https://www.mathsisfun.com/numbers/e-eulers-number.html
𝑒 ≈ 1 +
1
𝑛
𝑛
AI VIETNAM
All-in-One Course
23
Year 2022
Example
 Euler's number
𝑒 = 2.71828
Formula
1) Compute factorial
2) Compute sum
4
24
Year 2022
Example
 Euler's number
25
Year 2022
Example: Quadratic Root
 Compute quadratic root for the number N
4
AI VIETNAM
All-in-One Course
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
Compute 9
𝑁 = 9
𝑠𝑒𝑡 𝑥0 =
9
2
= 4.5
𝑛 = 0
𝑛 = 0
𝑥1 =
𝑥0 +
𝑁
𝑥0
2
=
4.5 +
9
4.5
2
=
6.5
2
= 3.25
𝑛 = 1
𝑥2 =
𝑥1 +
𝑁
𝑥1
2
=
3.25 +
9
3.25
2
=
6.019
2
= 3.009
𝑛 = 2
𝑥3 =
𝑥2 +
𝑁
𝑥2
2
=
3.009 +
9
3.009
2
= 3.00001
26
Year 2022
Example: Quadratic Root
 Compute quadratic root for the number N
AI VIETNAM
All-in-One Course
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
27
Questions
AI VIETNAM
All-in-One Course
?
Year 2022
While Loop
4
AI VIETNAM
All-in-One Course
Condition
Thực thi các câu lệnh
trong while
False
True
Code trước while
Code sau while
colon
indentation
keyword
28
Year 2022
While Loop
4
AI VIETNAM
All-in-One Course
Condition
Thực thi các câu lệnh
trong while
False
True
Code trước while
Code sau while
29
Year 2022
While Loop
𝑖 = 0 𝑖 < 5 ?
yes
𝑖 = 0 + 1 = 1
print(0)
𝑖 < 5 ?
yes
𝑖 = 1 + 1 = 2
print(1) 𝑖 < 5 ?
𝑖 < 5 ?
yes
𝑖 = 2 + 1 = 2
print(2)
𝑖 < 5 ?
yes
𝑖 = 3 + 1 = 4
print(3) 𝑖 < 5 ?
𝑖 < 5 ?
yes
𝑖 = 4 + 1 = 5
print(4)
𝑖 < 5 ?
no print(′Phần code này
khi đã thoát while′)
4
30
Year 2022
While Loop
while-True-break
4
AI VIETNAM
All-in-One Course
31
Year 2022
Exercises
4
AI VIETNAM
All-in-One Course
32
Pascal's Triangle
Level = 5
0, 1, 1, 2, 3, 5, 8, 13, 21
+
Length = 9
Fibonacci Sequence
https://www.mathsisfun.com
Year 2022
Exercises
4
AI VIETNAM
All-in-One Course
33
Year 2022
𝑠𝑖𝑛 𝑥 ≈ ෍
𝑛=0
∞
−1 𝑛
𝑥 2𝑛+1
2𝑛 + 1 !
= 𝑥 −
𝑥3
3!
+
𝑥5
5!
−
𝑥7
7!
+
𝑥9
9!
− ⋯
𝑐𝑜𝑠 𝑥 ≈ ෍
𝑛=0
∞
−1 𝑛
𝑥2𝑛
2𝑛 !
= 1 −
𝑥2
2!
+
𝑥4
4!
−
𝑥6
6!
+
𝑥8
8!
−
𝑥10
10!
+ ⋯
𝑒𝑥 ≈ ෍
𝑛=0
∞
𝑥𝑛
𝑛!
= 1 +
𝑥1
1!
+
𝑥2
2!
+
𝑥3
3!
+
𝑥4
4!
+
𝑥5
5!
+ ⋯
𝑠𝑖𝑛ℎ 𝑥 ≈ ෍
𝑛=0
∞
𝑥 2𝑛+1
2𝑛 + 1 !
= 𝑥 +
𝑥3
3!
+
𝑥5
5!
+
𝑥7
7!
+
𝑥9
9!
+ ⋯
𝑐𝑜𝑠ℎ 𝑥 ≈ ෍
𝑛=0
∞
𝑥2𝑛
2𝑛 !
= 1 +
𝑥2
2!
+
𝑥4
4!
+
𝑥6
6!
+
𝑥8
8!
+
𝑥10
10!
+ ⋯
Exercises
4
AI VIETNAM
All-in-One Course
34
PI estimation
E estimation
Simulation of
coin tossing
Compute quadratic root for the number N
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
Year 2022
Recursive
4
AI VIETNAM
All-in-One Course
35
PI estimation
E estimation
Simulation of
coin tossing
Compute quadratic root for the number N
𝑥𝑛+1 =
𝑥𝑛 +
𝑁
𝑥𝑛
2
Newton Method
Set a value for 𝑥0; n = 0
(𝑥0 = N/2)
n = n + 1
Year 2022
 Conditions
 Loops
 String
 File
Outline
String
AI VIETNAM
All-in-One Course
36
 String creation
https://commons.wikimedia.org/wiki/File:Ascii_Table-nocolor.svg 37
Variables
 Character type
AI VIETNAM
All-in-One Course
Year 2022 38
ASCII Table
https://upload.wikimedia.org/wikipedia/commons/d/dd/ASCII-Table.svg
 American Standard code for
information interchange
ASCII represents 128 characters
ASCII is stored as 8- bit byte
ASCII is not standardized
AI VIETNAM
All-in-One Course
Year 2022 39
ASCII Table
AI VIETNAM
All-in-One Course
Year 2022 40
ASCII Table
AI VIETNAM
All-in-One Course
Year 2022 41
String
AI VIETNAM
All-in-One Course
 Insert into a string
String
 + and * operators
AI VIETNAM
All-in-One Course
 Logic operators
Year 2022 44
String
AI VIETNAM
All-in-One Course
isdigit(): Kiểm tra xem string gồm các kí tự số
isalpha(): Kiểm tra xem string chỉ được tạo
từ các kí tự chữ cái
islower(): Kiểm tra xem string với tất cả các
kí tự ở dạng chữ thường
isupper(): Kiểm tra xem string với tất cả các kí
tự ở dạng chữ hoa
Year 2022 45
String
AI VIETNAM
All-in-One Course
istitle(): Kiểm tra xem string có bắt
đầu bằng chữ in hoa
isspace(): Kiểm tra xem string
chỉ là khoảng trắng
count() để đếm số kí tự xuất hiện trong một string,
len() để tính chiều dài của một string
Year 2022 46
String
AI VIETNAM
All-in-One Course
title(): Chuyển đổi kí tự đầu từng từ (word) trong một
chuỗi thành kí tự hoa
capitalize(): Chuyển đổi chữ cái đầu tiên của một chuỗi
thành chữ hoa và các kí tự sau thành chữ thường
swapcase(): Chuyển đổi các kí tự từ chữ thường
sang chữ hoa và ngược lại
Year 2022 47
String
AI VIETNAM
All-in-One Course
upper(): Chuyển đổi tất cả các kí tự trong chuỗi
thành chữ hoa
lower(): Chuyển đổi các kí tự sang chữ thường
center(): Chỉnh chuỗi ở trung tâm, và chiều dài của chuỗi là 40
Year 2022 48
String
AI VIETNAM
All-in-One Course
strip(): Loại bỏ khoảng trắng ở cả hai đầu của chuỗi
replace(): Thay thế chuỗi
partition(): Tách chuỗi
Year 2022 49
String
AI VIETNAM
All-in-One Course
endswith(): Kiểm tra phần kết thúc của một string.
startswith(): Kiểm tra phần đầu của một string.
find(): Tìm vị trí xuất hiện của string s1 trong string s2.
Giá trị -1 được trả về trong trường hợp s1 không được tìm thấy trong
s2.
50
String
 Common Error
AI VIETNAM
All-in-One Course
index(): Tìm vị trí xuất hiện của string
s1 trong string s2.
Lỗi ValueError được trả về trong trường
hợp s1 không được tìm thấy trong s2.
Year 2022 51
String
 Common Error
AI VIETNAM
All-in-One Course
Year 2022 52
 Conditions
 Loops
 String
 File
Outline
File
 Typical procedure
AI VIETNAM
All-in-One Course
Python
A file
(1)
(2)
(3)
Connect to file
Read from/write to file
Disconnect to file
(1)
(2)
(3)
open(file_path, ‘r’)
read()
close()
(1)
(2)
(3)
Read from a file
(already exist)
67
File
AI VIETNAM
All-in-One Course
Python
A file
(1)
(2)
(3)
Connect to file
Read from/write to file
Disconnect to file
(1)
(2)
(3)
open(file_path, ‘r’)
readlines()
close()
(1)
(2)
(3)
Read content
from a file as lines
 Typical procedure
68
File
AI VIETNAM
All-in-One Course
Python
A file
(1)
(2)
(3)
Connect to file
Read from/write to file
Disconnect to file
(1)
(2)
(3)
open(file_path, ‘w’)
write()
close()
(1)
(2)
(3)
Write to a file
(not exist)
 Typical procedure
69
File
Python
A file
(1)
(2)
(3)
Connect to file
Read from/write to file
Disconnect to file
(1)
(2)
(3)
open(file_path, ‘a’)
write()
close()
(1)
(2)
(3)
Write to a file
(appending content if
the file already exists)
 Typical procedure
70
File
 Useful functions
AI VIETNAM
All-in-One Course
Check if a file exists
String splitting
String joining
Year 2022 71
File
 Common Error
AI VIETNAM
All-in-One Course
Year 2022 72
File
 Example
AI VIETNAM
All-in-One Course
Year 2022 73
File
 with keyword
AI VIETNAM
All-in-One Course
Year 2022 74
File
 Example
AI VIETNAM
All-in-One Course
Year 2022 75
File
AI VIETNAM
All-in-One Course
Year 2022
 Example
76
File
 Text data
 IRIS data
AI VIETNAM
All-in-One Course
Year 2022 77
File
 Example
AI VIETNAM
All-in-One Course
Year 2022 78
File
AI VIETNAM
All-in-One Course
 Example
 Conditions
 Loops
 String
 File
 XML and JSON Processing
Outline
String - XML
 eXtensible Markup Language
 Designed to store and transport data
 Designed to be both human- and machine-readable.
AI VIETNAM
All-in-One Course
Year 2022 53
String - XML
 Example
AI VIETNAM
All-in-One Course
Year 2022 54
String - XML
 Example
AI VIETNAM
All-in-One Course
Year 2022 55
String - XML
 Syntax
XML Prolog
Attribute
AI VIETNAM
All-in-One Course
Year 2022 56
String - XML
 Syntax
Element
Opening tag
Closing tag
AI VIETNAM
All-in-One Course
Year 2022 57
String - XML
 Example
Element
Opening tag
Closing tag
AI VIETNAM
All-in-One Course
Year 2022 58
String - JSON
 JSON (JavaScript Object Notation)
 Data exchange format
 Lightweight
 Text-based
 Language-independent
 Designed to be both human- and machine-readable.
AI VIETNAM
All-in-One Course
Year 2022 59
String - JSON
 Example
AI VIETNAM
All-in-One Course
Year 2022 60
String - JSON
 Example
AI VIETNAM
All-in-One Course
Year 2022 61
String - JSON
 Example
AI VIETNAM
All-in-One Course
Year 2022 62
String - JSON
 Syntax
Object
A pair
AI VIETNAM
All-in-One Course
Year 2022 63
String - JSON
 Syntax
Object
https://en.wikipedia.org/wiki/JSON
AI VIETNAM
All-in-One Course
Year 2022 64
String - JSON
 Syntax
Array of objects
https://en.wikipedia.org/wiki/JSON
AI VIETNAM
All-in-One Course
Year 2022 65
String - JSON
 Example
AI VIETNAM
All-in-One Course
How!!!
Year 2022 66
Data Structure
List
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
 Introduction
 List
 Some algorithms on List
 Addresses
 Common Errors
Outline
Abstract Data Types
AI VIETNAM
All-in-One Course
1
List
4 5 6 7 8 9
data = [4, 5, 6, 7, 8, 9]
index 0 1 2 3 4 5
Strings
‘A’ ‘I’
name =
0 1
index
dictionary_name = {key-1:value-1, …, key-n:value-n}
colon
comma
bracket
element
tuple_name = (element-1, …, element-n)
String
 Create and iterate a string
2
AI VIETNAM
All-in-One Course
Year 2022
A I
name =
0 1
index
name = ‘AI’
List
 A container that can contain elements
3
AI VIETNAM
All-in-One Course
list_name = [element-1, …, element-n]
Year 2022
6 5 7 1 9 2
data =
0 1 2 3 4 5
index
List
AI VIETNAM
All-in-One Course
 Index
4 5 6 7 8 9
data = [4, 5, 6, 7, 8, 9]
Backward
index
-6 -5 -4 -3 -2 -1
data[-1]
9
data[-3]
7
Forward
index
0 1 2 3 4 5
data[0]
4
data[3]
7
 Slicing
4 5 6 7 8 9
data = [4, 5, 6, 7, 8, 9]
Forward
index
0 1 2 3 4 5
6 7
data[2:4]
7 8 9
data[3:]
4 5 6
data[:3]
Year 2022 4
list[start:end:step]
Giá trị mắc định của start là 0, của
end là len(list), và của step là 1
List
AI VIETNAM
All-in-One Course
 Add an element
6 5 7 1 9 2
data =
data.append(4) # thêm 4 vào vị trị cuối list
6 5 7 1 9 2
data = 4
6 5 7 1 9 2
data =
data.insert(0, 4) # thêm 4 vào vị trị có
# index = 0
6 5 7 1 9 2
data = 4
5
List
AI VIETNAM
All-in-One Course
6 5 7 1 9 2
data =
# thay đổi phần tử thứ 1
data[1] = 4
data = 6 4 7 1 9 2
 Updating an element
 Add a list of elements
6 5 7 1
data =
data.extend([9, 2]) # thêm 9 và 2 vào vị trị cuối list
6 5 7 1 9 2
data =
6
List
AI VIETNAM
All-in-One Course
 + and * operators
6 5 7
data1 =
1 9 2
data2 =
# nối 2 list
data = data1 + data2
6 5 7 1 9 2
data =
6 5
data =
# nhân list với một số nguyên
data_m = data * 3
6 5
data_m = 6 5 6 5 7
List
AI VIETNAM
All-in-One Course
 sort() – Sắp xếp các phần tử
6 5 7 1 9 2
data =
data = 1 2 5 6 7 9
data.sort()
6 5 7 1 9 2
data =
data = 9 7 6 5 2 1
data.sort(reverse = True)
8
List
 Deleting an element
AI VIETNAM
All-in-One Course
6 5 7 1 9 2
data =
data.pop(2) # tại vị trí index = 2
6 5 1 9 2
data =
6 5 7 1 9 2
data =
data.remove(5) # xóa phần tử đầu tiên
# có giá trị là 5
6 7 1 9 2
data =
Year 2022 9
List
AI VIETNAM
All-in-One Course
 Delete elements
6 5 7 1 9 2
data =
data.clear()
data = []
6 5 7 1 9 2
data =
# xóa phần tử thứ 1 và 2
del data[1:3]
data = 6 1 9 2
10
List
AI VIETNAM
All-in-One Course
6 5 7 1 9 2
data =
# trả về vị trí của phần tử đầu tiên có giá trị là 9
data.index(9) = 4
index() – Trả về vị trí đầu tiên
reverse() – Đảo ngược vị trí các phần tử
6 5 7 1 9 2
data =
data = 2 9 1 7 5 6
data.reserse()
11
Year 2022
List
AI VIETNAM
All-in-One Course
count() – Trả về số lần xuất hiện
của một phần tử
6 5 7 1 9 2
data =
# trả về số lần phần tử 7 xuất hiện trong list
data.count(7) = 1
copy() – copy một list
6 5 7 1 9 2
data =
data_copy =
data_copy = data.copy()
6 5 7 1 9 2
12
Built-in Functions for List
Year 2022
len(), min(), and max()
6 5 7 1 9 2
data =
# trả về số phần tử
len(data) = 6
# trả về số phần tử có giá trị nhỏ nhất
min(data) = 1
# trả về số phần tử có giá trị lớn nhất
max(data) = 9
13
Công thức Áp dụng cho hàm rời rạc (1D)
Diện tích A
𝑓(𝑥)
𝑥 0 1 2 3 4 5 6 7 8 9
F 3 = ෍
𝑥≤3
𝑓(𝑥) = 𝑓 0 + 𝑓 1 + 𝑓 2 + 𝑓 3
= 1 + 8 + 5 + 7 = 21
F 6 = ෍
𝑥≤6
𝑓(𝑥) = 1 + 8 + 5 + 7 + 3 + 5 + 8 = 37
Diện tích A
A = F 6 − F 3 = ෍
4≤𝑥≤6
𝑓 𝑥 = 3 + 5 + 8 = 16
https://www.mathsisfun.com/calculus/integration-introduction.html
F a = න
−∞
𝑎
𝑓(𝑥)𝑑(𝑥)
F b = න
−∞
𝑏
𝑓 𝑥 𝑑(𝑥)
Diện tích A
𝑓(𝑥) ≥ 0
A = F b − F(a)
Example
AI VIETNAM
All-in-One Course
14
Áp dụng cho hàm rời rạc (1D)
0 1 2 3 4 5 6 7 8 9
𝑥
F 3 = ෍
𝑥≤3
𝑓(𝑥) = 𝑓 0 + 𝑓 1 + 𝑓 2 + 𝑓 3
= 1 + 8 + 5 + 7 = 21
F 6 = ෍
𝑥≤6
𝑓(𝑥) = 1 + 8 + 5 + 7 + 3 + 5 + 8 = 37
Diện tích A
A = F 6 − F 3 = ෍
4≤𝑥≤6
𝑓 𝑥 = 3 + 5 + 8 = 16
F x = 𝑓 𝑥 + F x − 1
F 7 = 𝑓 7 + F 6 = 3 + 37 = 40
Tính chất
Xây dựng integral array dùng tính chất F x = 𝑓 𝑥 + F x − 1
𝑓(𝑥)
0 1 2 3 4 5 6 7 8 9
𝑥
𝐹(𝑥)
+ + + + +
+ + + +
Tính tổng với độ phức tạp ~ O(1)
෍
𝑎≤𝑥≤𝑏
𝑓 𝑥 = F b − F a − 1
෍
4≤𝑥≤6
𝑓 𝑥 = F 6 − F 3 = 37 − 21 = 16
Example
AI VIETNAM
All-in-One Course
15
Built-in Functions
 sorted(aList) – Sắp xếp các phần tử
6 5 7 1 9 2
data =
sorted_data = 1 2 5 6 7 9
sorted_data = sorted(data)
6 5 7 1 9 2
data =
sorted_data = 9 7 6 5 2 1
sorted_data = sorted(data, reverse=True)
sorted(iterable, reverse=reverse)
16
Built-in Functions
sum()
6 5 7 1 9 2
+
result
data =
6 5 7 1 9 2
data =
# tính tổng
sum(data) = 30
𝑠𝑢𝑚𝑚𝑎𝑡𝑖𝑜𝑛 = ෍
𝑖=0
𝑛
𝑑𝑎𝑡𝑎𝑖
Built-in Functions
sum()
6 5 7 1 9 2
+ result
0 1 2 3 4 5
index
data =
6 5 7 1 9 2
data =
# tính tổng
sum(data) = 30
18
Using index
𝑠𝑢𝑚𝑚𝑎𝑡𝑖𝑜𝑛 = ෍
𝑖=0
𝑛
𝑑𝑎𝑡𝑎𝑖
Built-in Functions
zip()
1 2 3
data1 =
Year 2022 19
5 6 7
data2 =
1 5
2 6
3 7
Built-in Functions
reversed()
6 1 7
data =
Year 2022 20
AI VIETNAM
All-in-One Course
7 1 6
reversed(data) =
Built-in Functions
enumerate()
data =
Year 2022
enumerate(data) =
6 1 7
6 1 7
0 1 2
index
21
Examples
AI VIETNAM
All-in-One Course
Sum of even numbers
6 5 7 1 9 2
data =
Sum of elements with even indices
6 5 7 1 9 2
data =
Examples
AI VIETNAM
All-in-One Course
square(aList)
6 5 7 1 9 2
data =
36 25 49 1 81 4
square(data) =
Year 2022 23
List Comprehension
AI VIETNAM
All-in-One Course
Year 2022
omitted
added
24
List Comprehension
Sigmoid
Function
σ 𝑥 =
1
1 + 𝑒−𝑥
σ′(𝑥) = σ(𝑥)(1 − σ(𝑥))
List Comprehension
ReLU
Function
ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
ReLU ′ 𝑥 = ቊ
0 if 𝑥 ≤ 0
1 if 𝑥 > 0
26
List Comprehension
ReLU
Function
ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
ReLU ′ 𝑥 = ቊ
0 if 𝑥 ≤ 0
1 if 𝑥 > 0
27
List Comprehension
AI VIETNAM
All-in-One Course
[condition_to_branch_x for x in data condition_to_filter_x]
List Sorting
AI VIETNAM
All-in-One Course
29
Mutable and Immutable
AI VIETNAM
All-in-One Course
51
30
Year 2022
Algorithms on List
 Linear searching
6 5 7 1 9 2
data =
0 1 2 3 4 5
index
6 5 7 1 9 2
start
Searching for 9
Returning 4
0 1 2 3 4 5
index
6 5 7 1 9 2
start
Searching for 8
Returning ?
0 1 2 3 4 5
index
end
If iterating
the last item
item  getItem()
Returning index
index = -1
31
if item==value,
indexgetIndex()
Algorithms on List
 Sorting using min(), remove(), and append()
Year 2022 32
6 5 7 1 9 2
data =
result = [ ]
min(data) = 1
data.remove(1) = 6 5 7 9 2
result.append(1) = 1
. . .
if the list is
non-empty?
item  getMin()
append(item) to result
remove(item) from list
Algorithms on List
 Sorting using min(), remove(), and append()
Year 2022 33
6 5 7 9 2
data =
result = 1
min(data) = 2
data.remove(2) = 6 5 7 9
result.append(2) = 1
. . .
2
if the list is
non-empty?
item  getMin()
append(item) to result
remove(item) from list
Quizzes
AI VIETNAM
All-in-One Course
Year 2022
Quizzes
AI VIETNAM
All-in-One Course
Year 2022
Quiz 1
Quiz 2
Quiz 3
Converting to List
AI VIETNAM
All-in-One Course
aList  list(iterable)
4 5 6 7 8 9
data = list(range(4, 10)
index 0 1 2 3 4 5
A I
data =
0 1
index
name = ‘AI’
data =
34
Plotting a function
 Using matplotlib
AI VIETNAM
All-in-One Course
35
x-data
y-data
Plotting a function
 Using matplotlib
AI VIETNAM
All-in-One Course
36
How to do it?
𝑥 ∈ −8, 8
𝑦 = 𝑥2
List and File
 Read and Write from/to a log file
AI VIETNAM
All-in-One Course
37
 Introduction
 List
 Some algorithms on List
 Addresses
 Common Errors
Outline
Variables and Addresses
4
AI VIETNAM
All-in-One Course
38
20
x
140707105248672
y
140707105248672
10
x
140707105248352
y
140707105248672
20
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
39
 Immutable types: Cannot be changed in place
 Including ints, floats, strings, and tuples
“AI”
x
1511427632072
“AI”
x
1511427632072
1511427661360
“AI VIETNAM”
destroyed
automatically
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
40
 Immutable types: Cannot be changed in place
 Including ints, floats, strings, and tuples
“AI”
x
1511427633024
y
1511427633024
x
1511427693808
“AI VIETNAM”
“AI”
y
1511427633024
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
41
1 2 3
0 1 2
a_list
1511426884232
1 2 3 4
0 1 2 3
5
4
a_list
1511427661128
4
0
5
1
a_list = a_list +
Year 2022
Variables and Addresses
AI VIETNAM
All-in-One Course
4
42
. . .
0 1 2
a_list
1511426884232
1 2 3
x
a1 = 140707105248064
a2 = 140707105248096
a3 = 140707105248128
a1 a2 a3
a1 a2 a3
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
43
. .
0 1
a_list
1511426884232
1 2
x
a1 = 140707105248064
a2 = 140707105248096
a1 a2
a1 a2
20
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
44
value 3
a1 = 140707105248128
a2 = 140707105248320
square
number
result 9
result
a1
a1
a2 a2
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
45
value 3
a1 = 140707105248128
a2 = 140707105248320
square
number
result 9
result
a1
a1
a2 a2
Year 2022
a1 = 1511427661128
a2 = 140707105248160
square
input_list
number
a2
. . .
0 1 2
a_list
a1
1 2 3
a3 a4 a5
4
46
a1 = 1511428290376
a2 = 140707105248160
square
input_list
number
a2
. . .
0 1 2
a_list
a1
1 2 3
a3 a4 a5
4
.
3
a2
47
Variables and Addresses
4
AI VIETNAM
All-in-One Course
48
add
a_list
number
1 2 3
0 1 2
a_list
address 1
4
address 2
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
49
add
a_list
number
1 2 3
0 1 2
a_list
address 1
4
address 2
1 2 3
0 1 2
4
3
address 3
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
50
add
a_list
number
1 2 3
0 1 2
a_list
address 1
4
address 2
1 2 3
0 1 2
4
3
address 3
Year 2022
Variables and Addresses
4
AI VIETNAM
All-in-One Course
51
1 2 3
0 1 2
a_list
address 1
4
1 2 3
0 1 2
4
3
Year 2022
Mutable and Immutable
AI VIETNAM
All-in-One Course
52
6 5 7 1 9 2
data
36 25 49 1 81 4
result
square
data
data_s
Mutable and Immutable
AI VIETNAM
All-in-One Course
6 5 7 1 9 2
data
6
value
square
data
Get from data[0]
36 5 7 1 9 2
data
36
value*value
square
data
Set to data[0]
53
List Copy
4
AI VIETNAM
All-in-One Course
54
1 2 3 4
0 1 2 3
5
4
list1
1700123138824
Memory address
list2
1700123138824
list2 = list1
1 2 3 4
0 1 2 3
5
4
list1[3] = 9
Replace 4 by 9
1 2 3 9
0 1 2 3
5
4
list1
1700123138824
list2
1700123138824
Year 2022
List Copy
4
AI VIETNAM
All-in-One Course
55
1 2 3 4
0 1 2 3
5
4
list1[3] = 9
Replace 4 by 9
1 2 3 9
0 1 2 3
5
4
list1
1700123139912
list2
1700123139976
1 2 3 4
0 1 2 3
5
4
1 2 3 4
0 1 2 3
5
4
list1
1700123139912
list2
1700123139976
1 2 3 4
0 1 2 3
5
4
list2 = copy.copy(list1)
List Copy
. 3
0 1
1 2
0 1
1700123189704
List1[0][0] = 9
Replace 1 by 9
. 3
0 1
list1
1700123189832
list2
1700123189960
. 3
9 2
0 1
1700123189704
0 1
. 3
0 1
list1
1700123189832
list2
1700123189960
. 3
1 2
0 1
1700123189704
0 1
list2 = copy.copy(list1)
56
. 3
0 1
1 2
0 1
1700124007112
List1[0][0] = 9
Replace 1 by 9
. 3
0 1
list1
1700124007240
9 2
0 1
1700124007112
list2
1700124007176
. 3
0 1
1 2
0 1
1700124007304
. 3
0 1
list1
1700124007240
1 2
0 1
1700124007112
list2
1700124007176
. 3
0 1
1 2
0 1
1700124007304
list2 = copy. deepcopy(list1)
57
Quizzes
AI VIETNAM
All-in-One Course
Year 2022
 Small number caching
Caching integers in [-5, 256]
 Introduction
 List
 Some algorithms on List
 Addresses
 Common Errors
Outline
Common Errors
 Error 1
AI VIETNAM
All-in-One Course
58
Year 2022
Common Errors
 Error 2
AI VIETNAM
All-in-One Course
59
Year 2022
Common Errors
 Error 3
AI VIETNAM
All-in-One Course
60
Year 2022
Common Errors
 Error 4
AI VIETNAM
All-in-One Course
61
Year 2022
Common Errors
 Error 5
AI VIETNAM
All-in-One Course
62
Year 2022
Common Errors
 Error 6
AI VIETNAM
All-in-One Course
63
Year 2022
Common Errors
 Error 7
AI VIETNAM
All-in-One Course
64
Year 2022
Common Errors
 Error 8
AI VIETNAM
All-in-One Course
65
Year 2022
Common Errors
 Error 9
AI VIETNAM
All-in-One Course
66
Year 2022
Common Errors
 Error 10
AI VIETNAM
All-in-One Course
67
Year 2022
Common Errors
 Error 11
AI VIETNAM
All-in-One Course
68
Year 2022
Common Errors
 Error 12
AI VIETNAM
All-in-One Course
69
Year 2022
Common Errors
 Error 13
AI VIETNAM
All-in-One Course
70
Year 2022
Common Errors
 Error 14
AI VIETNAM
All-in-One Course
71
Year 2022
Common Errors
 Error 15
AI VIETNAM
All-in-One Course
72
Year 2022
Common Errors
 Error 16
AI VIETNAM
All-in-One Course
73
Year 2022
Common Errors
 Error 17
AI VIETNAM
All-in-One Course
74
Year 2022
Common Errors
 Error 18
AI VIETNAM
All-in-One Course
75
Year 2022
Common Errors
 Error 19
AI VIETNAM
All-in-One Course
76
Year 2022
Common Errors
 Error 20
AI VIETNAM
All-in-One Course
77
Year 2022
Common Errors
 Error 21
AI VIETNAM
All-in-One Course
78
Year 2022
Common Errors
 Error 22
AI VIETNAM
All-in-One Course
numbers = [1, 2, 3, 4, 5] 1
Output
numbers = [1, 2, 3, 4, 5] 1, 2
Output
numbers = [1, 2, 3, 4, 5] 1, 2, 3
Output
numbers = [1, 2, 3, 4, 5, 3]
79
Year 2022
Common Errors
 Error 22
AI VIETNAM
All-in-One Course
numbers = [1, 2, 3, 4, 5, 3] 1, 2, 3, 4, 5, 3
Output
numbers = [1, 2, 3, 4, 5, 3, 3]
80
Year 2022
Common Errors
 Error 22
AI VIETNAM
All-in-One Course
numbers = [1, 2, 3, 4, 5, 3] 1, 2, 3, 4, 5, 3
Output
numbers = [1, 2, 3, 4, 5, 3, 3] 1, 2, 3, 4, 5, 3, 3
Output
numbers = [1, 2, 3, 4, 5, 3, 3, 3] ° ° °
81
Year 2022
Common Errors
 Error 25
AI VIETNAM
All-in-One Course
Year 2022 82
Common Errors
 Error 26
AI VIETNAM
All-in-One Course
???
Year 2022 83
Common Errors
 Error 27
AI VIETNAM
All-in-One Course
Year 2022 84
Quizzes
AI VIETNAM
All-in-One Course
85
Year 2022
Further Reading
 List (Chapters 6 and 13)
AI VIETNAM
All-in-One Course
86
 Binary Searching and Sorting
Data Structure
Tuple, Set, and Dictionary
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
 Common Errors (Quick Review)
 Tuple
 Set
 Dictionary
 Code Optimization
Outline
Tuple
 Structure
AI VIETNAM
All-in-One Course
tuple_name = (element-1, …, element-n)
Create a tuple Tuple unpacking
Year 2022 1
Tuple
AI VIETNAM
All-in-One Course
tuple_name = (element-1, …, element-n)
( ) can be removed Tuple with one element
Year 2022
 Structure
2
Tuple
 + and * operators
AI VIETNAM
All-in-One Course
index() - tìm vị trí xuất hiện của một giá trị
count() - đếm số lần xuất hiện của một giá trị
Year 2022 3
Tuple
len() - Tìm chiều dài của một tuple
Lấy giá trị min và max của một tuple
Dùng hàm zip() cho tuple
Sắp xếp các giá trị trong một tuple
Year 2022 4
Tuple
 Immutable
5
AI VIETNAM
All-in-One Course
however
Year 2022
1 2 add2
0 1 2
t
add1
3 10
0 1
Tuple Examples
AI VIETNAM
All-in-One Course
Swapping two variables
list2tuple
tuple2list
Memory requirement
Tuple slicing
6
Tuple
 Example: Solve quadratic equation
AI VIETNAM
All-in-One Course
Case 1: delta<0
Case 2: delta>0
Case 3: delta=0
Data is protected
Year 2022 7
 Common Errors (Quick Review)
 Tuple
 Set
 Dictionary
 Code Optimization
Outline
Set
 Create a set
AI VIETNAM
All-in-One Course
Items with different data types
Using curly brackets
Set comprehension
Year 2022 8
Set
AI VIETNAM
All-in-One Course
Access the items of a set Copy a set
Year 2022 9
Set
AI VIETNAM
All-in-One Course
Add an item Insert a set to another set
Join two sets Not allow duplicate values
Year 2022 10
Set
AI VIETNAM
All-in-One Course
difference function
difference_update function
symmetric_difference
symmetric_difference_update
11
Set
AI VIETNAM
All-in-One Course
 Bitwise operator
Year 2022 12
Set
 Remove an item
AI VIETNAM
All-in-One Course
remove(item)
Remove an item from the set.
https://docs.python.org/3/library
/stdtypes.html?t#set
discard(item)
Remove an item from the set if it is present.
Year 2022
Set comprehension
13
Set
AI VIETNAM
All-in-One Course
remove(item)
Remove an item from the set.
Raises KeyError if elem is not contained in the set.
https://docs.python.org/3/library/stdtypes.html?t#set
discard(item)
Remove an item from the set if it is present.
Year 2022
 Remove an item
14
Set
 Create a set
AI VIETNAM
All-in-One Course
Unordered and unindexed Cannot contain unhashable types
Year 2022 15
Set
AI VIETNAM
All-in-One Course
Year 2022
Set  List
and Tuple
???
??? 16
- 50,000 movie review for sentiment analysis (data)
- Consist of: + 25,000 movie review for training
+ 25,000 movie review for testing
- Label: positive – negative = 1 – 1
“A wonderful little production. <br /><br />The filming technique is very unassuming- very old-
time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the
entire piece…..”
positive
“This show was an amazing, fresh & innovative idea in the 70's when it first aired. The first 7 or 8
years were brilliant, but things dropped off after that. By 1990, the show was not really funny
anymore, and it's continued its decline further to the complete waste of time it is today….”
negative
“I thought this was a wonderful way to spend time on a too hot summer weekend, sitting in the air
conditioned theater and watching a light-hearted comedy. The plot is simplistic, but the dialogue is
witty and the characters are likable (even the well bread suspected serial killer)….”
positive
“BTW Carver gets a very annoying sidekick who makes you wanna shoot him the first three
minutes he's on screen.”
negative
Set
AI VIETNAM
AI Course
 Text classification
Set
 Text classification
AI VIETNAM
AI Course
Output
𝑧
Sigmoid
activation
Fully-connected layer
Text
Sample
Preprocessing
(standardization &
vectorization)
Embedding
Preprocessing
Year 2022 18
Embedding
- Example corpus
sample1: ‘We are learning AI’
sample2: ‘AI is a CS topic’
(1) Build vocabulary from corpus
(2) Transform text into features
index 0 1 2 3 4 5 6 7
word pad are/a ai we topic learning is cs
We are learning AI
we are learning ai
Standardize
3 1 5 2 0
AI is a CS topic
ai is a cs topic
2 6 1 7 4
Vectorization
19
Embedding Layer
(3) Embedding layer
index word
0 pad
1 are/a
2 AI
3 We
4 Topic
5 Learning
6 is
7 cs
We are learning AI
3
1
5
2
0
Output
𝑧
Sigmoid
activation
Fully-connected layer
Embedding
20
Set
AI VIETNAM
AI Course
 Convert text to numbers
 Common Errors (Quick Review)
 Tuple
 Set
 Dictionary
 Code Optimization
Outline
Dictionary
AI VIETNAM
All-in-One Course
 Structure
Create a dictionary
dictionary_name = {key-1:value-1, …, key-n:value-n}
colon
comma
bracket
element
Year 2022 22
Dictionary
AI VIETNAM
All-in-One Course
 Create a Dictionary
Year 2022 23
Dictionary
AI VIETNAM
All-in-One Course
 Update a value  Copy a dictionary
Year 2022 24
Dictionary
AI VIETNAM
All-in-One Course
 Hàm copy() chỉ sao chép
kiểu shallow
 Sử dụng hàm deepcopy()
trong module copy
Year 2022 25
Dictionary
AI VIETNAM
All-in-One Course
 Get keys and values
Get keys
Get values
Get keys and values
Get keys
Year 2022 26
Dictionary
AI VIETNAM
All-in-One Course
 Get a value by a key
Get value using get() function Get value and delete the corresponding item
Year 2022 27
Dictionary
AI VIETNAM
All-in-One Course
popitem() - lấy ra một phần tử ở cuối dictionary clear() - xóa tất cả các phần tử của một dictionary
Use del keyword to delete an item
Year 2022 28
Dictionary
AI VIETNAM
All-in-One Course
 Key that does not exist
Try to delete a non-existing item Try to get an item by a non-existing key
Year 2022 29
Dictionary
setdefault() function
4
AI VIETNAM
All-in-One Course
30
example
Result ???
Year 2022
Dictionary
Method 1
4
AI VIETNAM
All-in-One Course
31
Method 2
 Get a value via a key
Year 2022
Dictionary
Merge two dictionaries
AI VIETNAM
All-in-One Course
Check if a key exists
Remove empty items
32
Dictionary comprehension
Dictionary
AI VIETNAM
All-in-One Course
Year 2022 33
 Common error
Dictionary
AI VIETNAM
All-in-One Course
Year 2022 34
 Common error
Dictionary Saving and Loading
 JSON (JavaScript Object Notation)
Year 2021
AI VIETNAM
All-in-One Course
 Data exchange format
 Lightweight
 Text-based
 Language-independent
 Designed to be both human- and machine-readable.
Dictionary Saving and Loading
AI VIETNAM
All-in-One Course
Year 2022 36
Sorting
AI VIETNAM
All-in-One Course
Year 2022 37
sorted(iterable, key=None, reverse=False)
item=7
Sorting
AI VIETNAM
All-in-One Course
Year 2022
item=(‘g’, 13)
38
Sorting
AI VIETNAM
All-in-One Course
Year 2022
item=(‘g’, 13)
a g e
list1 = h b
16 13 18
list2 = 11 15
list3 =
a g e h b
16 13 18 11 15
item
Lambda function
 Take any number of arguments
 Can only have one expression
Year 2022
AI VIETNAM
All-in-One Course
Syntax
lambda arguments : expression
40
Sorting
AI VIETNAM
All-in-One Course item=(‘g’, 13)
Using lambda function
 Common Errors (Quick Review)
 Tuple
 Set
 Dictionary
 Code Optimization
Outline
Code Optimization (1)
 Use built-in functions
AI VIETNAM
All-in-One Course
Tìm các phần tử duy nhất trong list
Tính tổng các phần tử trong list
42
Code Optimization (2)
 Use built-in functions
AI VIETNAM
All-in-One Course
Dùng list comprehension
Đếm số phần tử trong list dùng Counter
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 44
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 45
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 46
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 47
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 48
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 49
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 50
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 51
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 52
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 53
Bad Codes
AI VIETNAM
All-in-One Course
Year 2022 54
Good Code
AI VIETNAM
All-in-One Course
Year 2022 55
Good Code
AI VIETNAM
All-in-One Course
Year 2022 56
Good Code
AI VIETNAM
All-in-One Course
Year 2022 57
Good Code
AI VIETNAM
All-in-One Course
Year 2022 58
 Common Errors (Quick Review)
 Tuple
 Set
 Dictionary
 Code Optimization
Outline
Stack
4
AI VIETNAM
All-in-One Course
59
Year 2022
 Introduction
1
2
3
4
TOP
POP PUSH
LAST IN
FIRST OUT
STACK
2
3
4
1
2
3
4
FULL
STACK
EMPTY
STACK
1
PUSH
2
1
POP PEEK
TOP
STACK OPERATIONS
Stack
4
AI VIETNAM
All-in-One Course
60
Year 2022
Simple
Implementation
TOP=NULL
STEP1
Create Empty Stack
TOP=12
STEP2
PUSH(12)
12 TOP
TOP=8
STEP3
PUSH(8)
12
8 TOP
TOP=21
STEP3
PUSH(21)
12
8
21 TOP
Stack
AI VIETNAM
All-in-One Course
Year 2022
TOP=33
STEP1
Create Stack
12
8
21
33 TOP
TOP=33 TOP=21
12
8
21
33
12
8
21
STEP2
POP()
TOP
TOP=21 TOP=8
12
8
21
12
8
STEP3
POP()
TOP
TOP=8 TOP=12
12
8
12
STEP4
POP()
TOP
Queue
AI VIETNAM
All-in-One Course
 Introduction
Enqueue
Dequeue
Add an element to the end of the queue
Remove an element from the front of the queue
2 4 7 3 5
Enqueue Dequeue
First in – First out
5
Enqueue
3
Enqueue
5
3 5
Dequeue
3
62
Queue
4
AI VIETNAM
All-in-One Course
63
Year 2022
Simple
Implementation
Further Reading
AI VIETNAM
All-in-One Course
Object-Oriented
Programming
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
Reference Books
 Introduction
 Classes and Objects
 Iterator and Class Data Type
 Inheritance
 Exercises
Outline
OOP Introduction
Procedural programming
Year 2022
data 1
data 2
data n
data 3
Function 1
Function 2
Function k
Top-down approach
Security
Maintenance
Reusability
…
Implementation
Implementation
AI VIETNAM
All-in-One Course
1
OOP Introduction
OOP programming
Year 2022
Bottom-up approach
Security
Maintenance
Reusability
Implementation
Access modifiers
Inheritance
Objects/Classes
data 1
Function 1
data 3
Function 2
data n
Function k
Encapsulation
Polymorphism
AI VIETNAM
All-in-One Course
2
Introduction
 What is OOP?
Year 2022
Creating objects that contain both data and functions
Data 1 Data 2 Data n
Task 1
function 1 function 2
Task n
functions
Procedural programming Object-oriented programming
Object 1
Data and
Functions
Object n
Data and
Functions
relationship
Writing functions that perform operations on the data
AI VIETNAM
All-in-One Course
3
Introduction
 OOP advantages
Year 2022
A clear structure
Easier to maintain, modify and debug
Reusable
Doctor Assistant
Waiter
Doctor (struct)
Assistant (struct)
Waiter (struct)
AI VIETNAM
All-in-One Course
4
Introduction
 Classes and Objects
Year 2022
A class is a template for objects, and an object is an instance of a class.
Fruit
Strawberry
Apple
Banana
AI VIETNAM
All-in-One Course
5
Introduction
 Classes and Objects
Year 2022
A class is a template for objects, and an object is an instance of a class.
Animal
Cat
Deer
Tiger
AI VIETNAM
All-in-One Course
6
Introduction
 Classes and Objects
A class is a template for objects, and an object is an instance of a class.
Cat
Japanese Bobtail
Scottish Fold
Calico
AI VIETNAM
All-in-One Course
7
Introduction
 Classes and Objects
https://www.visual-
paradigm.com/guide/uml-unified-modeling-
language/uml-class-diagram-tutorial/
AI VIETNAM
All-in-One Course
8
Classes and Objects
 Abstract view
Year 2022
Cat
Attributes
Functions/
Actions
Name Color Age Sleep Walk Eat
Cat
name
color
age
sleep
walk
eat
Class Diagram
AI VIETNAM
All-in-One Course
9
Class Diagram
 Describe the structure of a system
Classes
their attributes
operations
(methods)
relationships among
objects
Class name
Attributes
Methods
- private
+ public
Access modifiers
A cat includes a name, a color, and an age. The daily activities of the
cat consists of sleeping, walking, and eating.
Draw a class diagram for the above description. All the attributes and
methods are publicly accessed.
3 parts
Cat
+ name: string
+ color: string
+ age: int
+ sleep(): void
+ walk(): void
+ eat(): void
AI VIETNAM
All-in-One Course
10
Year 2022
OOP Introduction
Detect Class
and its
Members
AI VIETNAM
All-in-One Course
Book
+ author: string
+ title: string
+ genre: string
+ price: double
+ date: string
+ publisher: string
+ description: string
…
Year 2022 11
Objects and Classes
 Create a function in a class
AI VIETNAM
All-in-One Course
The __init__() function is called
automatically every time the class
is being used to create a new object.
The self parameter is a reference
to the current instance of the class.
__call__() function: instances behave
like functions and can be called like a
functions.
Year 2022 12
Objects and Classes
 Create a class
Using init() function
Change property values
Year 2022 13
self Keyword
Year 2022
self
int side;
int side;
Must be the first argument of methods
Used to create and access data members
AI VIETNAM
All-in-One Course
14
Classes and Objects
We have a new data type
cat = Cat(‘Calico’, ‘BW’, 2)
create an object
variable
AI VIETNAM
All-in-One Course
For class names
Including words
concatenated
Each word starts with
upper case
For attribute names
Including words
concatenated
Each word starts with
upper case except the
first word
Naming conventions
Cat
+ name: string
+ color: string
+ age: int
…
Year 2022
Exercise
Implementation
Book
+ author: string
+ title: string
+ genre: string
+ price: double
+ date: string
+ publisher: string
+ description: string
…
Implement the Book class
in Python
16
AI VIETNAM
All-in-One Course
Classes and Objects
Back to the Cat example
Cat
+ name: string
…
…
AI VIETNAM
All-in-One Course
Year 2022 17
Classes and Objects
Problem and Solution:
Step 1 – implement getter and setter functions
Cat
+ name: string
…
+ getName(): string
+ setName(string): void
…
- private
+ public
Access modifiers
AI VIETNAM
All-in-One Course
Year 2022
Classes and Objects
Solution: Step 2 – Using private for attributes
Cat
- name: string
…
+ getName(): string
+ setName(string): void
…
- private
+ public
Access modifiers
19
Classes and Objects
Takeaways
Cat
- name: string
- color: string
- age: int
+ getName(): string
+ setName(string): void
+ getColor(): string
+ setColor(string): void
+ getAge(): int
+ setAge(int): void
- private
+ public
Access modifiers
Use the private access modifiers
for typical attributes
Create getter and setter functions
to access protected attributes
Use the public access modifiers
for the getter and setter functions
A cat includes a name, a color, and an age.
AI VIETNAM
All-in-One Course
20
Year 2022
 Introduction
 Classes and Objects
 Iterator and Class Data Type
 Inheritance
 Exercises
Outline
Iterator
AI VIETNAM
All-in-One Course
1 Create iterator using iter()
2 Get value using next()
Year 2022 21
Iterator
AI VIETNAM
All-in-One Course
22
__iter__(): set initialization for the iterator
__next__(): get a value of the iterator
update the state of the iterator
Using raise StopIteration
Iterator
AI VIETNAM
All-in-One Course
Iterator
AI VIETNAM
All-in-One Course
Year 2022
 List
10 next
Data Pointer
Node1
HEAD
20 next
Data Pointer
Node2
30 next
Data Pointer
Node3
NULL
Singly linked list
24
Iterator
AI VIETNAM
All-in-One Course
Year 2022
 List
Iterator
AI VIETNAM
All-in-One Course
Year 2022
 List
10 next
Data Pointer
Node1
HEAD
20 next
Data Pointer
Node2
30 next
Data Pointer
Node3
None
Singly linked list
Lists and Classes
17
Sort a list of numbers
AI VIETNAM
All-in-One Course
27
Lists and Classes
28
Sort a list of squares
AI VIETNAM
All-in-One Course
Year 2022
Lists and Classes
29
Sort a list of squares
AI VIETNAM
All-in-One Course
Year 2022
Class Data Type
Year 2022
A person comprises a name in string and a date of birth. A date
consists of day, month, and year.
Write a function to check if two people have the same name.
Write a function to check if two people have the same date of
birth.
Draw a class diagram and implement in Python
Using a class as a data type
30
AI VIETNAM
All-in-One Course
Class Data Type
Using a class as a data type
A person comprises a name in string
and a date of birth. A date consists of
day, month, and year.
Draw a class diagram and implement
in Python
- name: string
- dateOfBirth: Date
+ describe(): void
Person
- day: int
- month: int
- year: int
+ describe(): void
Date
AI VIETNAM
All-in-One Course
31
Class Data Type
Using a class as a data type
A person comprises a name in string
and a date of birth. A date consists of
day, month, and year.
- name: string
- dateOfBirth: Date
+ describe(): void
Person
- day: int
- month: int
- year: int
+ describe(): void
Date
Using Date as a data type
AI VIETNAM
All-in-One Course
32
Year 2022
Class Data Type
AI VIETNAM
All-in-One Course
Aggregation
Class Data Type
A person comprises a name in
string and a date of birth. A date
consists of day, month, and
year.
Write a function to check if two
people have the same name.
Write a function to check if two
people have the same date of
birth.
Using a class as a data type
- name: string
- dateOfBirth: Date
+ describe(): void
+ checkSameName(string): bool
+ checkSameAge(int): bool
Person
- day: int
- month: int
- year: int
+ describe(): void
Date
- name: string
- dateOfBirth: Date
+ describe(): void
+ checkSameName(string): bool
+ checkSameAge(Date): bool
Person
- day: int
- month: int
- year: int
+ describe(): void
Date
AI VIETNAM
All-in-One Course
Custom MLP for Fashion-MNIST
 ReLU and SGD
Year 2022
784 Nodes
Input layer
Output
1
𝑧1
𝑧10
Softmax
activation
1
ReLU
activation
128 Nodes
Hidden layer
Fully
connect
Fully
connect
10 Nodes
Output layer
28
28
784
flatten data
…
…
AI VIETNAM
All-in-One Course
Custom MLP for Fashion-MNIST
 Custom ReLU
ReLU 𝑥 = ቊ
0 if 𝑥 ≤ 0
𝑥 if 𝑥 > 0
init method
call method
Initialize values/variables
necessary for a class
Forward computation
max(0, x)
AI VIETNAM
All-in-One Course
Year 2022
Custom MLP for Fashion-MNIST
Custom Dense
init method
call method
Initialize values/variables
necessary for a class
Forward computation
𝒛 = 𝒙𝜽
784 Nodes
Input layer
1 1
ReLU
activation
128 Nodes
Hidden layer
Fully
connect
…
num_outputs = 128
input_shape = (None, 784)
𝜽 = 𝜽𝟏 𝜽𝟐 … 𝜽𝟏𝟐𝟖
build method
Do something using the shape
of the input tensors
Result
Custom MLP for
Fashion-MNIST
 Introduction
 Classes and Objects
 Iterator and Class Data Type
 Inheritance
 Exercises
Outline
Inheritance
 Introduction
Year 2022
Mechanism by which one class is allowed to inherit the features
(attributes and methods) of another class.
Subclass: The class that inherits the other class is known as
subclass (a derived class, extended class, or child class).
The subclass can add its own attributes and methods in addition
to the superclass attributes and methods.
Super Class: The class whose features are inherited is known as
superclass (a base class or a parent class).
AI VIETNAM
All-in-One Course
40
Inheritance
Year 2022
 Introduction
Person
- name: string
// …
Employee
- name: string
- annualSalary: double
- yearOfStartingWork: int
- insuaranceNumber: string
// …
AI VIETNAM
All-in-One Course
41
Inheritance
Person
# name: string
// …
Employee
- annualSalary: double
- yearOfStartingWork: int
- insuaranceNumber: string
// …
is
Person
- name: string
// …
Employee
- name: string
- annualSalary: double
- yearOfStartingWork: int
- insuaranceNumber: string
// …
- private
+ public
Access modifiers
# protected
An employee is a person.
Person
Employee
is-a
relationship
AI VIETNAM
All-in-One Course
Inheritance
Inherit attributes and methods
from one class to another
Benefit: Code reusability
Derived class (child) - the class
that inherits from another class
Base class (parent) - the class
being inherited from
DerivedClass(BaseClass)
Animal
# name: string
+ setName(string): void
Cat
// …
is
A cat is an animal.
Animal
Cat
is-a
relationship
AI VIETNAM
All-in-One Course
43
Inheritance
Year 2022
Super Class
Subclass
UMLAnnotation
‘-’ stands for ‘private’
‘#’ stands for ‘protected’
‘+’ stands for ‘public’
What features does a manager inherit?
 Introduction
To extend an existing class
Employee
# name: string
# salary: double
+ computeSalary(): double
Manager
- bonus: double
+ computeSalary(): double
is
AI VIETNAM
All-in-One Course
44
Inheritance
 As a template
Year 2022 https://beginnersbook.com/2013/05/java-abstract-class-method/
A class Animal that has a method sound() and the subclasses of it like Dog,
Lion, Horse, Cat, etc.
Since the animal sound differs from one animal to another, there is no point
to implement this method in parent class.
This is because every child class must override this method to give its own
implementation details, like Lion class will say “Roar” in this method and
Dog class will say “Woof”.
AI VIETNAM
All-in-One Course
45
Inheritance
Year 2022
 As a template
Animal
+ sound(): void
is
Horse
+ sound(): void
Dog
+ sound(): void
Lion
+ sound(): void
AI VIETNAM
All-in-One Course
46
Example
 Implement the two classes below
Math1
+ __init__()
+ isEven(int): bool
+ factorial(int): int
Math2
+ __init__()
+ isEven(int): bool
+ factorial(int): int
+ estimateE(int): double
AI VIETNAM
All-in-One Course
47
Year 2022
Example
Year 2022
Math1
+ __init__()
+ isEven(int): bool
+ factorial(int): int
Implement the two
classes below
AI VIETNAM
All-in-One Course
48
Example
Math2
+ __init__()
+ isEven(int): bool
+ factorial(int): int
+ estimateEuler(int): double
Implement the two classes below
𝑒 = 2.71828
AI VIETNAM
All-in-One Course
Year 2022
Example
Math2
+ __init__()
+ isEven(int): bool
+ factorial(int): int
+ estimateEuler(int): double
Implement the two classes below
𝑒 = 2.71828
AI VIETNAM
All-in-One Course
50
Year 2022
Example
How to reuse an existing class?
Math1
+ __init__()
+ isEven(int): bool
+ factorial(int): int
Math2
+ __init__()
+ isEven(int): bool
+ factorial(int): int
+ estimateEuler(int): double
AI VIETNAM
All-in-One Course
Example
 Inheritance
Year 2022
Math1: super class or
parent class
Math2: child class or
derived class
Child classes can use
the public and protected
attributes and methods
of the super classes.
Math1
+ __init__()
+ isEven(int): bool
+ factorial(int): int
Math2
+ __init__()
+ estimateEuler(int): double
52
AI VIETNAM
All-in-One Course
53
54
Another Example
Employee-Manager Example: Simple requirement
A standard employee of company X includes his/her name and
base salary. For example, Peter is working for X, and his base
salary is 60000$ a year. Implement the Employee class and the
computeSalary() method to compute the final salary for an
employee. The salary for an employee is his/her base salary.
A manager includes his/her name, base salary, and bonus. The final
salary for the manager comprises the base salary and a bonus. For
example, Mary is a manager in the company. Her base salary and
bonus are 60000$ and 20000$ a year, respectively. Yearly, she gets
paid 80000$ a year. Implement the Manager class and the
computeSalary() method to compute the final salary.
AI VIETNAM
All-in-One Course
Year 2022
Employee
- name: string
- salary: double
+ computeSalary(): double
Manager
- name: string
- salary: double
- bonus: double
+ computeSalary(): double
Another Example
Employee-Manager Example (Using inheritance)
A standard employee of company X includes his/her name and base salary. For example,
Peter is working for X, and his base salary is 60000$ a year.
Implement the Employee class and the computeSalary() method to compute the final
salary for an employee. The salary for an employee is his/her base salary.
A manager is an employee who has the name and base salary attributes. However, the
final salary for the manager comprises the base salary and a bonus.
For example, Mary is a manager in the company. Her base salary and bonus are 60000$
and 20000$ a year, respectively. Yearly, she gets paid 80000$ a year.
Implement the Manager class and the computeSalary() method to compute the final
salary.
AI VIETNAM
All-in-One Course
Another Example
Employee-Manager
Employee
# name: string
# salary: double
+ computeSalary(): double
Manager
- bonus: double
+ computeSalary(): double
is
57
Example
 Inheritance recognition
Year 2022
Squares and circles are both examples of
shapes. There are certain questions one can
reasonably ask of both a circle and a square
(such as, ‘what is the area?’ or ‘what is the
perimeter?’) but some questions can be asked
only of one or the other but not both (such as,
‘what is the length of a side?’ or ‘what is the
radius?’)
Square
- side: int
+ perimeter(): double
+ area(): double
Circle
- radius: double
+ perimeter(): double
+ area(): double
AI VIETNAM
All-in-One Course
58
Example
 Inheritance recognition
Square
- side: int
+ __init__(int)
Circle
- radius: double
+ __init__(double)
Shape
+ perimeter(): double
+ area(): double
is
Shape does not know how to
compute its perimeter and area
Use @abstractmethod to ask its
child to implement them
Using pass in the abstract method
AI VIETNAM
All-in-One Course
Year 2022
Example
 Inheritance recognition
AI VIETNAM
All-in-One Course
60
Example
 Inheritance recognition
AI VIETNAM
All-in-One Course
Year 2022
Example
 Inheritance recognition
AI VIETNAM
All-in-One Course
Year 2022
Example
 Exercise
Square
- side: int
+ __init__(int)
Circle
- radius: double
+ __init__(double)
Shape
+ perimeter(): double
+ area(): double
is
Rectangle
- height: int
- width: int
+ __init__(int, int)
AI VIETNAM
All-in-One Course
Overriding
Year 2022
AI VIETNAM
All-in-One Course
Overriding
66
Employee
- name: string
- salary: double
+ computeSalary(): double
Manager
- bonus: double
+ computeSalary(): double
is
Overriding is a feature that
allows a child class to provide
a specific implementation of a
method that is already
provided by its super-class.
Overriding
Example
Doctor
+ perform(): void
Student
+ perform(): void
Person
+ perform(): void
is
AI VIETNAM
All-in-One Course
Vector
- x: int
- y: int
+ __init__(int, int)
+ add(Vector): void
+ dotProduct(Vector): int
+ check(Vector): bool
A vector in 2D includes x and y.
1) Implement a constructor with no
parameters. This constructors set 1
to x and y.
2) Implement a constructor with two
parameters x and y.
3) Implement a destructor
4) Write a method to compute the
addition between a vector and
another vector
5) Write a method to compute the dot
product between two vectors.
6) Check if two vectors are the same
Exercise Ԧ
𝑥 =
2
3
Ԧ
𝑦 =
4
2
Ԧ
𝑦
Ԧ
𝑥
Ԧ
𝑣 =
3
3
+ Ԧ
𝑦 =
7
5
Ԧ
𝑣
𝑢 =
4
4
+ Ԧ
𝑥 =
6
7
𝑢
x. y = ෍
1
𝑛
𝑥𝑖𝑦𝑖
Dot Product
Advanced Python
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
 Exception
 Iterator
 Generator
 Decorator
 Text Libraries
 Sound Libraries
Outline
Try/Catch
 Used in functions
Year 2022
AI VIETNAM
All-in-One Course
1
Try/Catch
 Exception Handling
Year 2022
AI VIETNAM
All-in-One Course
Code in try Code in catch
Something
wrong
Code after
try/catch
2
Try/Catch
 Exception Handling
Year 2022
AI VIETNAM
All-in-One Course
Code in try Code in catch
Something
wrong
Code in finally
Code after
try/catch
3
Try/Catch
Year 2022
AI VIETNAM
All-in-One Course
Code in try Code in catch
Something
wrong
Code in finally
Code after
try/catch
4
 Exception Handling
Try/Catch
Year 2022
AI VIETNAM
All-in-One Course
Code in try Code in catch
Something
wrong
Code in finally
Code after
try/catch
5
 Exception Handling
Exception in Python
AI VIETNAM
All-in-One Course
6
https://chercher.tech/python-programming/python-exception-handling
Common Exceptions
 KeyError
 FileNotFoundError
 IndexError
7
Common Exceptions
 ZeroDivisionError
Year 2022
AI VIETNAM
All-in-One Course
8
 OverflowError
Common Exceptions
 ValueError
Year 2022 9
 NameError
 SyntaxError
Common Exceptions
 IndentationError
Year 2022
AI VIETNAM
All-in-One Course
 TypeErrors
10
Common Exceptions
 StopIteration
Year 2022
AI VIETNAM
All-in-One Course
11
PermissionError
Year 2022
EOFError
Common Exceptions
AI VIETNAM
All-in-One Course
hit Ctrl+D while waiting for input from users
12
Iterator
4
AI VIETNAM
All-in-One Course
Year 2022 13
 Introduction
Iterator
4
AI VIETNAM
All-in-One Course
 Range and Iterator
Year 2022 14
Iterator
4
AI VIETNAM
All-in-One Course
Year 2022 15
 Range and Iterator
Iterator
4
16
AI VIETNAM
All-in-One Course
Year 2022
 Range and Iterator
Iterator
4
17
AI VIETNAM
All-in-One Course
Year 2022
 Range and Iterator
Iterator
4
18
AI VIETNAM
All-in-One Course
Year 2022
 List and Iterator
Iterator
4
19
AI VIETNAM
All-in-One Course
 List and Iterator
Year 2022
Iterator
4
20
AI VIETNAM
All-in-One Course
 Tuple and Iterator
Year 2022
Iterator
4
21
AI VIETNAM
All-in-One Course
 Tuple and Iterator
Year 2022
Iterator
4
22
AI VIETNAM
All-in-One Course
 String and Iterator
Year 2022
Iterator
4
23
AI VIETNAM
All-in-One Course
Year 2022
 String and Iterator
Iterator
4
24
AI VIETNAM
All-in-One Course
 Set and Iterator
Year 2022
Iterator
4
25
AI VIETNAM
All-in-One Course
Year 2022
 Set and Iterator
Iterator
4
26
AI VIETNAM
All-in-One Course
 Dictionary and Iterator
Year 2022
Iterator
4
27
AI VIETNAM
All-in-One Course
 Dictionary and Iterator
Year 2022
Iterator
4
Year 2022
AI VIETNAM
All-in-One Course
28
1 Create iterator using iter()
2 Get value using next()
Iterator
4
Year 2022
AI VIETNAM
All-in-One Course
29
 Classes and Iterator
Iterator
4
Year 2022
AI VIETNAM
All-in-One Course
30
1 Implement iter()
2 Implement next()
3 Raise StopIteration
Iterator
4
Year 2022
AI VIETNAM
All-in-One Course
31
Iterator
4
Year 2022
AI VIETNAM
All-in-One Course
32
Iterator
4
Year 2022
AI VIETNAM
All-in-One Course
33
“A wonderful little production. <br /><br />The filming technique is very unassuming- very old-
time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the
entire piece…..”
positive
“This show was an amazing, fresh & innovative idea in the 70's when it first aired. The first 7 or 8
years were brilliant, but things dropped off after that. By 1990, the show was not really funny
anymore, and it's continued its decline further to the complete waste of time it is today….”
negative
“I thought this was a wonderful way to spend time on a too hot summer weekend, sitting in the air
conditioned theater and watching a light-hearted comedy. The plot is simplistic, but the dialogue is
witty and the characters are likable (even the well bread suspected serial killer)….”
positive
“BTW Carver gets a very annoying sidekick who makes you wanna shoot him the first three
minutes he's on screen.”
negative
Iterator
Year 2022
 For large datasets
Features Label
Iterator
 For large datasets
dataset
a chunk
a chunk
a chunk
a chunk
A whole dataset does not fit the
memory, but a chunk does
From Iterator to Generator
4
Year 2022
AI VIETNAM
All-in-One Course
34
Iterator Generator
Generator
4
Year 2022
AI VIETNAM
All-in-One Course
34
Generator
4
Year 2022
AI VIETNAM
All-in-One Course
35
Generator
4
Year 2022
AI VIETNAM
All-in-One Course
36
 Create a generator
Generator
 For large datasets
dataset
a chunk
a chunk
a chunk
a chunk
A whole dataset does not fit the
memory, but a chunk does
 Exception
 Iterator
 Generator
 Decorator
 Text Libraries
 Sound Libraries
Outline
Inner Functions
4
Year 2022
AI VIETNAM
All-in-One Course
37
 Functions as variables
Decorator
Year 2022
AI VIETNAM
All-in-One Course
 Motivation
𝑦 = 𝑎𝑥2 + 𝑏𝑥 + 𝑐
∆= 𝑏2 − 4𝑎𝑐
…
Decorator
Year 2022
AI VIETNAM
All-in-One Course
 Motivation
𝑦 = 𝑎𝑥2 + 𝑏𝑥 + 𝑐
∆= 𝑏2 − 4𝑎𝑐
…
How to add the constraint without
modifying the existing code?
𝑎 ≠ 0
A constraint
Decorator
 Solution 1
Decorator
 Solution 2
 A function as an argument
Decorator
 Solution 3
Decorator
 Solution 3
Walrus Operator
4
Year 2022
AI VIETNAM
All-in-One Course
45
 Variable assignments inside
of larger expressions
data
expected length is 5 Truncate
padding
if shorter
if longer
Walrus Operator
4
Year 2022
AI VIETNAM
All-in-One Course
46
 Variable assignments inside
of larger expressions
data
expected length is 5 Truncate
padding
if shorter
if longer
Walrus Operator
4
Year 2022
AI VIETNAM
All-in-One Course
47
 Variable assignments inside of larger expressions
Generate random numbers until getting 5
Walrus Operator
4
Year 2022
AI VIETNAM
All-in-One Course
48
 Variable assignments inside of larger expressions
Generate random numbers until getting 5
 Exception
 Iterator
 Generator
 Decorator
 Text Libraries
 Sound Libraries
Outline
Natural Language Processing
 Introduction
Year 2022
AI VIETNAM
All-in-One Course
www.sneakernews.ml 49
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022 Practical Natural Language Processing by Sowmya Vajjala, Bodhisattwa Majumder, Anuj Gupta, Harshit Surana 50
NLPApplications
AI VIETNAM
All-in-One Course
Practical Natural Language Processing by Sowmya Vajjala,
Bodhisattwa Majumder, Anuj Gupta, Harshit Surana
51
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022 https://www.mygreatlearning.com/blog/trending-natural-language-processing-applications/ 52
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
 Text Classification
https://codeit.us/blog/nlp-applications-in-business 53
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
https://codeit.us/blog/nlp-applications-in-business
https://monkeylearn.com/text-classification/
 Text Classification
Topic Labeling
Sentiment Analysis
54
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022 https://monkeylearn.com/text-classification/
 Text Classification
Intent Detection
Language Detection
55
NLPApplications
AI VIETNAM
All-in-One Course
https://www.slideserve.com/london/natural-language-processing-information-extraction-cse-573-dan-weld
 Information Extraction IE Pipeline
56
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
 Information Extraction
57
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022 https://mobidev.biz/blog/natural-language-processing-nlp-use-cases-business
 Information Extraction
58
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022 https://mobidev.biz/blog/natural-language-processing-nlp-use-cases-business
 Information Extraction
59
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022 Practical Natural Language Processing by Sowmya Vajjala, Bodhisattwa Majumder, Anuj Gupta, Harshit Surana
 Conversational Agents (Chatbots)
61
NLPApplications
 Conversational Agents (Chatbots)
Recipe Recommendations
Dialog Systems in Detail
Practical Natural Language Processing by Sowmya Vajjala,
Bodhisattwa Majumder, Anuj Gupta, Harshit Surana
63
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
 Topics in Brief
1. Spelling correction
2. Snippet extraction: All the search
results show a text snippet involving
the query.
3. Biographical information extraction
4. Search results classification: all,
news, images, videos
1
2
3
4
Search and Information Retrieval
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
 Topics in Brief
https://mobidev.biz/blog/natural-language-processing-nlp-use-cases-business 65
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
 Topics in Brief
https://techcommunity.microsoft.com/t5/ai-customer-engineering-team/bootstrap-your-text-summarization-solution-with-the-latest/ba-p/1268809 66
NLPApplications
AI VIETNAM
All-in-One Course
Year 2022
 Topics in Brief
https://www.studytonight.com/post/different-machine-translation-models-in-nlp
https://www.analyticsvidhya.com/blog/2019/01/neural-machine-translation-keras/
Machine Translation
68
Text Libraries
❖ Underthesea Library
Open-source Vietnamese Natural Language Process Toolkit
🔨 Installation:
📝 Description:
 A Vietnamese NLP toolkit: API for apply some pretrained NLP models.
 A Pytorch library: backed by Pytorch libraray.
 A open-source software
source: https://github.com/undertheseanlp/underthesea
AI VIETNAM
All-in-One Course
69
Text Libraries
❖ Underthesea Library: Usages
source: https://github.com/undertheseanlp/underthesea
😳 Syntax: underthesea.pos_tag(sentence)
Input:
• sentence: raw sentence (unicode, str)
Output:
• tokens: list of tuple with word, pos tag
🌟 POS Tagging
AI VIETNAM
All-in-One Course
70
Text Libraries
🌟 Text Classification
source: https://github.com/undertheseanlp/underthesea
😳 Syntax: underthesea.classify(X)
Input:
• X: raw sentence (unicode, str)
Output:
• tokens: list categories of sentence
Articles
Text
Classification
technology
finance
social science
Output
Input
AI VIETNAM
All-in-One Course
71
❖ Underthesea Library: Usages
Text Libraries
🌟 Sentiment Analysis
source: https://github.com/undertheseanlp/underthesea
😳 Syntax: underthesea.sentiment(X)
Input:
• X: raw sentence (unicode, str)
Output:
• labels: sentiment of sentence
Sentiment
Analysis
Sentiment
category
Output
Input
Text
AI VIETNAM
All-in-One Course
72
❖ Underthesea Library: Usages
Text Libraries
❖ translate Library
source: https://pypi.org/project/translate/
🔨 Installation:
A simple yet powerful command line translator with google translate behind it
AI VIETNAM
All-in-One Course
73
Text Libraries
source: https://pypi.org/project/translate/
😳 Syntax: translate.Translator.translate(X)
Input:
• X: raw sentence (unicode, str)
Output:
• y: translated sentence
Machine
Translation
Output
Input
Text in
English
Text in
Vietnamese
🌟 Machine Translation
AI VIETNAM
All-in-One Course
74
❖ translate Library
Text Libraries
❖ googletrans Library
source: https://pypi.org/project/googletrans/
🔨 Installation:
A free and unlimited python library that implemented Google Translate API
AI VIETNAM
All-in-One Course
75
Text Libraries
😳 Syntax: googletrans.Translator.translate(text)
Input:
• text: raw text (unicode, str)
Output:
• <class 'googletrans.models.Translated'>
Machine
Translation
Output
Input
Text in
English
Text in
Vietnamese
source: https://pypi.org/project/googletrans/
🌟 Machine Translation
AI VIETNAM
All-in-One Course
76
❖ googletrans Library
Text Libraries
❖ newspaper3k Library
🔨 Installation:
Amazing Python library for extracting & curating articles
source: https://newspaper.readthedocs.io/en/latest/
AI VIETNAM
All-in-One Course
78
Text Libraries
😳 Syntax: newspaper.Article
Input:
• url: article’s url (str)
Output:
• <class 'newspaper.article.Article'>
Crawl data
system
Output
Input
Article’s url Article (str)
source: https://newspaper.readthedocs.io/en/latest/
🌟 Text crawler
AI VIETNAM
All-in-One Course
79
❖ newspaper3k Library
Text Libraries
❖ gensim Library
🔨 Installation:
A Python library for topic modelling, document indexing and similarity retrieval
with large corpora
source: https://radimrehurek.com/gensim/
AI VIETNAM
All-in-One Course
80
Text Libraries
😳 Syntax: gensim.summarization.summarize(text, ratio=0.2)
Input:
• text: article text (str)
• ratio: the propotion of the number of sentences of the original text to be chosen for the summary
Output:
• Most representative sentences of the given text
Text
Summarization
Output
Input
Article
Summary
text
source: https://radimrehurek.com/gensim/
AI VIETNAM
All-in-One Course
81
❖ gensim Library
 Exception
 Iterator
 Generator
 Decorator
 Text Libraries
 Sound Libraries
Outline
https://research.aimultiple.com/voice-recognition-applications/
https://www.syndacast.com/google-voice-search-users-and-how-they-use-it/
Using voice assistant to search for stuff on the Internet has now become the ideal way of searching for 71% of participants
in a PWC survey
Voice search
82
Voice to text
58% of respondents claimed to text their friends by using voice assistant, rather than to physically type. Source: PWC
http://www.hoanvusolutions.com.vn/phan-mem-speech-recognition-cho-ios/
https://research.aimultiple.com/voice-recognition-applications/
https://viblo.asia/p/machine-learning-that-thu-vi-6-nhan-dien-giong-noi-1Je5E8DylnL 84
Voice commands to smart home devices
https://ebusinessinstitute.com/voice/
Dummy-Based Anonymization for Voice-Controlled IoT Devices, Katrin Winkler and Erik Buchmann
https://fptshop.store/tuya-wifi-ir-remote-control-for-smart-home-infrared-universal-remote-control-for-alexa-and-google-home-l1462654249.html 85
https://www.247.ai/products/voices
https://voximplant.com/blog/4-ivr-strategies-that-take-your-customer-calls-from-good-to-great
Interactive Voice Response
86
https://www.ivrtechgroup.com/ivr/what-is-interactive-voice-response-ivr
Interactive Voice Response
87
Voice
biometrics
for security
Pal, Gregory. (2016). Voice of the
people: The case for biometrics in
government. Biometric Technology
Today. 2016. 5-7. 10.1016/S0969-
4765(16)30087-X.
Voice recognition
authentication
system
Speech Libraries
❖ librosa Library
🔨 Installation:
A python package for music and audio analysis
source: https://librosa.org/doc/latest/index.html
AI VIETNAM
All-in-One Course
89
Text Libraries
❖ librosa Library: Usages
😳 Syntax: librosa.load(filename, sr=22050)
Input:
• filename: filepath of .wav soundfile
Output:
• data: sound datapoints (in time-domain)
• sr: sampling rate of the sound
Speech Reader
Input
source: https://librosa.org/doc/main/generated/librosa.load.html
🌟 Sound reader
AI VIETNAM
All-in-One Course
90
Text Libraries
😳 Syntax: librosa.feature.melspectrogram(y, sr)
Input:
• y: audio datapoints
• sr: sampling rate of audio
Output:
• S: vector of mel spectrogram
Mel
spectrogram
converter
Input
Audio data points,
sampling rate
🌟 Mel spectrogram converter
source: https://librosa.org/doc/main/generated/librosa.feature.melspectrogram.html
AI VIETNAM
All-in-One Course
91
❖ librosa Library: Usages
Speech Libraries
❖ SpeechRecognition Library
🔨 Installation:
Library for performing speech recognition, with support for several engines and
APIs, online and offline
source: https://pypi.org/project/SpeechRecognition/
AI VIETNAM
All-in-One Course
94
Text Libraries
😳 Syntax: speech_recognition.Recognizer.recognize_google(audio, language)
Input:
• audio: audio data (AudioData class)
• language: input audio language
Output:
• text: transcribed text (str)
Automatic
Speech
Recognition
Input
🌟 Automatic Speech Recognition
Output
Transcribed
text
source: https://pypi.org/project/SpeechRecognition/
AI VIETNAM
All-in-One Course
95
❖ SpeechRecognition Library
Speech Libraries
❖ gTTS Library
🔨 Installation:
A Python library and CLI tool to interface with Google Translate’s text-to-speech
API.
source: https://pypi.org/project/gTTS/
AI VIETNAM
All-in-One Course
96
Text Libraries
😳 Syntax: gTTS(content, lang)
Input:
• content: a string
• lang: spoken language
Output: <class 'gtts.tts.gTTS'>
Text to Speech
Input
🌟 Text to Speech
Output
source: https://pypi.org/project/gTTS/
Text
AI VIETNAM
All-in-One Course
97
❖ gTTS Library
Advanced Python
Data Loading and Saving
Year 2022
Quang-Vinh Dinh
Ph.D. in Computer Science
AI VIETNAM
All-in-One Course
 XML
 JSON
 Tabular Data
 Image Data
 Some important libs
Outline
XML
 eXtensible Markup Language
 Designed to store and transport data
 Designed to be both human- and machine-readable.
Year 2022 1
AI VIETNAM
All-in-One Course
XMLApplication
VOC2007 Dataset
20 categories
Year 2022
Person: person
Animal: bird, cat, cow, dog, horse, sheep
Vehicle: aeroplane, bicycle, boat, bus, car, motorbike, train
Indoor: bottle, chair, dining table, potted plant, sofa, tv/monitor
VOC2007 Dataset
 Example
3
Year 2022
Image labelling Tool
XML
 Example
Year 2022
AI VIETNAM
All-in-One Course
To
Address
Body
XML
Year 2022 6
AI VIETNAM
All-in-One Course
 Example
author
title
publisher
XML
 Syntax
Year 2022
XML Prologue
Attribute
AI VIETNAM
All-in-One Course
7
XML
Year 2022
Element
Opening tag
Closing tag
AI VIETNAM
All-in-One Course
8
 Syntax
XML
 Syntax
 All elements must be properly nested within each other
 XML Tags are Case Sensitive
Year 2022
https://codebeautify.org/xmlvalidator
AI VIETNAM
All-in-One Course
9
XML
 XML documents form a tree structure
Year 2022 https://www.w3schools.com/xml/xml_tree.asp
AI VIETNAM
All-in-One Course
XML
 XMLAttribute
 XML Element
 Text
 Attributes
 Other elements
 Mix of the above
Year 2022
AI VIETNAM
All-in-One Course
8
11
Element
Attribute
Text
Mix
XML
 XML Elements vs. Attributes
Year 2022
AI VIETNAM
All-in-One Course
9
12
Element
Attribute
Which one is better?
XML
Year 2022 13
https://www.w3schools.com/xml/xml_attributes.asp
AI VIETNAM
All-in-One Course
 XML Elements vs. Attributes
Element
Attribute
XML in Python
 xml.etree.ElementTree
Year 2022 14
Root element
<letter>
Element
<to>
Text
John
Element
<from>
Text
Mary
Element
<heading>
Text
Greeting
Element
<body>
Text
…
XML in Python
Year 2022 15
Root element
<letter>
Element
<to>
Element
<from>
Element
<heading>
Element
<body>
Text
John
Text
Mary
Text
Greeting
Text
…
[0] [1] [2] [3]
[0]
[3]
.text .text
XML in Python
Year 2022 16
Root element
<letter>
Element
<to>
Element
<from>
Element
<heading>
Element
<body>
Text
John
Text
Mary
Text
Greeting
Text
…
find('to')
find('body')
.text .text
XML in Python
 xml.etree.ElementTree
Year 2022 17
Read from a file
Get root element
AI VIETNAM
All-in-One Course
XML in Python
 xml.etree.ElementTree
Year 2022 18
AI VIETNAM
All-in-One Course
XML in Python
 xml.etree.ElementTree
Year 2022 19
XML in Python
Year 2022 20
Root element
<letter>
Element
<date>
Element
<body>
Text
…
find(‘date')
Element
<day>
Element
<month>
Element
<year>
Text
19
Text
7
Text
2020
find(‘body')
XML in Python
Year 2022 21
Root element
<letter>
Element
<date>
Element
<body>
Text
…
find(‘day')
Element
<day>
Element
<month>
Element
<year>
Text
19
Text
7
Text
2020
find(‘body')
Year 2022
XML in Python
Year 2022 22
Root element
<letter>
Element
<date>
Element
<body>
Text
…
find(‘day')
Element
<day>
Element
<month>
Element
<year>
Text
19
Text
7
Text
2020
find(‘body')
find(‘date')
XML in Python
Year 2022 23
Root element
<company>
Element
<staff>
Element
< staff >
…
…
Element
<name>
Element
<salary>
Attribute
id=“1001”
Text
John
Text
100
XML in Python
24
Root element
<company>
Element
<staff>
Element
< staff >
…
…
Element
<name>
Element
<salary>
Attribute
id=“1001”
Text
John
Text
100
find(‘staff')
get(‘id')
find(‘name')
XML in Python
25
Root element
<company>
Element
<staff>
Element
< staff >
…
…
Element
<name>
Element
<salary>
Attribute
id=“1001”
Text
John
Text
100
findall(‘staff')
XML in Python
26
Root element
<company>
Element
<staff>
Element
< staff >
…
…
Element
<name>
Element
<salary>
Attribute
id=“1001”
Text
John
Text
100
find(‘name')
findall(‘staff')
get(‘id')
XML in Python
 Example
27
Root element
<company>
Element
< staff >
Element
<firstname>
Text
John
Element
<staff>
Attribute
id=“1001”
Element
<nickname>
Text
Stone
Element
<lastname>
Text
Smith
Element
<salary>
Text
100000
Attribute
currency=“USD”
XML in Python
 Example
28
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Element
<nickname>
Text
John
Text
Smith
Attribute
id=“1001”
Element
<salary>
Text
100000
Text
Stone
Attribute
currency=“USD”
Year 2022
AI VIETNAM
All-in-One Course
Using find()
XML in Python
 Example
Year 2022 29
AI VIETNAM
All-in-One Course
XML in Python
 Example
Year 2022 30
XML in Python
Year 2022 31
AI VIETNAM
All-in-One Course
 Example
XML in Python
Year 2022 32
 Example
XML in Python
 Save an XML document
Year 2022 33
AI VIETNAM
All-in-One Course
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
Element
<firstname>
Element
<lastname>
Text
Peter
Text
White
XML in Python
Year 2022 34
AI VIETNAM
All-in-One Course
Root element
<company>
Element
<staff>
 Save an XML document
XML in Python
Year 2022 35
AI VIETNAM
All-in-One Course
Root element
<company>
Element
<staff>
 Save an XML document
XML in Python
 Save an XML document
Year 2022 36
Root element
<company>
Element
<staff>
Element
<firstname>
XML in Python
 Save an XML document
Year 2022 37
Root element
<company>
Element
<staff>
Element
<firstname>
Text
John
XML in Python
 Save an XML document
Year 2022 38
Root element
<company>
Element
<staff>
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
XML in Python
 Save an XML document
Year 2022 39
Root element
<company>
Element
<staff>
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
XML in Python
 Save an XML document
Year 2022 40
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
XML in Python
 Save an XML document
Year 2022 41
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
XML in Python
 Save an XML document
Year 2022 42
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
Element
<firstname>
Text
Peter
XML in Python
 Save an XML document
Year 2022 43
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
Element
<firstname>
Element
<lastname>
Text
Peter
Text
White
XML in Python
Year 2022 44
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 45
Root element
<company>
Element
<staff>
Element
< staff >
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
Element
<firstname>
Element
<lastname>
Text
Peter
Text
White
Attribute
id=“1001”
Attribute
currency=“USD”
 Save an XML document
XML in Python
Year 2022 46
Root element
<company>
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 47
Root element
<company>
Element
<staff>
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 48
Root element
<company>
Element
<staff>
Attribute
id=“1001”
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 49
Root element
<company>
Element
<staff>
Attribute
id=“1001”
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 50
Root element
<company>
Element
<staff>
Element
<firstname>
Text
John
Attribute
id=“1001”
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 51
Root element
<company>
Element
<staff>
Element
<firstname>
Element
<lastname>
Text
John
Text
Smith
Attribute
id=“1001”
AI VIETNAM
All-in-One Course
 Save an XML document
XML in Python
Year 2022 52
 Save an XML document
XML in Python
AI VIETNAM
All-in-One Course
 XML and Dictionary
52
 XML
 JSON
 Tabular Data
 Image Data
 Some important libs
Outline
JSON
 JSON (JavaScript Object Notation)
 Data exchange format
 Lightweight
 Text-based
 Language-independent
 Designed to be both human- and machine-readable.
Year 2022 1
AI VIETNAM
All-in-One Course
53
JSON
 Example
Year 2022 2
AI VIETNAM
All-in-One Course
54
JSON
Year 2022 3
AI VIETNAM
All-in-One Course
 Example
55
JSON
Year 2022 4
AI VIETNAM
All-in-One Course
 Example
56
JSON
Year 2022 6
AI VIETNAM
All-in-One Course
 Example
57
JSON
 Syntax
Year 2022
Object
A pair
7
AI VIETNAM
All-in-One Course
58
JSON
Year 2022
Object
https://en.wikipedia.org/wiki/JSON
8
AI VIETNAM
All-in-One Course
 Syntax
59
JSON
Year 2022
Array of objects
https://en.wikipedia.org/wiki/JSON
9
AI VIETNAM
All-in-One Course
 Syntax
60
JSON
 Syntax
 Validator
Year 2022 61
https://jsonlint.com/
AI VIETNAM
All-in-One Course
JSON in Python
 Example
 Read JSON
Year 2022 62
AI VIETNAM
All-in-One Course
JSON in Python
 Example
 Save JSON data
Year 2022 63
AI VIETNAM
All-in-One Course
 XML
 JSON
 Tabular Data
 Image Data
 Some important libs
Outline
Important Packages
Year 2022
AI VIETNAM
All-in-One Course
1 2 3
Axis 0
Axis 0
Axis 1
1 2
3 4
5 6
 Numpy is a Python library
 For scientific computations
 Numpy array Tensor in Tensorflow and Pytorch
 Numpy arrays are multi-dimensional arrays
1D array 2D array
1 2
4 5
7 8
3
6
9
Axis 0
Axis 1
Axis 2
3D array
64
Important Packages
 Create Numpy array
 From List
5
Year 2022
AI VIETNAM
All-in-One Course
2
1
2
0
1
2 3
data
1
data 0
data 1
arr_np = np.array(python_list)
65
6
Important Packages
 Common attributes in Numpy
 dtype: data type
 shape: return a tuple of #elements in each dimension
 ndim: return #dimensions
Year 2022
AI VIETNAM
All-in-One Course
1 2 3
Axis 0
shape=(3,)
ndim=1
Axis 0
Axis 1
1 2
3 4
5 6
shape=(3,2)
ndim=2
1 2
4 5
7 8
3
6
9
Axis 0
Axis 1
Axis 2
shape=(3,3,2)
ndim=2
dtype example
66
Important Packages
 matplotlib package
Year 2022 67
AI VIETNAM
All-in-One Course
Important Packages
 Tabular data
Year 2022 68
AI VIETNAM
All-in-One Course
Features Label
Advertising data
Important Packages
 Tabular data
Year 2022
AI VIETNAM
All-in-One Course
Boston House Price Data
Features Label
Important Packages
Year 2022
 Google Colab and Drive
https://colab.research.google.com/drive/1YrU4un
s_kH9BVRDovBe8nI53qRCWd4sT?usp=sharing
 XML
 JSON
 Tabular Data
 Image Data
 Some important libs
Outline
Image Data
 Grayscale images
4
Year 2022
AI VIETNAM
All-in-One Course
71
(Height, Width)
Pixel p = scalar
0 ≤ p ≤ 255
Resolution: #pixels
Resolution = HeightxWidth
Image Data
 Color images
4
Year 2022
AI VIETNAM
All-in-One Course
72
(Height, Width, channel)
Pixel p=
𝑟
𝑔
𝑏
0 ≤ r,g,b ≤ 255
RGB color image Resolution: #pixels
Resolution = HeightxWidth
Important Packages
 PIL Image
Year 2022 73
AI VIETNAM
All-in-One Course
Important Packages
Year 2022 74
AI VIETNAM
All-in-One Course
 PIL Image
Important Packages
Year 2022 75
AI VIETNAM
All-in-One Course
 PIL Image
Important Packages
Year 2022 76
AI VIETNAM
All-in-One Course
 PIL Image
Important Packages
77
AI VIETNAM
All-in-One Course
Year 2022
 matplotlib package
Image Data
 Cat-Dog dataset
6
Year 2022
AI VIETNAM
All-in-One Course
cats_and_dogs
train
validation
cat
dog
cat
dog
78
Important Packages
Year 2022 79
AI VIETNAM
All-in-One Course
Cat-Dog Dataset
 Cat-Dog dataset
Important Packages
Year 2022 80
AI VIETNAM
All-in-One Course
 Cat-Dog dataset
Important Packages
 tqdm package
Year 2022 81
AI VIETNAM
All-in-One Course
Important Packages
Year 2022 82
AI VIETNAM
All-in-One Course
In Machine Learning
 matplotlib package
Important Packages
 Image matching: Applications
Year 2022 83
AI VIETNAM
All-in-One Course
https://pyimagesearch.com/2018/12/17/image-stitching-with-opencv-and-python/
https://paperswithcode.com/task/image-matching
Important Packages
 Image matching
AI VIETNAM
All-in-One Course
points_img1, points_img2  SIFT_matching(img1, img2)
 XML
 JSON
 Tabular Data
 Image Data
 Some important libs
Outline
Important Packages
Year 2022 85
AI VIETNAM
All-in-One Course
 os package
Important
Packages
Year 2022
AI VIETNAM
All-in-One Course
glob package
os package
Important Packages
 gzip package
Year 2022 87
AI VIETNAM
All-in-One Course
Important Packages
 pickle package
Year 2022 88
AI VIETNAM
All-in-One Course
Important Packages
Year 2022
 Gradient computation
+
𝑥1
𝑥2
𝑥3
𝑥4
𝑦 ∙ 2
Important Packages
Year 2022
AI VIETNAM
All-in-One Course
𝑥 ∙ 2 ∙ 2
𝑦 𝑧
 Gradient computation
Important Packages
Year 2022
AI VIETNAM
All-in-One Course
𝑥
𝑥
𝑥
∗ 𝑦
 Gradient computation
Important Packages
Year 2022
AI VIETNAM
All-in-One Course
𝑔 𝑥 = −3𝑥 + 4
ℎ 𝑔 = 2𝑔 + 1
 Gradient computation
Important Packages
Year 2022
AI VIETNAM
All-in-One Course
𝑔 𝑥 = 𝑥2 + 1
ℎ 𝑔 = 𝑒𝑔
 Gradient computation
Important Packages
Year 2022
𝑔 𝑥 = 𝑐𝑜𝑠 𝑥2𝑒𝑥 + 2𝑥
ℎ 𝑔 = 𝑒𝑔𝑠𝑖𝑛 𝑔
 Gradient computation
94
Module 1 - Python.pdf

Module 1 - Python.pdf

  • 1.
    Python An Introduction Year 2022 Quang-VinhDinh Ph.D. in Computer Science AI VIETNAM All-in-One Course
  • 2.
     Programming Languages Python Environment  Basic Data Types  Functions  Conditions  Loops  Common Errors Outline
  • 3.
    References  Books Year 2022Python 101 - 2020 Beyond the Basic Stuff with Python https://www.dropbox.com/sh/x69 9xsfs8wnadny/AACMcdVGxen1l 4yNWwQzoF-Xa?dl=0 AI VIETNAM All-in-One Course
  • 4.
    Programming Languages  Whatshould a programming language provide? Encode/Represent Numbers 1, -2 … -1.2, 2.7 … Text a, b, c Hello … Objects Real World Year 2022 2 AI VIETNAM All-in-One Course
  • 5.
    Programming Languages  Whatshould a programming language provide? A way to represent numbers using bits With three bits 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 8 different cases Positive numbers 0, 7 8, 15 Negative numbers −1, −8 … Mixed −3, 4 Year 2022 3 AI VIETNAM All-in-One Course
  • 6.
    Programming Languages  Whatshould a programming language provide? A way to represent numbers using bits With three bits 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 8 different cases Positive numbers Negative numbers 0, 7 8, 15 −1, −8 … Mixed −3, 4 How to distinguish the cases? Year 2022 4 AI VIETNAM All-in-One Course
  • 7.
    Programming Languages  Whatshould a programming language provide? A way to represent numbers using bits With three bits 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 8 different cases + Metadata Type 1 Positive numbers 0, 7 Type 2 Negative numbers −1, −8 Type 3 Mixed −3, 4 Year 2022 5 AI VIETNAM All-in-One Course
  • 8.
    Programming Languages  Whatshould a programming language provide? A way to represent numbers using bits With eight bits 256 different cases + Metadata Type 1 unsigned char 0, 255 Type 2 char −127, 128 Syntax for programmer char a_number = 6; 0 0 0 0 0 1 1 0 Year 2022 6 AI VIETNAM All-in-One Course
  • 9.
    Programming Languages  Whatshould a programming language provide? How to represent floating-point numbers? 3.14 3 . 14 a set of bits a set of bits With 4 bytes (32 bits) float With 8 bytes (64 bits) double Syntax for programmer float a_number = 3.14; double another_number = 2.71; Year 2022 7 AI VIETNAM All-in-One Course
  • 10.
    Programming Languages  Whatshould a programming language provide? How to represent/store text using bits? Need a mapping table! Year 2022 8 AI VIETNAM All-in-One Course
  • 11.
    Programming Languages  Whatshould a programming language provide? How to represent/store text using bits? Syntax for programmer char a_number = ‘A’; A mapping table 0 1 0 0 0 0 0 1 Decimal: 65 Year 2022 9 AI VIETNAM All-in-One Course
  • 12.
  • 13.
    Programming Languages  Whatshould a programming language provide? Numbers 1, -2 … -1.2, 2.7 … Text a, b, c Hello … Objects Real World Encode/Represent …, 1, 2, 3 … 1.4, 2.7, … ‘A’ ‘1’ char int float double What’s more??? Year 2022 11 AI VIETNAM All-in-One Course
  • 14.
    Programming Languages  C++and Python C++ example Python example 12 AI VIETNAM All-in-One Course
  • 15.
     Programming Languages Python Environment  Basic Data Types  Functions  Conditions  Loops  Common Errors Outline
  • 16.
    Introduction  Python history 1 AIVIETNAM All-in-One Course Year 2022 13
  • 17.
    Introduction  Python ecosystem 2 AIVIETNAM All-in-One Course Year 2022 14
  • 18.
    Introduction  Top ProgrammingLanguages (2021) AI VIETNAM All-in-One Course https://spectrum.ieee.org/top- programming-languages/ Year 2022
  • 19.
    Introduction  First Pythonprogram AI VIETNAM All-in-One Course Create a .py file Write Python code Run the file Demo Year 2022
  • 20.
    Introduction  Virtual environment AIVIETNAM All-in-One Course sudo apt-get install -y python3-venv python3 -m venv a_name source a_name/bin/activate Python Environment Python 3.6 Tensorflow 1.4 Python 3.6 Tensorflow 2.1 Python 3.8 Pytorch Year 2022 17
  • 21.
    Introduction  First Pythonprogram  Using Google Colab 6 AI VIETNAM All-in-One Course https://colab.research.google.com/notebooks/intro.ipynb#recent=true Demo Year 2022 18
  • 22.
    Introduction  First Pythonprogram  Using Anaconda + Jupyter Notebook AI VIETNAM All-in-One Course Demo Year 2022 conda create -n test_env2 python=3.9 conda activate an_env conda deactivate Setting up environment To check packages installed pip list Open the jupyter program jupyter notebook To install a package pip install package_name Some common commands
  • 23.
    Introduction  Install newpackage pip install matplotlib
  • 24.
    Variable 4 AI VIETNAM All-in-One Course variable_name= variable_value Variable values 1, 2, 3, 0, -1, -2 Integer 1.5, 0.5, -3.21, 1.0 Float 'Joe', 'Schmoe', "Joe", "Schmoe" String True, False Boolean 21 Year 2022
  • 25.
    Variable 4 AI VIETNAM All-in-One Course variable_name= variable_value variable_name Should has a meaning Cannot use keywords Example Demo 22
  • 26.
    Built-in Functions AI VIETNAM All-in-OneCourse print(parameters) type(parameter)
  • 27.
    Built-in Functions AI VIETNAM All-in-OneCourse input(promt) 4 24 Year 2022
  • 28.
    Built-in Functions AI VIETNAM All-in-OneCourse int() float() Type Conversion 4 Demo 25 Year 2022
  • 29.
    Random and MathModules 4 AI VIETNAM All-in-One Course https://docs.python.org/3/library/math.html Demo 26 Year 2022
  • 30.
    Random and MathModules 4 AI VIETNAM All-in-One Course https://docs.python.org/3/library/random.html Demo 27 Year 2022
  • 31.
    Basic Operators AI VIETNAM All-in-OneCourse 4 Demo 28 Year 2022
  • 32.
    Example 4 AI VIETNAM All-in-One Course 𝐹= 9𝐶 5 + 32 Celsius to Fahrenheit conversion 𝐶 = 𝐹 − 32 5 9 Celsius to Fahrenheit conversion 29 Year 2022
  • 33.
    Example Circumference and area ofcommon shapes 4 AI VIETNAM All-in-One Course Demo 30 Year 2022
  • 34.
  • 35.
    Functions 4 AI VIETNAM All-in-One Course Definefunction name Lowercase with underscores and begin with a verb Determine function parameters Input data help the function done Do docstring Explain and describe the function Output of the function Notes for function construction Indentation Use 4 spaces for indentation parentheses colon keyword General structure of a function indentation Demo (rectangle) 31 Year 2022
  • 36.
    Functions AI VIETNAM All-in-One Course Definefunction name Lowercase with underscores, usually begin with a verb Determine function parameters Input data help the function done Do docstring Explain and describe the function Output of the function compute_rectangle_area Name height, width Parameter area Output 4 32
  • 37.
    Functions  Default values 4 AIVIETNAM All-in-One Course Default values 33 Year 2022
  • 38.
    Sigmoid Function AI VIETNAM All-in-OneCourse 𝑦 = 𝜎(𝑢) = 1 1 + 𝑒−𝑢 𝑢 ∈ −∞ + ∞ 𝑦 ∈ 0 1 ∀𝑢1𝑢2 ∈ 𝑎 𝑏 và 𝑢1 ≤ 𝑢2 → 𝜎(𝑢1) ≤ 𝜎(𝑢1) 𝒖 +∞ −∞ 𝑢1 𝑢2 𝒚 𝑦1 𝑦2 Sigmoid function Property 34 Year 2022
  • 39.
    Activation Functions sigmoid 𝑥= 1 1 + 𝑒−𝑥 tanh 𝑥 = 𝑒𝑥 − 𝑒−𝑥 𝑒𝑥 + 𝑒−𝑥 35 S-shaped curves Map x values into small ranges
  • 40.
    Overflow and Underflow Why? AI VIETNAM All-in-One Course Year 2022 36
  • 41.
    Overflow and Underflow AIVIETNAM AI Insight Course Softmax function 𝑧1 = 1.0 𝑧2 = 3.0 Softmax 𝑓(𝑧1) = 0.12 𝑓(𝑧2) = 0.88 Input Probability 𝑧1 = 1.0 𝑧2 = 2.0 Softmax 𝑓(𝑧1) = 0.09 𝑓(𝑧2) = 0.24 Input Probability 𝑧3 = 3.0 𝑓(𝑧3) = 0.67 𝑃𝑖 = 𝑓 𝑧𝑖 = 𝑒𝑧𝑖 σ𝑗 𝑒𝑧𝑗 0 ≤ 𝑓 𝑧𝑖 ≤ 1 ෍ 𝑖 𝑓 𝑧𝑖 = 1 Year 2022 37
  • 42.
    Softmax function 𝑓 𝑥𝑖= 𝑒𝑥𝑖 σ𝑗 𝑒𝑥𝑗 0 ≤ 𝑓 𝑥𝑖 ≤ 1 ෍ 𝑖 𝑓 𝑥𝑖 = 1 Formula 𝑥1 = 1.0 𝑥2 = 2.0 Softmax 𝑓(𝑥1) = 0.09 𝑓(𝑥2) = 0.24 Input Probability 𝑥3 = 3.0 𝑓(𝑥3) = 0.67 Chuyển các giá trị của một vector thành các giá trị xác suất Implementation (straightforward)
  • 43.
    Softmax function 𝑓 𝑥𝑖= 𝑒𝑥𝑖 σ𝑗 𝑒𝑥𝑗 0 ≤ 𝑓 𝑥𝑖 ≤ 1 ෍ 𝑖 𝑓 𝑥𝑖 = 1 Formula 𝑥1 = 1.0 𝑥2 = 2.0 Softmax 𝑓(𝑥1) = 0.09 𝑓(𝑥2) = 0.24 Input Probability 𝑥3 = 3.0 𝑓(𝑥3) = 0.67 Giá trị nan vì 𝑒𝑥 vượt giới hạn lưu trữ của biến Chuyển các giá trị của một vector thành các giá trị xác suất Hàm mũ tăng rất nhanh khi x tăng 𝑒𝑥 𝑥 𝑒𝑥 ∈ [1, +∞) 𝑥 ∈ [0, +∞) Implementation (straightforward) 39
  • 44.
    Softmax function (stable) 𝑓𝑥𝑖 = 𝑒(𝑥𝑖−𝑚) σ𝑗 𝑒(𝑥𝑗−𝑚) (Stable) Formula 𝑚 = max(𝒙) 𝑥1 = 1.0 𝑥2 = 2.0 X 𝑥3 = 3.0 Softmax 𝑓(𝑥1) = 0.09 𝑓(𝑥2) = 0.24 Probability 𝑓(𝑥3) = 0.67 𝑥1 = −2.0 𝑥2 = −1.0 X-m 𝑥3 = 0 𝑒𝑥 𝑥 𝑒𝑥 ∈ (0, 1) 𝑥 ∈ (−∞, 0) Implementation (stable)
  • 45.
     Programming Languages Python Environment  Basic Data Types  Functions  Conditions  Loops  Common Errors Outline
  • 46.
    Condition  Comparison operators 4 AIVIETNAM All-in-One Course 41 Year 2022
  • 47.
    Condition  if condition 4 AIVIETNAM All-in-One Course Khối code K1 Điều kiện if Khối code trong if Khối code K2 True False keyword indentation colon 42 Year 2022
  • 48.
    Condition if condition 4 AI VIETNAM All-in-One Course ReLU𝑥 = ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 43 Year 2022
  • 49.
    Condition  if-else condition 4 AIVIETNAM All-in-One Course Khối code (K1) Điều kiện if Khối code trong if Khối Code (K2) True False Khối code trong else keyword indentation colon 44 Year 2022
  • 50.
    Condition  if-else condition 4 AIVIETNAM All-in-One Course if condition ReLU 𝑥 = ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 Demo 45 Year 2022
  • 51.
    Condition  if-elif-else condition AIVIETNAM All-in-One Course Khối code (K1) Điều kiện if Khối code trong if Khối Code (K2) True False Khối code trong elif Điều kiện elif Khối code trong else True False colon indentation Year 2022
  • 52.
    Condition  if-elif-else condition 4 AIVIETNAM All-in-One Course 47 FuzzyEncoding 𝑥, 𝑦, 𝑇 = 5, 4, 3, 2, 1, if 𝑥 + 𝑇 ≤ 𝑦 if 𝑥 < 𝑦 < 𝑥 + 𝑇 if 𝑥 = 𝑦 if 𝑦 < 𝑥 < 𝑦 + 𝑇 if 𝑦 + 𝑇 ≤ 𝑥 Year 2022 5 4 3 2 1 T LTP 𝑥, 𝑦 = ቐ 0 if 𝑥 = 𝑦 1 if 𝑥 > 𝑦 −1 if 𝑥 < 𝑦
  • 53.
    If-Else Condition andMath (1) if 𝑎 = 0 then 𝑦 = 𝑏2 if 𝑎 = 𝐾 then 𝑦 = 𝑏 Input: 𝑎 and 𝑏 𝑦 = 𝑎 𝐾 𝑏 + 𝐾 − 𝑎 𝐾 𝑏2 Input: 𝑎 and 𝑏 AI VIETNAM All-in-One Course 48 Year 2022
  • 54.
    If-Else Condition andMath (2) if 𝑎 > 0 then 𝑦 = 𝑏2 if 𝑎 < 0 then 𝑦 = 𝑏 Input: 𝑎 and 𝑏 𝑦 = 𝑏2 + 𝑏 2 + 𝑏2 − 𝑏 2 𝑎 𝑎 Input: 𝑎 and 𝑏 AI VIETNAM All-in-One Course 49 Year 2022
  • 55.
    If-Else Condition andMath (3) Input: 𝑎 and 𝑏 if 𝑎 = 0 then 𝑦 = 𝑏2 if 𝑎 = 1 then 𝑦 = 𝑏 if 𝑎 = 2 then 𝑦 = 𝑏 Input: 𝑎 and 𝑏 Convert 𝑎 into a one-hot vector 𝒗 𝑦 = 𝒗 ∙ 𝒖 𝒖 = [𝑏2 𝑏 𝑏] 𝒗 = [1 0 0] 𝒗 = [0 1 0] 𝒗 = [0 0 1] AI VIETNAM All-in-One Course 50 Year 2022
  • 56.
  • 57.
    For Loop 4 AI VIETNAM All-in-OneCourse Đã duyệt phần tử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for colon indentation keyword String Tuple List Dictionary range() Iterables 51 Year 2022
  • 58.
    For Loop Đã duyệt phầntử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for 4 52
  • 59.
    For Loop Đã duyệt phầntử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for 4 0, 1, 2, 3, 4 range(start=0, stop, step=1) range(start=0, stop=5, step=1) 0, 1, 2, 3, 4 range(5) Demo 53
  • 60.
    For Loop AI VIETNAM All-in-OneCourse Đã duyệt phần tử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for break break keyword 4 Demo 54
  • 61.
    For Loop AI VIETNAM All-in-OneCourse Đã duyệt phần tử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for continue continue keyword Demo 4 55
  • 62.
    Example  Simulation ofcoin tossing AI VIETNAM All-in-One Course Event: bất kì sự kiện gì xảy ra Experiment: sự thử nghiệm cho ra kết quả Sample space: tập hợp tất cả các kết quả có thể xảy ra của một experiment Random variable: biến ngẫu nhiên, mô tả outcome của một event Tiền xu có 2 mặt (head và tail) Sample space 𝑆 = Head, Tail Experiment: ném đồng xu Event: Gọi A là event mà kết quả của một lần ném là head 𝑃(𝐴) Xác suất để event A xảy ra Xác suất để kết quả của một lần ném là head A={head} S={head, tail} 𝑃 𝐴 = 𝐴 𝑆 = 1 2 Xác suất 𝑃(event) = event 𝑆 4 56 Year 2022
  • 63.
    Example  Simulation ofcoin tossing AI VIETNAM All-in-One Course Count #tails Count #heads Check if the two numbers are similar Demo 57 Year 2022
  • 64.
    Example: PI Estimation PI estimation 4 AI VIETNAM All-in-One Course hình từ wikipedia circle_area 𝐴𝑐= 𝜋𝑟2 circle radius 𝑟 = 1 square_area 𝐴𝑠 = 𝑠2 square side 𝑠 = 2 𝐴𝑠 𝐴𝑐 ≈ 𝑁𝑠 𝑁𝑐 𝑠2 𝜋𝑟2 ≈ 𝑁𝑠 𝑁𝑐 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 𝑁𝑠 is #random samples within the square generated according to uniform distribution 𝑁𝑐 is #random samples within the circle generated according to uniform distribution 58
  • 65.
    Example  PI estimation 4 AIVIETNAM All-in-One Course (hình từ wikipedia) 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 Random numbers ∈ [-1,1] Check if a point is within the circle 59 Year 2022
  • 66.
    Example  PI estimation 4 AIVIETNAM All-in-One Course (hình từ wikipedia) 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 https://www.mathsisfun.com/algebra/distance-2-points.html 60 Year 2022
  • 67.
    Example  PI estimation 4 AIVIETNAM All-in-One Course (hình từ wikipedia) 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 61 Year 2022
  • 68.
    Example  PI estimation 4 AIVIETNAM All-in-One Course 62 𝑃𝐼 ≈ 4 ෍ 𝑖=1 𝑛 −1 𝑖+1 2𝑖 − 1 Gregory-Leibniz Series Nilakantha Series 𝑃𝐼 ≈ 3 + 4 ෍ 𝑖=0 𝑛 −1𝑖 2𝑖 + 2 2𝑖 + 3 2𝑖 + 4 Year 2022
  • 69.
    Example  Euler's number 4 https://www.mathsisfun.com/numbers/e-eulers-number.html 𝑒≈ 1 + 1 𝑛 𝑛 AI VIETNAM All-in-One Course 63 Year 2022
  • 70.
    Example  Euler's number 𝑒= 2.71828 Formula 1) Compute factorial 2) Compute sum 4 64 Year 2022
  • 71.
  • 72.
    Example: Quadratic Root Compute quadratic root for the number N 4 AI VIETNAM All-in-One Course 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 Compute 9 𝑁 = 9 𝑠𝑒𝑡 𝑥0 = 9 2 = 4.5 𝑛 = 0 𝑛 = 0 𝑥1 = 𝑥0 + 𝑁 𝑥0 2 = 4.5 + 9 4.5 2 = 6.5 2 = 3.25 𝑛 = 1 𝑥2 = 𝑥1 + 𝑁 𝑥1 2 = 3.25 + 9 3.25 2 = 6.019 2 = 3.009 𝑛 = 2 𝑥3 = 𝑥2 + 𝑁 𝑥2 2 = 3.009 + 9 3.009 2 = 3.00001 66 Year 2022
  • 73.
    Example: Quadratic Root Compute quadratic root for the number N AI VIETNAM All-in-One Course 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 67
  • 74.
  • 75.
    While Loop 4 AI VIETNAM All-in-OneCourse Condition Thực thi các câu lệnh trong while False True Code trước while Code sau while colon indentation keyword 68 Year 2022
  • 76.
    While Loop 4 AI VIETNAM All-in-OneCourse Condition Thực thi các câu lệnh trong while False True Code trước while Code sau while 69 Year 2022
  • 77.
    While Loop 𝑖 =0 𝑖 < 5 ? yes 𝑖 = 0 + 1 = 1 print(0) 𝑖 < 5 ? yes 𝑖 = 1 + 1 = 2 print(1) 𝑖 < 5 ? 𝑖 < 5 ? yes 𝑖 = 2 + 1 = 2 print(2) 𝑖 < 5 ? yes 𝑖 = 3 + 1 = 4 print(3) 𝑖 < 5 ? 𝑖 < 5 ? yes 𝑖 = 4 + 1 = 5 print(4) 𝑖 < 5 ? no print(′Phần code này khi đã thoát while′) 4 70 Year 2022
  • 78.
  • 79.
    Exercises 4 AI VIETNAM All-in-One Course 72 Pascal'sTriangle Level = 5 0, 1, 1, 2, 3, 5, 8, 13, 21 + Length = 9 Fibonacci Sequence https://www.mathsisfun.com Year 2022
  • 80.
    Exercises 4 AI VIETNAM All-in-One Course 73 Year2022 𝑠𝑖𝑛 𝑥 ≈ ෍ 𝑛=0 ∞ −1 𝑛 𝑥 2𝑛+1 2𝑛 + 1 ! = 𝑥 − 𝑥3 3! + 𝑥5 5! − 𝑥7 7! + 𝑥9 9! − ⋯ 𝑐𝑜𝑠 𝑥 ≈ ෍ 𝑛=0 ∞ −1 𝑛 𝑥2𝑛 2𝑛 ! = 1 − 𝑥2 2! + 𝑥4 4! − 𝑥6 6! + 𝑥8 8! − 𝑥10 10! + ⋯ 𝑒𝑥 ≈ ෍ 𝑛=0 ∞ 𝑥𝑛 𝑛! = 1 + 𝑥1 1! + 𝑥2 2! + 𝑥3 3! + 𝑥4 4! + 𝑥5 5! + ⋯ 𝑠𝑖𝑛ℎ 𝑥 ≈ ෍ 𝑛=0 ∞ 𝑥 2𝑛+1 2𝑛 + 1 ! = 𝑥 + 𝑥3 3! + 𝑥5 5! + 𝑥7 7! + 𝑥9 9! + ⋯ 𝑐𝑜𝑠ℎ 𝑥 ≈ ෍ 𝑛=0 ∞ 𝑥2𝑛 2𝑛 ! = 1 + 𝑥2 2! + 𝑥4 4! + 𝑥6 6! + 𝑥8 8! + 𝑥10 10! + ⋯
  • 81.
    Exercises 4 AI VIETNAM All-in-One Course 74 PIestimation E estimation Simulation of coin tossing Compute quadratic root for the number N 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 Year 2022
  • 82.
    Recursive 4 AI VIETNAM All-in-One Course 75 PIestimation E estimation Simulation of coin tossing Compute quadratic root for the number N 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 Year 2022
  • 83.
    Common Errors  Error1 AI VIETNAM All-in-One Course 76 Year 2022
  • 84.
    Common Errors  Error2 AI VIETNAM All-in-One Course 77 Year 2022
  • 85.
    Common Errors  Error3 AI VIETNAM All-in-One Course 78 Year 2022
  • 86.
    Common Errors  Error4 AI VIETNAM All-in-One Course 79 Year 2022
  • 87.
    Common Errors  Error5 AI VIETNAM All-in-One Course 80 Year 2022
  • 88.
    Common Errors  Error6 AI VIETNAM All-in-One Course 81 Year 2022
  • 89.
    Common Errors  Error7 AI VIETNAM All-in-One Course 82 Year 2022
  • 90.
    Common Errors  Error8 AI VIETNAM All-in-One Course 83 Year 2022
  • 91.
    Common Errors  Error9 AI VIETNAM All-in-One Course 84 Year 2022
  • 92.
    Common Errors  Error10 AI VIETNAM All-in-One Course 85 Year 2022
  • 93.
    Common Errors  Error11 AI VIETNAM All-in-One Course 86 Year 2022
  • 94.
    Common Errors  Error12 AI VIETNAM All-in-One Course 87 Year 2022
  • 95.
    Common Errors  Error13 AI VIETNAM All-in-One Course 88 Year 2022
  • 96.
    Common Errors  Error14 AI VIETNAM All-in-One Course 89 Year 2022
  • 97.
    Common Errors  Error15 AI VIETNAM All-in-One Course 90 Year 2022
  • 98.
    Common Errors  Error16 AI VIETNAM All-in-One Course 91 Year 2022
  • 99.
    Common Errors  Error17 AI VIETNAM All-in-One Course 92 Year 2022
  • 100.
    Common Errors  Error18 AI VIETNAM All-in-One Course 93 Year 2022
  • 101.
    Common Errors  Error19 AI VIETNAM All-in-One Course 94 Year 2022
  • 102.
    Common Errors  Error20 AI VIETNAM All-in-One Course 95 Year 2022
  • 103.
    Common Errors  Error21 AI VIETNAM All-in-One Course 96 Year 2022
  • 105.
    Python A Deeper Step Year2022 Quang-Vinh Dinh Ph.D. in Computer Science AI VIETNAM All-in-One Course
  • 106.
     Conditions  Loops String  File Outline
  • 107.
    Condition  Comparison operators 1 AIVIETNAM All-in-One Course Year 2022
  • 108.
    Condition  if condition 2 AIVIETNAM All-in-One Course Khối code K1 Điều kiện if Khối code trong if Khối code K2 True False keyword indentation colon Year 2022
  • 109.
    Condition if condition 3 AI VIETNAM All-in-One Course ReLU𝑥 = ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 Year 2022
  • 110.
    Condition  if-else condition 4 AIVIETNAM All-in-One Course Khối code (K1) Điều kiện if Khối code trong if Khối Code (K2) True False Khối code trong else keyword indentation colon Year 2022
  • 111.
    Condition  if-else condition 5 AIVIETNAM All-in-One Course if condition ReLU 𝑥 = ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 Demo Year 2022
  • 112.
    Condition  if-elif-else condition AIVIETNAM All-in-One Course Khối code (K1) Điều kiện if Khối code trong if Khối Code (K2) True False Khối code trong elif Điều kiện elif Khối code trong else True False colon indentation Year 2022
  • 113.
    Condition  if-elif-else condition 7 AIVIETNAM All-in-One Course FuzzyEncoding 𝑥, 𝑦, 𝑇 = 5, 4, 3, 2, 1, if 𝑥 + 𝑇 ≤ 𝑦 if 𝑥 < 𝑦 < 𝑥 + 𝑇 if 𝑥 = 𝑦 if 𝑦 < 𝑥 < 𝑦 + 𝑇 if 𝑦 + 𝑇 ≤ 𝑥 Year 2022 5 4 3 2 1 T LTP 𝑥, 𝑦 = ቐ 0 if 𝑥 = 𝑦 1 if 𝑥 > 𝑦 −1 if 𝑥 < 𝑦
  • 114.
    If-Else Condition andMath (1) if 𝑎 = 0 then 𝑦 = 𝑏2 if 𝑎 = 𝐾 then 𝑦 = 𝑏 Input: 𝑎 and 𝑏 𝑦 = 𝑎 𝐾 𝑏 + 𝐾 − 𝑎 𝐾 𝑏2 Input: 𝑎 and 𝑏 AI VIETNAM All-in-One Course Year 2022 8
  • 115.
    If-Else Condition andMath (2) if 𝑎 > 0 then 𝑦 = 𝑏2 if 𝑎 < 0 then 𝑦 = 𝑏 Input: 𝑎 and 𝑏 𝑦 = 𝑏2 + 𝑏 2 + 𝑏2 − 𝑏 2 𝑎 𝑎 Input: 𝑎 and 𝑏 AI VIETNAM All-in-One Course Year 2022 9
  • 116.
    If-Else Condition andMath (3) Input: 𝑎 and 𝑏 if 𝑎 = 0 then 𝑦 = 𝑏2 if 𝑎 = 1 then 𝑦 = 𝑏 if 𝑎 = 2 then 𝑦 = 𝑏 Input: 𝑎 and 𝑏 Convert 𝑎 into a one-hot vector 𝒗 𝑦 = 𝒗 ∙ 𝒖 𝒖 = [𝑏2 𝑏 𝑏] 𝒗 = [1 0 0] 𝒗 = [0 1 0] 𝒗 = [0 0 1] AI VIETNAM All-in-One Course 10 Year 2022
  • 117.
     Conditions  Loops String  File Outline
  • 118.
    Motivation  Observation Year 2021 AIVIETNAM AI Course 2021 Features Label Feature Label House price data Advertising data
  • 119.
    For Loop 4 AI VIETNAM All-in-OneCourse Đã duyệt phần tử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for colon indentation keyword String Tuple List Dictionary range() Iterables 11 Year 2022
  • 120.
    For Loop Đã duyệt phầntử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for 4 12
  • 121.
    For Loop Đã duyệt phầntử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for 4 0, 1, 2, 3, 4 range(start=0, stop, step=1) range(start=0, stop=5, step=1) 0, 1, 2, 3, 4 range(5) Demo 13
  • 122.
    For Loop AI VIETNAM All-in-OneCourse Đã duyệt phần tử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for break break keyword 4 Demo 14
  • 123.
    For Loop AI VIETNAM All-in-OneCourse Đã duyệt phần tử cuối cùng? Thực thi các câu lệnh trong for True False Code trước for Code sau for continue continue keyword Demo 4 15
  • 124.
    Example  Simulation ofcoin tossing AI VIETNAM All-in-One Course Event: bất kì sự kiện gì xảy ra Experiment: sự thử nghiệm cho ra kết quả Sample space: tập hợp tất cả các kết quả có thể xảy ra của một experiment Random variable: biến ngẫu nhiên, mô tả outcome của một event Tiền xu có 2 mặt (head và tail) Sample space 𝑆 = Head, Tail Experiment: ném đồng xu Event: Gọi A là event mà kết quả của một lần ném là head 𝑃(𝐴) Xác suất để event A xảy ra Xác suất để kết quả của một lần ném là head A={head} S={head, tail} 𝑃 𝐴 = 𝐴 𝑆 = 1 2 Xác suất 𝑃(event) = event 𝑆 4 16 Year 2022
  • 125.
    Example  Simulation ofcoin tossing AI VIETNAM All-in-One Course Count #tails Count #heads Check if the two numbers are similar Demo 17 Year 2022
  • 126.
    Example: PI Estimation PI estimation 4 AI VIETNAM All-in-One Course hình từ wikipedia circle_area 𝐴𝑐= 𝜋𝑟2 circle radius 𝑟 = 1 square_area 𝐴𝑠 = 𝑠2 square side 𝑠 = 2 𝐴𝑠 𝐴𝑐 ≈ 𝑁𝑠 𝑁𝑐 𝑠2 𝜋𝑟2 ≈ 𝑁𝑠 𝑁𝑐 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 𝑁𝑠 is #random samples within the square generated according to uniform distribution 𝑁𝑐 is #random samples within the circle generated according to uniform distribution 18
  • 127.
    Example  PI estimation 4 AIVIETNAM All-in-One Course (hình từ wikipedia) 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 Random numbers ∈ [-1,1] Check if a point is within the circle 19 Year 2022
  • 128.
    Example  PI estimation 4 AIVIETNAM All-in-One Course (hình từ wikipedia) 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 https://www.mathsisfun.com/algebra/distance-2-points.html 20 Year 2022
  • 129.
    Example  PI estimation 4 AIVIETNAM All-in-One Course (hình từ wikipedia) 𝜋 ≈ 𝑠2 𝑁𝑐 𝑁𝑠 21 Year 2022
  • 130.
    Example  PI estimation 4 AIVIETNAM All-in-One Course 22 𝑃𝐼 ≈ 4 ෍ 𝑖=1 𝑛 −1 𝑖+1 2𝑖 − 1 Gregory-Leibniz Series Nilakantha Series 𝑃𝐼 ≈ 3 + 4 ෍ 𝑖=0 𝑛 −1𝑖 2𝑖 + 2 2𝑖 + 3 2𝑖 + 4 Year 2022
  • 131.
    Example  Euler's number 4 https://www.mathsisfun.com/numbers/e-eulers-number.html 𝑒≈ 1 + 1 𝑛 𝑛 AI VIETNAM All-in-One Course 23 Year 2022
  • 132.
    Example  Euler's number 𝑒= 2.71828 Formula 1) Compute factorial 2) Compute sum 4 24 Year 2022
  • 133.
  • 134.
    Example: Quadratic Root Compute quadratic root for the number N 4 AI VIETNAM All-in-One Course 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 Compute 9 𝑁 = 9 𝑠𝑒𝑡 𝑥0 = 9 2 = 4.5 𝑛 = 0 𝑛 = 0 𝑥1 = 𝑥0 + 𝑁 𝑥0 2 = 4.5 + 9 4.5 2 = 6.5 2 = 3.25 𝑛 = 1 𝑥2 = 𝑥1 + 𝑁 𝑥1 2 = 3.25 + 9 3.25 2 = 6.019 2 = 3.009 𝑛 = 2 𝑥3 = 𝑥2 + 𝑁 𝑥2 2 = 3.009 + 9 3.009 2 = 3.00001 26 Year 2022
  • 135.
    Example: Quadratic Root Compute quadratic root for the number N AI VIETNAM All-in-One Course 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 27
  • 136.
  • 137.
    While Loop 4 AI VIETNAM All-in-OneCourse Condition Thực thi các câu lệnh trong while False True Code trước while Code sau while colon indentation keyword 28 Year 2022
  • 138.
    While Loop 4 AI VIETNAM All-in-OneCourse Condition Thực thi các câu lệnh trong while False True Code trước while Code sau while 29 Year 2022
  • 139.
    While Loop 𝑖 =0 𝑖 < 5 ? yes 𝑖 = 0 + 1 = 1 print(0) 𝑖 < 5 ? yes 𝑖 = 1 + 1 = 2 print(1) 𝑖 < 5 ? 𝑖 < 5 ? yes 𝑖 = 2 + 1 = 2 print(2) 𝑖 < 5 ? yes 𝑖 = 3 + 1 = 4 print(3) 𝑖 < 5 ? 𝑖 < 5 ? yes 𝑖 = 4 + 1 = 5 print(4) 𝑖 < 5 ? no print(′Phần code này khi đã thoát while′) 4 30 Year 2022
  • 140.
  • 141.
    Exercises 4 AI VIETNAM All-in-One Course 32 Pascal'sTriangle Level = 5 0, 1, 1, 2, 3, 5, 8, 13, 21 + Length = 9 Fibonacci Sequence https://www.mathsisfun.com Year 2022
  • 142.
    Exercises 4 AI VIETNAM All-in-One Course 33 Year2022 𝑠𝑖𝑛 𝑥 ≈ ෍ 𝑛=0 ∞ −1 𝑛 𝑥 2𝑛+1 2𝑛 + 1 ! = 𝑥 − 𝑥3 3! + 𝑥5 5! − 𝑥7 7! + 𝑥9 9! − ⋯ 𝑐𝑜𝑠 𝑥 ≈ ෍ 𝑛=0 ∞ −1 𝑛 𝑥2𝑛 2𝑛 ! = 1 − 𝑥2 2! + 𝑥4 4! − 𝑥6 6! + 𝑥8 8! − 𝑥10 10! + ⋯ 𝑒𝑥 ≈ ෍ 𝑛=0 ∞ 𝑥𝑛 𝑛! = 1 + 𝑥1 1! + 𝑥2 2! + 𝑥3 3! + 𝑥4 4! + 𝑥5 5! + ⋯ 𝑠𝑖𝑛ℎ 𝑥 ≈ ෍ 𝑛=0 ∞ 𝑥 2𝑛+1 2𝑛 + 1 ! = 𝑥 + 𝑥3 3! + 𝑥5 5! + 𝑥7 7! + 𝑥9 9! + ⋯ 𝑐𝑜𝑠ℎ 𝑥 ≈ ෍ 𝑛=0 ∞ 𝑥2𝑛 2𝑛 ! = 1 + 𝑥2 2! + 𝑥4 4! + 𝑥6 6! + 𝑥8 8! + 𝑥10 10! + ⋯
  • 143.
    Exercises 4 AI VIETNAM All-in-One Course 34 PIestimation E estimation Simulation of coin tossing Compute quadratic root for the number N 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 Year 2022
  • 144.
    Recursive 4 AI VIETNAM All-in-One Course 35 PIestimation E estimation Simulation of coin tossing Compute quadratic root for the number N 𝑥𝑛+1 = 𝑥𝑛 + 𝑁 𝑥𝑛 2 Newton Method Set a value for 𝑥0; n = 0 (𝑥0 = N/2) n = n + 1 Year 2022
  • 145.
     Conditions  Loops String  File Outline
  • 146.
  • 147.
  • 148.
    Variables  Character type AIVIETNAM All-in-One Course Year 2022 38
  • 149.
    ASCII Table https://upload.wikimedia.org/wikipedia/commons/d/dd/ASCII-Table.svg  AmericanStandard code for information interchange ASCII represents 128 characters ASCII is stored as 8- bit byte ASCII is not standardized AI VIETNAM All-in-One Course Year 2022 39
  • 150.
  • 151.
  • 152.
  • 153.
    String  + and* operators AI VIETNAM All-in-One Course  Logic operators Year 2022 44
  • 154.
    String AI VIETNAM All-in-One Course isdigit():Kiểm tra xem string gồm các kí tự số isalpha(): Kiểm tra xem string chỉ được tạo từ các kí tự chữ cái islower(): Kiểm tra xem string với tất cả các kí tự ở dạng chữ thường isupper(): Kiểm tra xem string với tất cả các kí tự ở dạng chữ hoa Year 2022 45
  • 155.
    String AI VIETNAM All-in-One Course istitle():Kiểm tra xem string có bắt đầu bằng chữ in hoa isspace(): Kiểm tra xem string chỉ là khoảng trắng count() để đếm số kí tự xuất hiện trong một string, len() để tính chiều dài của một string Year 2022 46
  • 156.
    String AI VIETNAM All-in-One Course title():Chuyển đổi kí tự đầu từng từ (word) trong một chuỗi thành kí tự hoa capitalize(): Chuyển đổi chữ cái đầu tiên của một chuỗi thành chữ hoa và các kí tự sau thành chữ thường swapcase(): Chuyển đổi các kí tự từ chữ thường sang chữ hoa và ngược lại Year 2022 47
  • 157.
    String AI VIETNAM All-in-One Course upper():Chuyển đổi tất cả các kí tự trong chuỗi thành chữ hoa lower(): Chuyển đổi các kí tự sang chữ thường center(): Chỉnh chuỗi ở trung tâm, và chiều dài của chuỗi là 40 Year 2022 48
  • 158.
    String AI VIETNAM All-in-One Course strip():Loại bỏ khoảng trắng ở cả hai đầu của chuỗi replace(): Thay thế chuỗi partition(): Tách chuỗi Year 2022 49
  • 159.
    String AI VIETNAM All-in-One Course endswith():Kiểm tra phần kết thúc của một string. startswith(): Kiểm tra phần đầu của một string. find(): Tìm vị trí xuất hiện của string s1 trong string s2. Giá trị -1 được trả về trong trường hợp s1 không được tìm thấy trong s2. 50
  • 160.
    String  Common Error AIVIETNAM All-in-One Course index(): Tìm vị trí xuất hiện của string s1 trong string s2. Lỗi ValueError được trả về trong trường hợp s1 không được tìm thấy trong s2. Year 2022 51
  • 161.
    String  Common Error AIVIETNAM All-in-One Course Year 2022 52
  • 162.
     Conditions  Loops String  File Outline
  • 163.
    File  Typical procedure AIVIETNAM All-in-One Course Python A file (1) (2) (3) Connect to file Read from/write to file Disconnect to file (1) (2) (3) open(file_path, ‘r’) read() close() (1) (2) (3) Read from a file (already exist) 67
  • 164.
    File AI VIETNAM All-in-One Course Python Afile (1) (2) (3) Connect to file Read from/write to file Disconnect to file (1) (2) (3) open(file_path, ‘r’) readlines() close() (1) (2) (3) Read content from a file as lines  Typical procedure 68
  • 165.
    File AI VIETNAM All-in-One Course Python Afile (1) (2) (3) Connect to file Read from/write to file Disconnect to file (1) (2) (3) open(file_path, ‘w’) write() close() (1) (2) (3) Write to a file (not exist)  Typical procedure 69
  • 166.
    File Python A file (1) (2) (3) Connect tofile Read from/write to file Disconnect to file (1) (2) (3) open(file_path, ‘a’) write() close() (1) (2) (3) Write to a file (appending content if the file already exists)  Typical procedure 70
  • 167.
    File  Useful functions AIVIETNAM All-in-One Course Check if a file exists String splitting String joining Year 2022 71
  • 168.
    File  Common Error AIVIETNAM All-in-One Course Year 2022 72
  • 169.
  • 170.
    File  with keyword AIVIETNAM All-in-One Course Year 2022 74
  • 171.
  • 172.
  • 173.
    File  Text data IRIS data AI VIETNAM All-in-One Course Year 2022 77
  • 174.
  • 175.
  • 176.
     Conditions  Loops String  File  XML and JSON Processing Outline
  • 177.
    String - XML eXtensible Markup Language  Designed to store and transport data  Designed to be both human- and machine-readable. AI VIETNAM All-in-One Course Year 2022 53
  • 178.
    String - XML Example AI VIETNAM All-in-One Course Year 2022 54
  • 179.
    String - XML Example AI VIETNAM All-in-One Course Year 2022 55
  • 180.
    String - XML Syntax XML Prolog Attribute AI VIETNAM All-in-One Course Year 2022 56
  • 181.
    String - XML Syntax Element Opening tag Closing tag AI VIETNAM All-in-One Course Year 2022 57
  • 182.
    String - XML Example Element Opening tag Closing tag AI VIETNAM All-in-One Course Year 2022 58
  • 183.
    String - JSON JSON (JavaScript Object Notation)  Data exchange format  Lightweight  Text-based  Language-independent  Designed to be both human- and machine-readable. AI VIETNAM All-in-One Course Year 2022 59
  • 184.
    String - JSON Example AI VIETNAM All-in-One Course Year 2022 60
  • 185.
    String - JSON Example AI VIETNAM All-in-One Course Year 2022 61
  • 186.
    String - JSON Example AI VIETNAM All-in-One Course Year 2022 62
  • 187.
    String - JSON Syntax Object A pair AI VIETNAM All-in-One Course Year 2022 63
  • 188.
    String - JSON Syntax Object https://en.wikipedia.org/wiki/JSON AI VIETNAM All-in-One Course Year 2022 64
  • 189.
    String - JSON Syntax Array of objects https://en.wikipedia.org/wiki/JSON AI VIETNAM All-in-One Course Year 2022 65
  • 190.
    String - JSON Example AI VIETNAM All-in-One Course How!!! Year 2022 66
  • 192.
    Data Structure List Year 2022 Quang-VinhDinh Ph.D. in Computer Science AI VIETNAM All-in-One Course
  • 193.
     Introduction  List Some algorithms on List  Addresses  Common Errors Outline
  • 194.
    Abstract Data Types AIVIETNAM All-in-One Course 1 List 4 5 6 7 8 9 data = [4, 5, 6, 7, 8, 9] index 0 1 2 3 4 5 Strings ‘A’ ‘I’ name = 0 1 index dictionary_name = {key-1:value-1, …, key-n:value-n} colon comma bracket element tuple_name = (element-1, …, element-n)
  • 195.
    String  Create anditerate a string 2 AI VIETNAM All-in-One Course Year 2022 A I name = 0 1 index name = ‘AI’
  • 196.
    List  A containerthat can contain elements 3 AI VIETNAM All-in-One Course list_name = [element-1, …, element-n] Year 2022 6 5 7 1 9 2 data = 0 1 2 3 4 5 index
  • 197.
    List AI VIETNAM All-in-One Course Index 4 5 6 7 8 9 data = [4, 5, 6, 7, 8, 9] Backward index -6 -5 -4 -3 -2 -1 data[-1] 9 data[-3] 7 Forward index 0 1 2 3 4 5 data[0] 4 data[3] 7  Slicing 4 5 6 7 8 9 data = [4, 5, 6, 7, 8, 9] Forward index 0 1 2 3 4 5 6 7 data[2:4] 7 8 9 data[3:] 4 5 6 data[:3] Year 2022 4 list[start:end:step] Giá trị mắc định của start là 0, của end là len(list), và của step là 1
  • 198.
    List AI VIETNAM All-in-One Course Add an element 6 5 7 1 9 2 data = data.append(4) # thêm 4 vào vị trị cuối list 6 5 7 1 9 2 data = 4 6 5 7 1 9 2 data = data.insert(0, 4) # thêm 4 vào vị trị có # index = 0 6 5 7 1 9 2 data = 4 5
  • 199.
    List AI VIETNAM All-in-One Course 65 7 1 9 2 data = # thay đổi phần tử thứ 1 data[1] = 4 data = 6 4 7 1 9 2  Updating an element  Add a list of elements 6 5 7 1 data = data.extend([9, 2]) # thêm 9 và 2 vào vị trị cuối list 6 5 7 1 9 2 data = 6
  • 200.
    List AI VIETNAM All-in-One Course + and * operators 6 5 7 data1 = 1 9 2 data2 = # nối 2 list data = data1 + data2 6 5 7 1 9 2 data = 6 5 data = # nhân list với một số nguyên data_m = data * 3 6 5 data_m = 6 5 6 5 7
  • 201.
    List AI VIETNAM All-in-One Course sort() – Sắp xếp các phần tử 6 5 7 1 9 2 data = data = 1 2 5 6 7 9 data.sort() 6 5 7 1 9 2 data = data = 9 7 6 5 2 1 data.sort(reverse = True) 8
  • 202.
    List  Deleting anelement AI VIETNAM All-in-One Course 6 5 7 1 9 2 data = data.pop(2) # tại vị trí index = 2 6 5 1 9 2 data = 6 5 7 1 9 2 data = data.remove(5) # xóa phần tử đầu tiên # có giá trị là 5 6 7 1 9 2 data = Year 2022 9
  • 203.
    List AI VIETNAM All-in-One Course Delete elements 6 5 7 1 9 2 data = data.clear() data = [] 6 5 7 1 9 2 data = # xóa phần tử thứ 1 và 2 del data[1:3] data = 6 1 9 2 10
  • 204.
    List AI VIETNAM All-in-One Course 65 7 1 9 2 data = # trả về vị trí của phần tử đầu tiên có giá trị là 9 data.index(9) = 4 index() – Trả về vị trí đầu tiên reverse() – Đảo ngược vị trí các phần tử 6 5 7 1 9 2 data = data = 2 9 1 7 5 6 data.reserse() 11 Year 2022
  • 205.
    List AI VIETNAM All-in-One Course count()– Trả về số lần xuất hiện của một phần tử 6 5 7 1 9 2 data = # trả về số lần phần tử 7 xuất hiện trong list data.count(7) = 1 copy() – copy một list 6 5 7 1 9 2 data = data_copy = data_copy = data.copy() 6 5 7 1 9 2 12
  • 206.
    Built-in Functions forList Year 2022 len(), min(), and max() 6 5 7 1 9 2 data = # trả về số phần tử len(data) = 6 # trả về số phần tử có giá trị nhỏ nhất min(data) = 1 # trả về số phần tử có giá trị lớn nhất max(data) = 9 13
  • 207.
    Công thức Ápdụng cho hàm rời rạc (1D) Diện tích A 𝑓(𝑥) 𝑥 0 1 2 3 4 5 6 7 8 9 F 3 = ෍ 𝑥≤3 𝑓(𝑥) = 𝑓 0 + 𝑓 1 + 𝑓 2 + 𝑓 3 = 1 + 8 + 5 + 7 = 21 F 6 = ෍ 𝑥≤6 𝑓(𝑥) = 1 + 8 + 5 + 7 + 3 + 5 + 8 = 37 Diện tích A A = F 6 − F 3 = ෍ 4≤𝑥≤6 𝑓 𝑥 = 3 + 5 + 8 = 16 https://www.mathsisfun.com/calculus/integration-introduction.html F a = න −∞ 𝑎 𝑓(𝑥)𝑑(𝑥) F b = න −∞ 𝑏 𝑓 𝑥 𝑑(𝑥) Diện tích A 𝑓(𝑥) ≥ 0 A = F b − F(a) Example AI VIETNAM All-in-One Course 14
  • 208.
    Áp dụng chohàm rời rạc (1D) 0 1 2 3 4 5 6 7 8 9 𝑥 F 3 = ෍ 𝑥≤3 𝑓(𝑥) = 𝑓 0 + 𝑓 1 + 𝑓 2 + 𝑓 3 = 1 + 8 + 5 + 7 = 21 F 6 = ෍ 𝑥≤6 𝑓(𝑥) = 1 + 8 + 5 + 7 + 3 + 5 + 8 = 37 Diện tích A A = F 6 − F 3 = ෍ 4≤𝑥≤6 𝑓 𝑥 = 3 + 5 + 8 = 16 F x = 𝑓 𝑥 + F x − 1 F 7 = 𝑓 7 + F 6 = 3 + 37 = 40 Tính chất Xây dựng integral array dùng tính chất F x = 𝑓 𝑥 + F x − 1 𝑓(𝑥) 0 1 2 3 4 5 6 7 8 9 𝑥 𝐹(𝑥) + + + + + + + + + Tính tổng với độ phức tạp ~ O(1) ෍ 𝑎≤𝑥≤𝑏 𝑓 𝑥 = F b − F a − 1 ෍ 4≤𝑥≤6 𝑓 𝑥 = F 6 − F 3 = 37 − 21 = 16 Example AI VIETNAM All-in-One Course 15
  • 209.
    Built-in Functions  sorted(aList)– Sắp xếp các phần tử 6 5 7 1 9 2 data = sorted_data = 1 2 5 6 7 9 sorted_data = sorted(data) 6 5 7 1 9 2 data = sorted_data = 9 7 6 5 2 1 sorted_data = sorted(data, reverse=True) sorted(iterable, reverse=reverse) 16
  • 210.
    Built-in Functions sum() 6 57 1 9 2 + result data = 6 5 7 1 9 2 data = # tính tổng sum(data) = 30 𝑠𝑢𝑚𝑚𝑎𝑡𝑖𝑜𝑛 = ෍ 𝑖=0 𝑛 𝑑𝑎𝑡𝑎𝑖
  • 211.
    Built-in Functions sum() 6 57 1 9 2 + result 0 1 2 3 4 5 index data = 6 5 7 1 9 2 data = # tính tổng sum(data) = 30 18 Using index 𝑠𝑢𝑚𝑚𝑎𝑡𝑖𝑜𝑛 = ෍ 𝑖=0 𝑛 𝑑𝑎𝑡𝑎𝑖
  • 212.
    Built-in Functions zip() 1 23 data1 = Year 2022 19 5 6 7 data2 = 1 5 2 6 3 7
  • 213.
    Built-in Functions reversed() 6 17 data = Year 2022 20 AI VIETNAM All-in-One Course 7 1 6 reversed(data) =
  • 214.
    Built-in Functions enumerate() data = Year2022 enumerate(data) = 6 1 7 6 1 7 0 1 2 index 21
  • 215.
    Examples AI VIETNAM All-in-One Course Sumof even numbers 6 5 7 1 9 2 data = Sum of elements with even indices 6 5 7 1 9 2 data =
  • 216.
    Examples AI VIETNAM All-in-One Course square(aList) 65 7 1 9 2 data = 36 25 49 1 81 4 square(data) = Year 2022 23
  • 217.
    List Comprehension AI VIETNAM All-in-OneCourse Year 2022 omitted added 24
  • 218.
    List Comprehension Sigmoid Function σ 𝑥= 1 1 + 𝑒−𝑥 σ′(𝑥) = σ(𝑥)(1 − σ(𝑥))
  • 219.
    List Comprehension ReLU Function ReLU 𝑥= ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 ReLU ′ 𝑥 = ቊ 0 if 𝑥 ≤ 0 1 if 𝑥 > 0 26
  • 220.
    List Comprehension ReLU Function ReLU 𝑥= ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 ReLU ′ 𝑥 = ቊ 0 if 𝑥 ≤ 0 1 if 𝑥 > 0 27
  • 221.
    List Comprehension AI VIETNAM All-in-OneCourse [condition_to_branch_x for x in data condition_to_filter_x]
  • 222.
  • 223.
    Mutable and Immutable AIVIETNAM All-in-One Course 51 30 Year 2022
  • 224.
    Algorithms on List Linear searching 6 5 7 1 9 2 data = 0 1 2 3 4 5 index 6 5 7 1 9 2 start Searching for 9 Returning 4 0 1 2 3 4 5 index 6 5 7 1 9 2 start Searching for 8 Returning ? 0 1 2 3 4 5 index end If iterating the last item item  getItem() Returning index index = -1 31 if item==value, indexgetIndex()
  • 225.
    Algorithms on List Sorting using min(), remove(), and append() Year 2022 32 6 5 7 1 9 2 data = result = [ ] min(data) = 1 data.remove(1) = 6 5 7 9 2 result.append(1) = 1 . . . if the list is non-empty? item  getMin() append(item) to result remove(item) from list
  • 226.
    Algorithms on List Sorting using min(), remove(), and append() Year 2022 33 6 5 7 9 2 data = result = 1 min(data) = 2 data.remove(2) = 6 5 7 9 result.append(2) = 1 . . . 2 if the list is non-empty? item  getMin() append(item) to result remove(item) from list
  • 227.
  • 228.
  • 229.
    Converting to List AIVIETNAM All-in-One Course aList  list(iterable) 4 5 6 7 8 9 data = list(range(4, 10) index 0 1 2 3 4 5 A I data = 0 1 index name = ‘AI’ data = 34
  • 230.
    Plotting a function Using matplotlib AI VIETNAM All-in-One Course 35 x-data y-data
  • 231.
    Plotting a function Using matplotlib AI VIETNAM All-in-One Course 36 How to do it? 𝑥 ∈ −8, 8 𝑦 = 𝑥2
  • 232.
    List and File Read and Write from/to a log file AI VIETNAM All-in-One Course 37
  • 233.
     Introduction  List Some algorithms on List  Addresses  Common Errors Outline
  • 234.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 38 20 x 140707105248672 y 140707105248672 10 x 140707105248352 y 140707105248672 20 Year 2022
  • 235.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 39  Immutable types: Cannot be changed in place  Including ints, floats, strings, and tuples “AI” x 1511427632072 “AI” x 1511427632072 1511427661360 “AI VIETNAM” destroyed automatically Year 2022
  • 236.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 40  Immutable types: Cannot be changed in place  Including ints, floats, strings, and tuples “AI” x 1511427633024 y 1511427633024 x 1511427693808 “AI VIETNAM” “AI” y 1511427633024 Year 2022
  • 237.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 41 1 2 3 0 1 2 a_list 1511426884232 1 2 3 4 0 1 2 3 5 4 a_list 1511427661128 4 0 5 1 a_list = a_list + Year 2022
  • 238.
    Variables and Addresses AIVIETNAM All-in-One Course 4 42 . . . 0 1 2 a_list 1511426884232 1 2 3 x a1 = 140707105248064 a2 = 140707105248096 a3 = 140707105248128 a1 a2 a3 a1 a2 a3 Year 2022
  • 239.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 43 . . 0 1 a_list 1511426884232 1 2 x a1 = 140707105248064 a2 = 140707105248096 a1 a2 a1 a2 20 Year 2022
  • 240.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 44 value 3 a1 = 140707105248128 a2 = 140707105248320 square number result 9 result a1 a1 a2 a2 Year 2022
  • 241.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 45 value 3 a1 = 140707105248128 a2 = 140707105248320 square number result 9 result a1 a1 a2 a2 Year 2022
  • 242.
    a1 = 1511427661128 a2= 140707105248160 square input_list number a2 . . . 0 1 2 a_list a1 1 2 3 a3 a4 a5 4 46
  • 243.
    a1 = 1511428290376 a2= 140707105248160 square input_list number a2 . . . 0 1 2 a_list a1 1 2 3 a3 a4 a5 4 . 3 a2 47
  • 244.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 48 add a_list number 1 2 3 0 1 2 a_list address 1 4 address 2 Year 2022
  • 245.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 49 add a_list number 1 2 3 0 1 2 a_list address 1 4 address 2 1 2 3 0 1 2 4 3 address 3 Year 2022
  • 246.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 50 add a_list number 1 2 3 0 1 2 a_list address 1 4 address 2 1 2 3 0 1 2 4 3 address 3 Year 2022
  • 247.
    Variables and Addresses 4 AIVIETNAM All-in-One Course 51 1 2 3 0 1 2 a_list address 1 4 1 2 3 0 1 2 4 3 Year 2022
  • 248.
    Mutable and Immutable AIVIETNAM All-in-One Course 52 6 5 7 1 9 2 data 36 25 49 1 81 4 result square data data_s
  • 249.
    Mutable and Immutable AIVIETNAM All-in-One Course 6 5 7 1 9 2 data 6 value square data Get from data[0] 36 5 7 1 9 2 data 36 value*value square data Set to data[0] 53
  • 250.
    List Copy 4 AI VIETNAM All-in-OneCourse 54 1 2 3 4 0 1 2 3 5 4 list1 1700123138824 Memory address list2 1700123138824 list2 = list1 1 2 3 4 0 1 2 3 5 4 list1[3] = 9 Replace 4 by 9 1 2 3 9 0 1 2 3 5 4 list1 1700123138824 list2 1700123138824 Year 2022
  • 251.
    List Copy 4 AI VIETNAM All-in-OneCourse 55 1 2 3 4 0 1 2 3 5 4 list1[3] = 9 Replace 4 by 9 1 2 3 9 0 1 2 3 5 4 list1 1700123139912 list2 1700123139976 1 2 3 4 0 1 2 3 5 4 1 2 3 4 0 1 2 3 5 4 list1 1700123139912 list2 1700123139976 1 2 3 4 0 1 2 3 5 4 list2 = copy.copy(list1)
  • 252.
    List Copy . 3 01 1 2 0 1 1700123189704 List1[0][0] = 9 Replace 1 by 9 . 3 0 1 list1 1700123189832 list2 1700123189960 . 3 9 2 0 1 1700123189704 0 1 . 3 0 1 list1 1700123189832 list2 1700123189960 . 3 1 2 0 1 1700123189704 0 1 list2 = copy.copy(list1) 56
  • 253.
    . 3 0 1 12 0 1 1700124007112 List1[0][0] = 9 Replace 1 by 9 . 3 0 1 list1 1700124007240 9 2 0 1 1700124007112 list2 1700124007176 . 3 0 1 1 2 0 1 1700124007304 . 3 0 1 list1 1700124007240 1 2 0 1 1700124007112 list2 1700124007176 . 3 0 1 1 2 0 1 1700124007304 list2 = copy. deepcopy(list1) 57
  • 254.
    Quizzes AI VIETNAM All-in-One Course Year2022  Small number caching Caching integers in [-5, 256]
  • 255.
     Introduction  List Some algorithms on List  Addresses  Common Errors Outline
  • 256.
    Common Errors  Error1 AI VIETNAM All-in-One Course 58 Year 2022
  • 257.
    Common Errors  Error2 AI VIETNAM All-in-One Course 59 Year 2022
  • 258.
    Common Errors  Error3 AI VIETNAM All-in-One Course 60 Year 2022
  • 259.
    Common Errors  Error4 AI VIETNAM All-in-One Course 61 Year 2022
  • 260.
    Common Errors  Error5 AI VIETNAM All-in-One Course 62 Year 2022
  • 261.
    Common Errors  Error6 AI VIETNAM All-in-One Course 63 Year 2022
  • 262.
    Common Errors  Error7 AI VIETNAM All-in-One Course 64 Year 2022
  • 263.
    Common Errors  Error8 AI VIETNAM All-in-One Course 65 Year 2022
  • 264.
    Common Errors  Error9 AI VIETNAM All-in-One Course 66 Year 2022
  • 265.
    Common Errors  Error10 AI VIETNAM All-in-One Course 67 Year 2022
  • 266.
    Common Errors  Error11 AI VIETNAM All-in-One Course 68 Year 2022
  • 267.
    Common Errors  Error12 AI VIETNAM All-in-One Course 69 Year 2022
  • 268.
    Common Errors  Error13 AI VIETNAM All-in-One Course 70 Year 2022
  • 269.
    Common Errors  Error14 AI VIETNAM All-in-One Course 71 Year 2022
  • 270.
    Common Errors  Error15 AI VIETNAM All-in-One Course 72 Year 2022
  • 271.
    Common Errors  Error16 AI VIETNAM All-in-One Course 73 Year 2022
  • 272.
    Common Errors  Error17 AI VIETNAM All-in-One Course 74 Year 2022
  • 273.
    Common Errors  Error18 AI VIETNAM All-in-One Course 75 Year 2022
  • 274.
    Common Errors  Error19 AI VIETNAM All-in-One Course 76 Year 2022
  • 275.
    Common Errors  Error20 AI VIETNAM All-in-One Course 77 Year 2022
  • 276.
    Common Errors  Error21 AI VIETNAM All-in-One Course 78 Year 2022
  • 277.
    Common Errors  Error22 AI VIETNAM All-in-One Course numbers = [1, 2, 3, 4, 5] 1 Output numbers = [1, 2, 3, 4, 5] 1, 2 Output numbers = [1, 2, 3, 4, 5] 1, 2, 3 Output numbers = [1, 2, 3, 4, 5, 3] 79 Year 2022
  • 278.
    Common Errors  Error22 AI VIETNAM All-in-One Course numbers = [1, 2, 3, 4, 5, 3] 1, 2, 3, 4, 5, 3 Output numbers = [1, 2, 3, 4, 5, 3, 3] 80 Year 2022
  • 279.
    Common Errors  Error22 AI VIETNAM All-in-One Course numbers = [1, 2, 3, 4, 5, 3] 1, 2, 3, 4, 5, 3 Output numbers = [1, 2, 3, 4, 5, 3, 3] 1, 2, 3, 4, 5, 3, 3 Output numbers = [1, 2, 3, 4, 5, 3, 3, 3] ° ° ° 81 Year 2022
  • 280.
    Common Errors  Error25 AI VIETNAM All-in-One Course Year 2022 82
  • 281.
    Common Errors  Error26 AI VIETNAM All-in-One Course ??? Year 2022 83
  • 282.
    Common Errors  Error27 AI VIETNAM All-in-One Course Year 2022 84
  • 283.
  • 284.
    Further Reading  List(Chapters 6 and 13) AI VIETNAM All-in-One Course 86  Binary Searching and Sorting
  • 286.
    Data Structure Tuple, Set,and Dictionary Year 2022 Quang-Vinh Dinh Ph.D. in Computer Science AI VIETNAM All-in-One Course
  • 287.
     Common Errors(Quick Review)  Tuple  Set  Dictionary  Code Optimization Outline
  • 288.
    Tuple  Structure AI VIETNAM All-in-OneCourse tuple_name = (element-1, …, element-n) Create a tuple Tuple unpacking Year 2022 1
  • 289.
    Tuple AI VIETNAM All-in-One Course tuple_name= (element-1, …, element-n) ( ) can be removed Tuple with one element Year 2022  Structure 2
  • 290.
    Tuple  + and* operators AI VIETNAM All-in-One Course index() - tìm vị trí xuất hiện của một giá trị count() - đếm số lần xuất hiện của một giá trị Year 2022 3
  • 291.
    Tuple len() - Tìmchiều dài của một tuple Lấy giá trị min và max của một tuple Dùng hàm zip() cho tuple Sắp xếp các giá trị trong một tuple Year 2022 4
  • 292.
    Tuple  Immutable 5 AI VIETNAM All-in-OneCourse however Year 2022 1 2 add2 0 1 2 t add1 3 10 0 1
  • 293.
    Tuple Examples AI VIETNAM All-in-OneCourse Swapping two variables list2tuple tuple2list Memory requirement Tuple slicing 6
  • 294.
    Tuple  Example: Solvequadratic equation AI VIETNAM All-in-One Course Case 1: delta<0 Case 2: delta>0 Case 3: delta=0 Data is protected Year 2022 7
  • 295.
     Common Errors(Quick Review)  Tuple  Set  Dictionary  Code Optimization Outline
  • 296.
    Set  Create aset AI VIETNAM All-in-One Course Items with different data types Using curly brackets Set comprehension Year 2022 8
  • 297.
    Set AI VIETNAM All-in-One Course Accessthe items of a set Copy a set Year 2022 9
  • 298.
    Set AI VIETNAM All-in-One Course Addan item Insert a set to another set Join two sets Not allow duplicate values Year 2022 10
  • 299.
    Set AI VIETNAM All-in-One Course differencefunction difference_update function symmetric_difference symmetric_difference_update 11
  • 300.
    Set AI VIETNAM All-in-One Course Bitwise operator Year 2022 12
  • 301.
    Set  Remove anitem AI VIETNAM All-in-One Course remove(item) Remove an item from the set. https://docs.python.org/3/library /stdtypes.html?t#set discard(item) Remove an item from the set if it is present. Year 2022 Set comprehension 13
  • 302.
    Set AI VIETNAM All-in-One Course remove(item) Removean item from the set. Raises KeyError if elem is not contained in the set. https://docs.python.org/3/library/stdtypes.html?t#set discard(item) Remove an item from the set if it is present. Year 2022  Remove an item 14
  • 303.
    Set  Create aset AI VIETNAM All-in-One Course Unordered and unindexed Cannot contain unhashable types Year 2022 15
  • 304.
    Set AI VIETNAM All-in-One Course Year2022 Set  List and Tuple ??? ??? 16
  • 305.
    - 50,000 moviereview for sentiment analysis (data) - Consist of: + 25,000 movie review for training + 25,000 movie review for testing - Label: positive – negative = 1 – 1 “A wonderful little production. <br /><br />The filming technique is very unassuming- very old- time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the entire piece…..” positive “This show was an amazing, fresh & innovative idea in the 70's when it first aired. The first 7 or 8 years were brilliant, but things dropped off after that. By 1990, the show was not really funny anymore, and it's continued its decline further to the complete waste of time it is today….” negative “I thought this was a wonderful way to spend time on a too hot summer weekend, sitting in the air conditioned theater and watching a light-hearted comedy. The plot is simplistic, but the dialogue is witty and the characters are likable (even the well bread suspected serial killer)….” positive “BTW Carver gets a very annoying sidekick who makes you wanna shoot him the first three minutes he's on screen.” negative Set AI VIETNAM AI Course  Text classification
  • 306.
    Set  Text classification AIVIETNAM AI Course Output 𝑧 Sigmoid activation Fully-connected layer Text Sample Preprocessing (standardization & vectorization) Embedding Preprocessing Year 2022 18
  • 307.
    Embedding - Example corpus sample1:‘We are learning AI’ sample2: ‘AI is a CS topic’ (1) Build vocabulary from corpus (2) Transform text into features index 0 1 2 3 4 5 6 7 word pad are/a ai we topic learning is cs We are learning AI we are learning ai Standardize 3 1 5 2 0 AI is a CS topic ai is a cs topic 2 6 1 7 4 Vectorization 19
  • 308.
    Embedding Layer (3) Embeddinglayer index word 0 pad 1 are/a 2 AI 3 We 4 Topic 5 Learning 6 is 7 cs We are learning AI 3 1 5 2 0 Output 𝑧 Sigmoid activation Fully-connected layer Embedding 20
  • 309.
    Set AI VIETNAM AI Course Convert text to numbers
  • 310.
     Common Errors(Quick Review)  Tuple  Set  Dictionary  Code Optimization Outline
  • 311.
    Dictionary AI VIETNAM All-in-One Course Structure Create a dictionary dictionary_name = {key-1:value-1, …, key-n:value-n} colon comma bracket element Year 2022 22
  • 312.
    Dictionary AI VIETNAM All-in-One Course Create a Dictionary Year 2022 23
  • 313.
    Dictionary AI VIETNAM All-in-One Course Update a value  Copy a dictionary Year 2022 24
  • 314.
    Dictionary AI VIETNAM All-in-One Course Hàm copy() chỉ sao chép kiểu shallow  Sử dụng hàm deepcopy() trong module copy Year 2022 25
  • 315.
    Dictionary AI VIETNAM All-in-One Course Get keys and values Get keys Get values Get keys and values Get keys Year 2022 26
  • 316.
    Dictionary AI VIETNAM All-in-One Course Get a value by a key Get value using get() function Get value and delete the corresponding item Year 2022 27
  • 317.
    Dictionary AI VIETNAM All-in-One Course popitem()- lấy ra một phần tử ở cuối dictionary clear() - xóa tất cả các phần tử của một dictionary Use del keyword to delete an item Year 2022 28
  • 318.
    Dictionary AI VIETNAM All-in-One Course Key that does not exist Try to delete a non-existing item Try to get an item by a non-existing key Year 2022 29
  • 319.
    Dictionary setdefault() function 4 AI VIETNAM All-in-OneCourse 30 example Result ??? Year 2022
  • 320.
    Dictionary Method 1 4 AI VIETNAM All-in-OneCourse 31 Method 2  Get a value via a key Year 2022
  • 321.
    Dictionary Merge two dictionaries AIVIETNAM All-in-One Course Check if a key exists Remove empty items 32 Dictionary comprehension
  • 322.
  • 323.
  • 324.
    Dictionary Saving andLoading  JSON (JavaScript Object Notation) Year 2021 AI VIETNAM All-in-One Course  Data exchange format  Lightweight  Text-based  Language-independent  Designed to be both human- and machine-readable.
  • 325.
    Dictionary Saving andLoading AI VIETNAM All-in-One Course Year 2022 36
  • 326.
    Sorting AI VIETNAM All-in-One Course Year2022 37 sorted(iterable, key=None, reverse=False) item=7
  • 327.
  • 328.
    Sorting AI VIETNAM All-in-One Course Year2022 item=(‘g’, 13) a g e list1 = h b 16 13 18 list2 = 11 15 list3 = a g e h b 16 13 18 11 15 item
  • 329.
    Lambda function  Takeany number of arguments  Can only have one expression Year 2022 AI VIETNAM All-in-One Course Syntax lambda arguments : expression 40
  • 330.
    Sorting AI VIETNAM All-in-One Courseitem=(‘g’, 13) Using lambda function
  • 331.
     Common Errors(Quick Review)  Tuple  Set  Dictionary  Code Optimization Outline
  • 332.
    Code Optimization (1) Use built-in functions AI VIETNAM All-in-One Course Tìm các phần tử duy nhất trong list Tính tổng các phần tử trong list 42
  • 333.
    Code Optimization (2) Use built-in functions AI VIETNAM All-in-One Course Dùng list comprehension Đếm số phần tử trong list dùng Counter
  • 334.
  • 335.
  • 336.
  • 337.
  • 338.
  • 339.
  • 340.
  • 341.
  • 342.
  • 343.
  • 344.
  • 345.
  • 346.
  • 347.
  • 348.
  • 349.
     Common Errors(Quick Review)  Tuple  Set  Dictionary  Code Optimization Outline
  • 350.
    Stack 4 AI VIETNAM All-in-One Course 59 Year2022  Introduction 1 2 3 4 TOP POP PUSH LAST IN FIRST OUT STACK 2 3 4 1 2 3 4 FULL STACK EMPTY STACK 1 PUSH 2 1 POP PEEK TOP STACK OPERATIONS
  • 351.
    Stack 4 AI VIETNAM All-in-One Course 60 Year2022 Simple Implementation TOP=NULL STEP1 Create Empty Stack TOP=12 STEP2 PUSH(12) 12 TOP TOP=8 STEP3 PUSH(8) 12 8 TOP TOP=21 STEP3 PUSH(21) 12 8 21 TOP
  • 352.
    Stack AI VIETNAM All-in-One Course Year2022 TOP=33 STEP1 Create Stack 12 8 21 33 TOP TOP=33 TOP=21 12 8 21 33 12 8 21 STEP2 POP() TOP TOP=21 TOP=8 12 8 21 12 8 STEP3 POP() TOP TOP=8 TOP=12 12 8 12 STEP4 POP() TOP
  • 353.
    Queue AI VIETNAM All-in-One Course Introduction Enqueue Dequeue Add an element to the end of the queue Remove an element from the front of the queue 2 4 7 3 5 Enqueue Dequeue First in – First out 5 Enqueue 3 Enqueue 5 3 5 Dequeue 3 62
  • 354.
  • 355.
  • 357.
    Object-Oriented Programming Year 2022 Quang-Vinh Dinh Ph.D.in Computer Science AI VIETNAM All-in-One Course
  • 358.
  • 359.
     Introduction  Classesand Objects  Iterator and Class Data Type  Inheritance  Exercises Outline
  • 360.
    OOP Introduction Procedural programming Year2022 data 1 data 2 data n data 3 Function 1 Function 2 Function k Top-down approach Security Maintenance Reusability … Implementation Implementation AI VIETNAM All-in-One Course 1
  • 361.
    OOP Introduction OOP programming Year2022 Bottom-up approach Security Maintenance Reusability Implementation Access modifiers Inheritance Objects/Classes data 1 Function 1 data 3 Function 2 data n Function k Encapsulation Polymorphism AI VIETNAM All-in-One Course 2
  • 362.
    Introduction  What isOOP? Year 2022 Creating objects that contain both data and functions Data 1 Data 2 Data n Task 1 function 1 function 2 Task n functions Procedural programming Object-oriented programming Object 1 Data and Functions Object n Data and Functions relationship Writing functions that perform operations on the data AI VIETNAM All-in-One Course 3
  • 363.
    Introduction  OOP advantages Year2022 A clear structure Easier to maintain, modify and debug Reusable Doctor Assistant Waiter Doctor (struct) Assistant (struct) Waiter (struct) AI VIETNAM All-in-One Course 4
  • 364.
    Introduction  Classes andObjects Year 2022 A class is a template for objects, and an object is an instance of a class. Fruit Strawberry Apple Banana AI VIETNAM All-in-One Course 5
  • 365.
    Introduction  Classes andObjects Year 2022 A class is a template for objects, and an object is an instance of a class. Animal Cat Deer Tiger AI VIETNAM All-in-One Course 6
  • 366.
    Introduction  Classes andObjects A class is a template for objects, and an object is an instance of a class. Cat Japanese Bobtail Scottish Fold Calico AI VIETNAM All-in-One Course 7
  • 367.
    Introduction  Classes andObjects https://www.visual- paradigm.com/guide/uml-unified-modeling- language/uml-class-diagram-tutorial/ AI VIETNAM All-in-One Course 8
  • 368.
    Classes and Objects Abstract view Year 2022 Cat Attributes Functions/ Actions Name Color Age Sleep Walk Eat Cat name color age sleep walk eat Class Diagram AI VIETNAM All-in-One Course 9
  • 369.
    Class Diagram  Describethe structure of a system Classes their attributes operations (methods) relationships among objects Class name Attributes Methods - private + public Access modifiers A cat includes a name, a color, and an age. The daily activities of the cat consists of sleeping, walking, and eating. Draw a class diagram for the above description. All the attributes and methods are publicly accessed. 3 parts Cat + name: string + color: string + age: int + sleep(): void + walk(): void + eat(): void AI VIETNAM All-in-One Course 10 Year 2022
  • 370.
    OOP Introduction Detect Class andits Members AI VIETNAM All-in-One Course Book + author: string + title: string + genre: string + price: double + date: string + publisher: string + description: string … Year 2022 11
  • 371.
    Objects and Classes Create a function in a class AI VIETNAM All-in-One Course The __init__() function is called automatically every time the class is being used to create a new object. The self parameter is a reference to the current instance of the class. __call__() function: instances behave like functions and can be called like a functions. Year 2022 12
  • 372.
    Objects and Classes Create a class Using init() function Change property values Year 2022 13
  • 373.
    self Keyword Year 2022 self intside; int side; Must be the first argument of methods Used to create and access data members AI VIETNAM All-in-One Course 14
  • 374.
    Classes and Objects Wehave a new data type cat = Cat(‘Calico’, ‘BW’, 2) create an object variable AI VIETNAM All-in-One Course For class names Including words concatenated Each word starts with upper case For attribute names Including words concatenated Each word starts with upper case except the first word Naming conventions Cat + name: string + color: string + age: int … Year 2022
  • 375.
    Exercise Implementation Book + author: string +title: string + genre: string + price: double + date: string + publisher: string + description: string … Implement the Book class in Python 16 AI VIETNAM All-in-One Course
  • 376.
    Classes and Objects Backto the Cat example Cat + name: string … … AI VIETNAM All-in-One Course Year 2022 17
  • 377.
    Classes and Objects Problemand Solution: Step 1 – implement getter and setter functions Cat + name: string … + getName(): string + setName(string): void … - private + public Access modifiers AI VIETNAM All-in-One Course Year 2022
  • 378.
    Classes and Objects Solution:Step 2 – Using private for attributes Cat - name: string … + getName(): string + setName(string): void … - private + public Access modifiers 19
  • 379.
    Classes and Objects Takeaways Cat -name: string - color: string - age: int + getName(): string + setName(string): void + getColor(): string + setColor(string): void + getAge(): int + setAge(int): void - private + public Access modifiers Use the private access modifiers for typical attributes Create getter and setter functions to access protected attributes Use the public access modifiers for the getter and setter functions A cat includes a name, a color, and an age. AI VIETNAM All-in-One Course 20 Year 2022
  • 380.
     Introduction  Classesand Objects  Iterator and Class Data Type  Inheritance  Exercises Outline
  • 381.
    Iterator AI VIETNAM All-in-One Course 1Create iterator using iter() 2 Get value using next() Year 2022 21
  • 382.
    Iterator AI VIETNAM All-in-One Course 22 __iter__():set initialization for the iterator __next__(): get a value of the iterator update the state of the iterator Using raise StopIteration
  • 383.
  • 384.
    Iterator AI VIETNAM All-in-One Course Year2022  List 10 next Data Pointer Node1 HEAD 20 next Data Pointer Node2 30 next Data Pointer Node3 NULL Singly linked list 24
  • 385.
  • 386.
    Iterator AI VIETNAM All-in-One Course Year2022  List 10 next Data Pointer Node1 HEAD 20 next Data Pointer Node2 30 next Data Pointer Node3 None Singly linked list
  • 387.
    Lists and Classes 17 Sorta list of numbers AI VIETNAM All-in-One Course 27
  • 388.
    Lists and Classes 28 Sorta list of squares AI VIETNAM All-in-One Course Year 2022
  • 389.
    Lists and Classes 29 Sorta list of squares AI VIETNAM All-in-One Course Year 2022
  • 390.
    Class Data Type Year2022 A person comprises a name in string and a date of birth. A date consists of day, month, and year. Write a function to check if two people have the same name. Write a function to check if two people have the same date of birth. Draw a class diagram and implement in Python Using a class as a data type 30 AI VIETNAM All-in-One Course
  • 391.
    Class Data Type Usinga class as a data type A person comprises a name in string and a date of birth. A date consists of day, month, and year. Draw a class diagram and implement in Python - name: string - dateOfBirth: Date + describe(): void Person - day: int - month: int - year: int + describe(): void Date AI VIETNAM All-in-One Course 31
  • 392.
    Class Data Type Usinga class as a data type A person comprises a name in string and a date of birth. A date consists of day, month, and year. - name: string - dateOfBirth: Date + describe(): void Person - day: int - month: int - year: int + describe(): void Date Using Date as a data type AI VIETNAM All-in-One Course 32 Year 2022
  • 393.
    Class Data Type AIVIETNAM All-in-One Course Aggregation
  • 394.
    Class Data Type Aperson comprises a name in string and a date of birth. A date consists of day, month, and year. Write a function to check if two people have the same name. Write a function to check if two people have the same date of birth. Using a class as a data type - name: string - dateOfBirth: Date + describe(): void + checkSameName(string): bool + checkSameAge(int): bool Person - day: int - month: int - year: int + describe(): void Date - name: string - dateOfBirth: Date + describe(): void + checkSameName(string): bool + checkSameAge(Date): bool Person - day: int - month: int - year: int + describe(): void Date AI VIETNAM All-in-One Course
  • 395.
    Custom MLP forFashion-MNIST  ReLU and SGD Year 2022 784 Nodes Input layer Output 1 𝑧1 𝑧10 Softmax activation 1 ReLU activation 128 Nodes Hidden layer Fully connect Fully connect 10 Nodes Output layer 28 28 784 flatten data … … AI VIETNAM All-in-One Course
  • 396.
    Custom MLP forFashion-MNIST  Custom ReLU ReLU 𝑥 = ቊ 0 if 𝑥 ≤ 0 𝑥 if 𝑥 > 0 init method call method Initialize values/variables necessary for a class Forward computation max(0, x) AI VIETNAM All-in-One Course Year 2022
  • 397.
    Custom MLP forFashion-MNIST Custom Dense init method call method Initialize values/variables necessary for a class Forward computation 𝒛 = 𝒙𝜽 784 Nodes Input layer 1 1 ReLU activation 128 Nodes Hidden layer Fully connect … num_outputs = 128 input_shape = (None, 784) 𝜽 = 𝜽𝟏 𝜽𝟐 … 𝜽𝟏𝟐𝟖 build method Do something using the shape of the input tensors
  • 398.
  • 399.
     Introduction  Classesand Objects  Iterator and Class Data Type  Inheritance  Exercises Outline
  • 400.
    Inheritance  Introduction Year 2022 Mechanismby which one class is allowed to inherit the features (attributes and methods) of another class. Subclass: The class that inherits the other class is known as subclass (a derived class, extended class, or child class). The subclass can add its own attributes and methods in addition to the superclass attributes and methods. Super Class: The class whose features are inherited is known as superclass (a base class or a parent class). AI VIETNAM All-in-One Course 40
  • 401.
    Inheritance Year 2022  Introduction Person -name: string // … Employee - name: string - annualSalary: double - yearOfStartingWork: int - insuaranceNumber: string // … AI VIETNAM All-in-One Course 41
  • 402.
    Inheritance Person # name: string //… Employee - annualSalary: double - yearOfStartingWork: int - insuaranceNumber: string // … is Person - name: string // … Employee - name: string - annualSalary: double - yearOfStartingWork: int - insuaranceNumber: string // … - private + public Access modifiers # protected An employee is a person. Person Employee is-a relationship AI VIETNAM All-in-One Course
  • 403.
    Inheritance Inherit attributes andmethods from one class to another Benefit: Code reusability Derived class (child) - the class that inherits from another class Base class (parent) - the class being inherited from DerivedClass(BaseClass) Animal # name: string + setName(string): void Cat // … is A cat is an animal. Animal Cat is-a relationship AI VIETNAM All-in-One Course 43
  • 404.
    Inheritance Year 2022 Super Class Subclass UMLAnnotation ‘-’stands for ‘private’ ‘#’ stands for ‘protected’ ‘+’ stands for ‘public’ What features does a manager inherit?  Introduction To extend an existing class Employee # name: string # salary: double + computeSalary(): double Manager - bonus: double + computeSalary(): double is AI VIETNAM All-in-One Course 44
  • 405.
    Inheritance  As atemplate Year 2022 https://beginnersbook.com/2013/05/java-abstract-class-method/ A class Animal that has a method sound() and the subclasses of it like Dog, Lion, Horse, Cat, etc. Since the animal sound differs from one animal to another, there is no point to implement this method in parent class. This is because every child class must override this method to give its own implementation details, like Lion class will say “Roar” in this method and Dog class will say “Woof”. AI VIETNAM All-in-One Course 45
  • 406.
    Inheritance Year 2022  Asa template Animal + sound(): void is Horse + sound(): void Dog + sound(): void Lion + sound(): void AI VIETNAM All-in-One Course 46
  • 407.
    Example  Implement thetwo classes below Math1 + __init__() + isEven(int): bool + factorial(int): int Math2 + __init__() + isEven(int): bool + factorial(int): int + estimateE(int): double AI VIETNAM All-in-One Course 47 Year 2022
  • 408.
    Example Year 2022 Math1 + __init__() +isEven(int): bool + factorial(int): int Implement the two classes below AI VIETNAM All-in-One Course 48
  • 409.
    Example Math2 + __init__() + isEven(int):bool + factorial(int): int + estimateEuler(int): double Implement the two classes below 𝑒 = 2.71828 AI VIETNAM All-in-One Course Year 2022
  • 410.
    Example Math2 + __init__() + isEven(int):bool + factorial(int): int + estimateEuler(int): double Implement the two classes below 𝑒 = 2.71828 AI VIETNAM All-in-One Course 50 Year 2022
  • 411.
    Example How to reusean existing class? Math1 + __init__() + isEven(int): bool + factorial(int): int Math2 + __init__() + isEven(int): bool + factorial(int): int + estimateEuler(int): double AI VIETNAM All-in-One Course
  • 412.
    Example  Inheritance Year 2022 Math1:super class or parent class Math2: child class or derived class Child classes can use the public and protected attributes and methods of the super classes. Math1 + __init__() + isEven(int): bool + factorial(int): int Math2 + __init__() + estimateEuler(int): double 52 AI VIETNAM All-in-One Course
  • 413.
  • 414.
  • 415.
    Another Example Employee-Manager Example:Simple requirement A standard employee of company X includes his/her name and base salary. For example, Peter is working for X, and his base salary is 60000$ a year. Implement the Employee class and the computeSalary() method to compute the final salary for an employee. The salary for an employee is his/her base salary. A manager includes his/her name, base salary, and bonus. The final salary for the manager comprises the base salary and a bonus. For example, Mary is a manager in the company. Her base salary and bonus are 60000$ and 20000$ a year, respectively. Yearly, she gets paid 80000$ a year. Implement the Manager class and the computeSalary() method to compute the final salary. AI VIETNAM All-in-One Course Year 2022 Employee - name: string - salary: double + computeSalary(): double Manager - name: string - salary: double - bonus: double + computeSalary(): double
  • 416.
    Another Example Employee-Manager Example(Using inheritance) A standard employee of company X includes his/her name and base salary. For example, Peter is working for X, and his base salary is 60000$ a year. Implement the Employee class and the computeSalary() method to compute the final salary for an employee. The salary for an employee is his/her base salary. A manager is an employee who has the name and base salary attributes. However, the final salary for the manager comprises the base salary and a bonus. For example, Mary is a manager in the company. Her base salary and bonus are 60000$ and 20000$ a year, respectively. Yearly, she gets paid 80000$ a year. Implement the Manager class and the computeSalary() method to compute the final salary. AI VIETNAM All-in-One Course
  • 417.
    Another Example Employee-Manager Employee # name:string # salary: double + computeSalary(): double Manager - bonus: double + computeSalary(): double is 57
  • 418.
    Example  Inheritance recognition Year2022 Squares and circles are both examples of shapes. There are certain questions one can reasonably ask of both a circle and a square (such as, ‘what is the area?’ or ‘what is the perimeter?’) but some questions can be asked only of one or the other but not both (such as, ‘what is the length of a side?’ or ‘what is the radius?’) Square - side: int + perimeter(): double + area(): double Circle - radius: double + perimeter(): double + area(): double AI VIETNAM All-in-One Course 58
  • 419.
    Example  Inheritance recognition Square -side: int + __init__(int) Circle - radius: double + __init__(double) Shape + perimeter(): double + area(): double is Shape does not know how to compute its perimeter and area Use @abstractmethod to ask its child to implement them Using pass in the abstract method AI VIETNAM All-in-One Course Year 2022
  • 420.
    Example  Inheritance recognition AIVIETNAM All-in-One Course 60
  • 421.
    Example  Inheritance recognition AIVIETNAM All-in-One Course Year 2022
  • 422.
    Example  Inheritance recognition AIVIETNAM All-in-One Course Year 2022
  • 423.
    Example  Exercise Square - side:int + __init__(int) Circle - radius: double + __init__(double) Shape + perimeter(): double + area(): double is Rectangle - height: int - width: int + __init__(int, int) AI VIETNAM All-in-One Course
  • 425.
    Overriding Year 2022 AI VIETNAM All-in-OneCourse Overriding 66 Employee - name: string - salary: double + computeSalary(): double Manager - bonus: double + computeSalary(): double is Overriding is a feature that allows a child class to provide a specific implementation of a method that is already provided by its super-class.
  • 426.
    Overriding Example Doctor + perform(): void Student +perform(): void Person + perform(): void is AI VIETNAM All-in-One Course
  • 427.
    Vector - x: int -y: int + __init__(int, int) + add(Vector): void + dotProduct(Vector): int + check(Vector): bool A vector in 2D includes x and y. 1) Implement a constructor with no parameters. This constructors set 1 to x and y. 2) Implement a constructor with two parameters x and y. 3) Implement a destructor 4) Write a method to compute the addition between a vector and another vector 5) Write a method to compute the dot product between two vectors. 6) Check if two vectors are the same Exercise Ԧ 𝑥 = 2 3 Ԧ 𝑦 = 4 2 Ԧ 𝑦 Ԧ 𝑥 Ԧ 𝑣 = 3 3 + Ԧ 𝑦 = 7 5 Ԧ 𝑣 𝑢 = 4 4 + Ԧ 𝑥 = 6 7 𝑢 x. y = ෍ 1 𝑛 𝑥𝑖𝑦𝑖 Dot Product
  • 429.
    Advanced Python Year 2022 Quang-VinhDinh Ph.D. in Computer Science AI VIETNAM All-in-One Course
  • 430.
     Exception  Iterator Generator  Decorator  Text Libraries  Sound Libraries Outline
  • 431.
    Try/Catch  Used infunctions Year 2022 AI VIETNAM All-in-One Course 1
  • 432.
    Try/Catch  Exception Handling Year2022 AI VIETNAM All-in-One Course Code in try Code in catch Something wrong Code after try/catch 2
  • 433.
    Try/Catch  Exception Handling Year2022 AI VIETNAM All-in-One Course Code in try Code in catch Something wrong Code in finally Code after try/catch 3
  • 434.
    Try/Catch Year 2022 AI VIETNAM All-in-OneCourse Code in try Code in catch Something wrong Code in finally Code after try/catch 4  Exception Handling
  • 435.
    Try/Catch Year 2022 AI VIETNAM All-in-OneCourse Code in try Code in catch Something wrong Code in finally Code after try/catch 5  Exception Handling
  • 436.
    Exception in Python AIVIETNAM All-in-One Course 6 https://chercher.tech/python-programming/python-exception-handling
  • 437.
    Common Exceptions  KeyError FileNotFoundError  IndexError 7
  • 438.
    Common Exceptions  ZeroDivisionError Year2022 AI VIETNAM All-in-One Course 8  OverflowError
  • 439.
    Common Exceptions  ValueError Year2022 9  NameError  SyntaxError
  • 440.
    Common Exceptions  IndentationError Year2022 AI VIETNAM All-in-One Course  TypeErrors 10
  • 441.
    Common Exceptions  StopIteration Year2022 AI VIETNAM All-in-One Course 11
  • 442.
    PermissionError Year 2022 EOFError Common Exceptions AIVIETNAM All-in-One Course hit Ctrl+D while waiting for input from users 12
  • 444.
  • 445.
    Iterator 4 AI VIETNAM All-in-One Course Range and Iterator Year 2022 14
  • 446.
    Iterator 4 AI VIETNAM All-in-One Course Year2022 15  Range and Iterator
  • 447.
  • 448.
  • 449.
  • 450.
  • 451.
  • 452.
  • 453.
  • 454.
  • 455.
  • 456.
  • 457.
    Iterator 4 26 AI VIETNAM All-in-One Course Dictionary and Iterator Year 2022
  • 458.
    Iterator 4 27 AI VIETNAM All-in-One Course Dictionary and Iterator Year 2022
  • 459.
    Iterator 4 Year 2022 AI VIETNAM All-in-OneCourse 28 1 Create iterator using iter() 2 Get value using next()
  • 460.
    Iterator 4 Year 2022 AI VIETNAM All-in-OneCourse 29  Classes and Iterator
  • 461.
    Iterator 4 Year 2022 AI VIETNAM All-in-OneCourse 30 1 Implement iter() 2 Implement next() 3 Raise StopIteration
  • 462.
  • 463.
  • 464.
  • 465.
    “A wonderful littleproduction. <br /><br />The filming technique is very unassuming- very old- time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the entire piece…..” positive “This show was an amazing, fresh & innovative idea in the 70's when it first aired. The first 7 or 8 years were brilliant, but things dropped off after that. By 1990, the show was not really funny anymore, and it's continued its decline further to the complete waste of time it is today….” negative “I thought this was a wonderful way to spend time on a too hot summer weekend, sitting in the air conditioned theater and watching a light-hearted comedy. The plot is simplistic, but the dialogue is witty and the characters are likable (even the well bread suspected serial killer)….” positive “BTW Carver gets a very annoying sidekick who makes you wanna shoot him the first three minutes he's on screen.” negative Iterator Year 2022  For large datasets Features Label
  • 466.
    Iterator  For largedatasets dataset a chunk a chunk a chunk a chunk A whole dataset does not fit the memory, but a chunk does
  • 468.
    From Iterator toGenerator 4 Year 2022 AI VIETNAM All-in-One Course 34 Iterator Generator
  • 469.
  • 470.
  • 471.
    Generator 4 Year 2022 AI VIETNAM All-in-OneCourse 36  Create a generator
  • 472.
    Generator  For largedatasets dataset a chunk a chunk a chunk a chunk A whole dataset does not fit the memory, but a chunk does
  • 473.
     Exception  Iterator Generator  Decorator  Text Libraries  Sound Libraries Outline
  • 474.
    Inner Functions 4 Year 2022 AIVIETNAM All-in-One Course 37  Functions as variables
  • 475.
    Decorator Year 2022 AI VIETNAM All-in-OneCourse  Motivation 𝑦 = 𝑎𝑥2 + 𝑏𝑥 + 𝑐 ∆= 𝑏2 − 4𝑎𝑐 …
  • 477.
    Decorator Year 2022 AI VIETNAM All-in-OneCourse  Motivation 𝑦 = 𝑎𝑥2 + 𝑏𝑥 + 𝑐 ∆= 𝑏2 − 4𝑎𝑐 … How to add the constraint without modifying the existing code? 𝑎 ≠ 0 A constraint
  • 478.
  • 479.
    Decorator  Solution 2 A function as an argument
  • 480.
  • 481.
  • 482.
    Walrus Operator 4 Year 2022 AIVIETNAM All-in-One Course 45  Variable assignments inside of larger expressions data expected length is 5 Truncate padding if shorter if longer
  • 483.
    Walrus Operator 4 Year 2022 AIVIETNAM All-in-One Course 46  Variable assignments inside of larger expressions data expected length is 5 Truncate padding if shorter if longer
  • 484.
    Walrus Operator 4 Year 2022 AIVIETNAM All-in-One Course 47  Variable assignments inside of larger expressions Generate random numbers until getting 5
  • 485.
    Walrus Operator 4 Year 2022 AIVIETNAM All-in-One Course 48  Variable assignments inside of larger expressions Generate random numbers until getting 5
  • 486.
     Exception  Iterator Generator  Decorator  Text Libraries  Sound Libraries Outline
  • 487.
    Natural Language Processing Introduction Year 2022 AI VIETNAM All-in-One Course www.sneakernews.ml 49
  • 488.
    NLPApplications AI VIETNAM All-in-One Course Year2022 Practical Natural Language Processing by Sowmya Vajjala, Bodhisattwa Majumder, Anuj Gupta, Harshit Surana 50
  • 489.
    NLPApplications AI VIETNAM All-in-One Course PracticalNatural Language Processing by Sowmya Vajjala, Bodhisattwa Majumder, Anuj Gupta, Harshit Surana 51
  • 490.
    NLPApplications AI VIETNAM All-in-One Course Year2022 https://www.mygreatlearning.com/blog/trending-natural-language-processing-applications/ 52
  • 491.
    NLPApplications AI VIETNAM All-in-One Course Year2022  Text Classification https://codeit.us/blog/nlp-applications-in-business 53
  • 492.
    NLPApplications AI VIETNAM All-in-One Course Year2022 https://codeit.us/blog/nlp-applications-in-business https://monkeylearn.com/text-classification/  Text Classification Topic Labeling Sentiment Analysis 54
  • 493.
    NLPApplications AI VIETNAM All-in-One Course Year2022 https://monkeylearn.com/text-classification/  Text Classification Intent Detection Language Detection 55
  • 494.
  • 495.
    NLPApplications AI VIETNAM All-in-One Course Year2022  Information Extraction 57
  • 496.
    NLPApplications AI VIETNAM All-in-One Course Year2022 https://mobidev.biz/blog/natural-language-processing-nlp-use-cases-business  Information Extraction 58
  • 497.
    NLPApplications AI VIETNAM All-in-One Course Year2022 https://mobidev.biz/blog/natural-language-processing-nlp-use-cases-business  Information Extraction 59
  • 498.
    NLPApplications AI VIETNAM All-in-One Course Year2022 Practical Natural Language Processing by Sowmya Vajjala, Bodhisattwa Majumder, Anuj Gupta, Harshit Surana  Conversational Agents (Chatbots) 61
  • 499.
    NLPApplications  Conversational Agents(Chatbots) Recipe Recommendations Dialog Systems in Detail Practical Natural Language Processing by Sowmya Vajjala, Bodhisattwa Majumder, Anuj Gupta, Harshit Surana 63
  • 500.
    NLPApplications AI VIETNAM All-in-One Course Year2022  Topics in Brief 1. Spelling correction 2. Snippet extraction: All the search results show a text snippet involving the query. 3. Biographical information extraction 4. Search results classification: all, news, images, videos 1 2 3 4 Search and Information Retrieval
  • 501.
    NLPApplications AI VIETNAM All-in-One Course Year2022  Topics in Brief https://mobidev.biz/blog/natural-language-processing-nlp-use-cases-business 65
  • 502.
    NLPApplications AI VIETNAM All-in-One Course Year2022  Topics in Brief https://techcommunity.microsoft.com/t5/ai-customer-engineering-team/bootstrap-your-text-summarization-solution-with-the-latest/ba-p/1268809 66
  • 503.
    NLPApplications AI VIETNAM All-in-One Course Year2022  Topics in Brief https://www.studytonight.com/post/different-machine-translation-models-in-nlp https://www.analyticsvidhya.com/blog/2019/01/neural-machine-translation-keras/ Machine Translation 68
  • 505.
    Text Libraries ❖ UndertheseaLibrary Open-source Vietnamese Natural Language Process Toolkit 🔨 Installation: 📝 Description:  A Vietnamese NLP toolkit: API for apply some pretrained NLP models.  A Pytorch library: backed by Pytorch libraray.  A open-source software source: https://github.com/undertheseanlp/underthesea AI VIETNAM All-in-One Course 69
  • 506.
    Text Libraries ❖ UndertheseaLibrary: Usages source: https://github.com/undertheseanlp/underthesea 😳 Syntax: underthesea.pos_tag(sentence) Input: • sentence: raw sentence (unicode, str) Output: • tokens: list of tuple with word, pos tag 🌟 POS Tagging AI VIETNAM All-in-One Course 70
  • 507.
    Text Libraries 🌟 TextClassification source: https://github.com/undertheseanlp/underthesea 😳 Syntax: underthesea.classify(X) Input: • X: raw sentence (unicode, str) Output: • tokens: list categories of sentence Articles Text Classification technology finance social science Output Input AI VIETNAM All-in-One Course 71 ❖ Underthesea Library: Usages
  • 508.
    Text Libraries 🌟 SentimentAnalysis source: https://github.com/undertheseanlp/underthesea 😳 Syntax: underthesea.sentiment(X) Input: • X: raw sentence (unicode, str) Output: • labels: sentiment of sentence Sentiment Analysis Sentiment category Output Input Text AI VIETNAM All-in-One Course 72 ❖ Underthesea Library: Usages
  • 509.
    Text Libraries ❖ translateLibrary source: https://pypi.org/project/translate/ 🔨 Installation: A simple yet powerful command line translator with google translate behind it AI VIETNAM All-in-One Course 73
  • 510.
    Text Libraries source: https://pypi.org/project/translate/ 😳Syntax: translate.Translator.translate(X) Input: • X: raw sentence (unicode, str) Output: • y: translated sentence Machine Translation Output Input Text in English Text in Vietnamese 🌟 Machine Translation AI VIETNAM All-in-One Course 74 ❖ translate Library
  • 511.
    Text Libraries ❖ googletransLibrary source: https://pypi.org/project/googletrans/ 🔨 Installation: A free and unlimited python library that implemented Google Translate API AI VIETNAM All-in-One Course 75
  • 512.
    Text Libraries 😳 Syntax:googletrans.Translator.translate(text) Input: • text: raw text (unicode, str) Output: • <class 'googletrans.models.Translated'> Machine Translation Output Input Text in English Text in Vietnamese source: https://pypi.org/project/googletrans/ 🌟 Machine Translation AI VIETNAM All-in-One Course 76 ❖ googletrans Library
  • 513.
    Text Libraries ❖ newspaper3kLibrary 🔨 Installation: Amazing Python library for extracting & curating articles source: https://newspaper.readthedocs.io/en/latest/ AI VIETNAM All-in-One Course 78
  • 514.
    Text Libraries 😳 Syntax:newspaper.Article Input: • url: article’s url (str) Output: • <class 'newspaper.article.Article'> Crawl data system Output Input Article’s url Article (str) source: https://newspaper.readthedocs.io/en/latest/ 🌟 Text crawler AI VIETNAM All-in-One Course 79 ❖ newspaper3k Library
  • 515.
    Text Libraries ❖ gensimLibrary 🔨 Installation: A Python library for topic modelling, document indexing and similarity retrieval with large corpora source: https://radimrehurek.com/gensim/ AI VIETNAM All-in-One Course 80
  • 516.
    Text Libraries 😳 Syntax:gensim.summarization.summarize(text, ratio=0.2) Input: • text: article text (str) • ratio: the propotion of the number of sentences of the original text to be chosen for the summary Output: • Most representative sentences of the given text Text Summarization Output Input Article Summary text source: https://radimrehurek.com/gensim/ AI VIETNAM All-in-One Course 81 ❖ gensim Library
  • 517.
     Exception  Iterator Generator  Decorator  Text Libraries  Sound Libraries Outline
  • 518.
    https://research.aimultiple.com/voice-recognition-applications/ https://www.syndacast.com/google-voice-search-users-and-how-they-use-it/ Using voice assistantto search for stuff on the Internet has now become the ideal way of searching for 71% of participants in a PWC survey Voice search 82
  • 519.
    Voice to text 58%of respondents claimed to text their friends by using voice assistant, rather than to physically type. Source: PWC http://www.hoanvusolutions.com.vn/phan-mem-speech-recognition-cho-ios/ https://research.aimultiple.com/voice-recognition-applications/ https://viblo.asia/p/machine-learning-that-thu-vi-6-nhan-dien-giong-noi-1Je5E8DylnL 84
  • 520.
    Voice commands tosmart home devices https://ebusinessinstitute.com/voice/ Dummy-Based Anonymization for Voice-Controlled IoT Devices, Katrin Winkler and Erik Buchmann https://fptshop.store/tuya-wifi-ir-remote-control-for-smart-home-infrared-universal-remote-control-for-alexa-and-google-home-l1462654249.html 85
  • 521.
  • 522.
  • 523.
    Voice biometrics for security Pal, Gregory.(2016). Voice of the people: The case for biometrics in government. Biometric Technology Today. 2016. 5-7. 10.1016/S0969- 4765(16)30087-X. Voice recognition authentication system
  • 525.
    Speech Libraries ❖ librosaLibrary 🔨 Installation: A python package for music and audio analysis source: https://librosa.org/doc/latest/index.html AI VIETNAM All-in-One Course 89
  • 526.
    Text Libraries ❖ librosaLibrary: Usages 😳 Syntax: librosa.load(filename, sr=22050) Input: • filename: filepath of .wav soundfile Output: • data: sound datapoints (in time-domain) • sr: sampling rate of the sound Speech Reader Input source: https://librosa.org/doc/main/generated/librosa.load.html 🌟 Sound reader AI VIETNAM All-in-One Course 90
  • 527.
    Text Libraries 😳 Syntax:librosa.feature.melspectrogram(y, sr) Input: • y: audio datapoints • sr: sampling rate of audio Output: • S: vector of mel spectrogram Mel spectrogram converter Input Audio data points, sampling rate 🌟 Mel spectrogram converter source: https://librosa.org/doc/main/generated/librosa.feature.melspectrogram.html AI VIETNAM All-in-One Course 91 ❖ librosa Library: Usages
  • 528.
    Speech Libraries ❖ SpeechRecognitionLibrary 🔨 Installation: Library for performing speech recognition, with support for several engines and APIs, online and offline source: https://pypi.org/project/SpeechRecognition/ AI VIETNAM All-in-One Course 94
  • 529.
    Text Libraries 😳 Syntax:speech_recognition.Recognizer.recognize_google(audio, language) Input: • audio: audio data (AudioData class) • language: input audio language Output: • text: transcribed text (str) Automatic Speech Recognition Input 🌟 Automatic Speech Recognition Output Transcribed text source: https://pypi.org/project/SpeechRecognition/ AI VIETNAM All-in-One Course 95 ❖ SpeechRecognition Library
  • 530.
    Speech Libraries ❖ gTTSLibrary 🔨 Installation: A Python library and CLI tool to interface with Google Translate’s text-to-speech API. source: https://pypi.org/project/gTTS/ AI VIETNAM All-in-One Course 96
  • 531.
    Text Libraries 😳 Syntax:gTTS(content, lang) Input: • content: a string • lang: spoken language Output: <class 'gtts.tts.gTTS'> Text to Speech Input 🌟 Text to Speech Output source: https://pypi.org/project/gTTS/ Text AI VIETNAM All-in-One Course 97 ❖ gTTS Library
  • 533.
    Advanced Python Data Loadingand Saving Year 2022 Quang-Vinh Dinh Ph.D. in Computer Science AI VIETNAM All-in-One Course
  • 534.
     XML  JSON Tabular Data  Image Data  Some important libs Outline
  • 535.
    XML  eXtensible MarkupLanguage  Designed to store and transport data  Designed to be both human- and machine-readable. Year 2022 1 AI VIETNAM All-in-One Course
  • 536.
    XMLApplication VOC2007 Dataset 20 categories Year2022 Person: person Animal: bird, cat, cow, dog, horse, sheep Vehicle: aeroplane, bicycle, boat, bus, car, motorbike, train Indoor: bottle, chair, dining table, potted plant, sofa, tv/monitor
  • 537.
  • 538.
  • 539.
    XML  Example Year 2022 AIVIETNAM All-in-One Course To Address Body
  • 540.
    XML Year 2022 6 AIVIETNAM All-in-One Course  Example author title publisher
  • 541.
    XML  Syntax Year 2022 XMLPrologue Attribute AI VIETNAM All-in-One Course 7
  • 542.
    XML Year 2022 Element Opening tag Closingtag AI VIETNAM All-in-One Course 8  Syntax
  • 543.
    XML  Syntax  Allelements must be properly nested within each other  XML Tags are Case Sensitive Year 2022 https://codebeautify.org/xmlvalidator AI VIETNAM All-in-One Course 9
  • 544.
    XML  XML documentsform a tree structure Year 2022 https://www.w3schools.com/xml/xml_tree.asp AI VIETNAM All-in-One Course
  • 545.
    XML  XMLAttribute  XMLElement  Text  Attributes  Other elements  Mix of the above Year 2022 AI VIETNAM All-in-One Course 8 11 Element Attribute Text Mix
  • 546.
    XML  XML Elementsvs. Attributes Year 2022 AI VIETNAM All-in-One Course 9 12 Element Attribute Which one is better?
  • 547.
    XML Year 2022 13 https://www.w3schools.com/xml/xml_attributes.asp AIVIETNAM All-in-One Course  XML Elements vs. Attributes Element Attribute
  • 548.
    XML in Python xml.etree.ElementTree Year 2022 14 Root element <letter> Element <to> Text John Element <from> Text Mary Element <heading> Text Greeting Element <body> Text …
  • 549.
    XML in Python Year2022 15 Root element <letter> Element <to> Element <from> Element <heading> Element <body> Text John Text Mary Text Greeting Text … [0] [1] [2] [3] [0] [3] .text .text
  • 550.
    XML in Python Year2022 16 Root element <letter> Element <to> Element <from> Element <heading> Element <body> Text John Text Mary Text Greeting Text … find('to') find('body') .text .text
  • 551.
    XML in Python xml.etree.ElementTree Year 2022 17 Read from a file Get root element AI VIETNAM All-in-One Course
  • 552.
    XML in Python xml.etree.ElementTree Year 2022 18 AI VIETNAM All-in-One Course
  • 553.
    XML in Python xml.etree.ElementTree Year 2022 19
  • 554.
    XML in Python Year2022 20 Root element <letter> Element <date> Element <body> Text … find(‘date') Element <day> Element <month> Element <year> Text 19 Text 7 Text 2020 find(‘body')
  • 555.
    XML in Python Year2022 21 Root element <letter> Element <date> Element <body> Text … find(‘day') Element <day> Element <month> Element <year> Text 19 Text 7 Text 2020 find(‘body') Year 2022
  • 556.
    XML in Python Year2022 22 Root element <letter> Element <date> Element <body> Text … find(‘day') Element <day> Element <month> Element <year> Text 19 Text 7 Text 2020 find(‘body') find(‘date')
  • 557.
    XML in Python Year2022 23 Root element <company> Element <staff> Element < staff > … … Element <name> Element <salary> Attribute id=“1001” Text John Text 100
  • 558.
    XML in Python 24 Rootelement <company> Element <staff> Element < staff > … … Element <name> Element <salary> Attribute id=“1001” Text John Text 100 find(‘staff') get(‘id') find(‘name')
  • 559.
    XML in Python 25 Rootelement <company> Element <staff> Element < staff > … … Element <name> Element <salary> Attribute id=“1001” Text John Text 100 findall(‘staff')
  • 560.
    XML in Python 26 Rootelement <company> Element <staff> Element < staff > … … Element <name> Element <salary> Attribute id=“1001” Text John Text 100 find(‘name') findall(‘staff') get(‘id')
  • 561.
    XML in Python Example 27 Root element <company> Element < staff > Element <firstname> Text John Element <staff> Attribute id=“1001” Element <nickname> Text Stone Element <lastname> Text Smith Element <salary> Text 100000 Attribute currency=“USD”
  • 562.
    XML in Python Example 28 Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Element <nickname> Text John Text Smith Attribute id=“1001” Element <salary> Text 100000 Text Stone Attribute currency=“USD” Year 2022 AI VIETNAM All-in-One Course Using find()
  • 563.
    XML in Python Example Year 2022 29 AI VIETNAM All-in-One Course
  • 564.
    XML in Python Example Year 2022 30
  • 565.
    XML in Python Year2022 31 AI VIETNAM All-in-One Course  Example
  • 566.
    XML in Python Year2022 32  Example
  • 567.
    XML in Python Save an XML document Year 2022 33 AI VIETNAM All-in-One Course Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Text John Text Smith Element <firstname> Element <lastname> Text Peter Text White
  • 568.
    XML in Python Year2022 34 AI VIETNAM All-in-One Course Root element <company> Element <staff>  Save an XML document
  • 569.
    XML in Python Year2022 35 AI VIETNAM All-in-One Course Root element <company> Element <staff>  Save an XML document
  • 570.
    XML in Python Save an XML document Year 2022 36 Root element <company> Element <staff> Element <firstname>
  • 571.
    XML in Python Save an XML document Year 2022 37 Root element <company> Element <staff> Element <firstname> Text John
  • 572.
    XML in Python Save an XML document Year 2022 38 Root element <company> Element <staff> Element <firstname> Element <lastname> Text John Text Smith
  • 573.
    XML in Python Save an XML document Year 2022 39 Root element <company> Element <staff> Element <firstname> Element <lastname> Text John Text Smith
  • 574.
    XML in Python Save an XML document Year 2022 40 Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Text John Text Smith
  • 575.
    XML in Python Save an XML document Year 2022 41 Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Text John Text Smith
  • 576.
    XML in Python Save an XML document Year 2022 42 Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Text John Text Smith Element <firstname> Text Peter
  • 577.
    XML in Python Save an XML document Year 2022 43 Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Text John Text Smith Element <firstname> Element <lastname> Text Peter Text White
  • 578.
    XML in Python Year2022 44 AI VIETNAM All-in-One Course  Save an XML document
  • 579.
    XML in Python Year2022 45 Root element <company> Element <staff> Element < staff > Element <firstname> Element <lastname> Text John Text Smith Element <firstname> Element <lastname> Text Peter Text White Attribute id=“1001” Attribute currency=“USD”  Save an XML document
  • 580.
    XML in Python Year2022 46 Root element <company> AI VIETNAM All-in-One Course  Save an XML document
  • 581.
    XML in Python Year2022 47 Root element <company> Element <staff> AI VIETNAM All-in-One Course  Save an XML document
  • 582.
    XML in Python Year2022 48 Root element <company> Element <staff> Attribute id=“1001” AI VIETNAM All-in-One Course  Save an XML document
  • 583.
    XML in Python Year2022 49 Root element <company> Element <staff> Attribute id=“1001” AI VIETNAM All-in-One Course  Save an XML document
  • 584.
    XML in Python Year2022 50 Root element <company> Element <staff> Element <firstname> Text John Attribute id=“1001” AI VIETNAM All-in-One Course  Save an XML document
  • 585.
    XML in Python Year2022 51 Root element <company> Element <staff> Element <firstname> Element <lastname> Text John Text Smith Attribute id=“1001” AI VIETNAM All-in-One Course  Save an XML document
  • 586.
    XML in Python Year2022 52  Save an XML document
  • 587.
    XML in Python AIVIETNAM All-in-One Course  XML and Dictionary 52
  • 588.
     XML  JSON Tabular Data  Image Data  Some important libs Outline
  • 589.
    JSON  JSON (JavaScriptObject Notation)  Data exchange format  Lightweight  Text-based  Language-independent  Designed to be both human- and machine-readable. Year 2022 1 AI VIETNAM All-in-One Course 53
  • 590.
    JSON  Example Year 20222 AI VIETNAM All-in-One Course 54
  • 591.
    JSON Year 2022 3 AIVIETNAM All-in-One Course  Example 55
  • 592.
    JSON Year 2022 4 AIVIETNAM All-in-One Course  Example 56
  • 593.
    JSON Year 2022 6 AIVIETNAM All-in-One Course  Example 57
  • 594.
    JSON  Syntax Year 2022 Object Apair 7 AI VIETNAM All-in-One Course 58
  • 595.
  • 596.
    JSON Year 2022 Array ofobjects https://en.wikipedia.org/wiki/JSON 9 AI VIETNAM All-in-One Course  Syntax 60
  • 597.
    JSON  Syntax  Validator Year2022 61 https://jsonlint.com/ AI VIETNAM All-in-One Course
  • 598.
    JSON in Python Example  Read JSON Year 2022 62 AI VIETNAM All-in-One Course
  • 599.
    JSON in Python Example  Save JSON data Year 2022 63 AI VIETNAM All-in-One Course
  • 600.
     XML  JSON Tabular Data  Image Data  Some important libs Outline
  • 601.
    Important Packages Year 2022 AIVIETNAM All-in-One Course 1 2 3 Axis 0 Axis 0 Axis 1 1 2 3 4 5 6  Numpy is a Python library  For scientific computations  Numpy array Tensor in Tensorflow and Pytorch  Numpy arrays are multi-dimensional arrays 1D array 2D array 1 2 4 5 7 8 3 6 9 Axis 0 Axis 1 Axis 2 3D array 64
  • 602.
    Important Packages  CreateNumpy array  From List 5 Year 2022 AI VIETNAM All-in-One Course 2 1 2 0 1 2 3 data 1 data 0 data 1 arr_np = np.array(python_list) 65
  • 603.
    6 Important Packages  Commonattributes in Numpy  dtype: data type  shape: return a tuple of #elements in each dimension  ndim: return #dimensions Year 2022 AI VIETNAM All-in-One Course 1 2 3 Axis 0 shape=(3,) ndim=1 Axis 0 Axis 1 1 2 3 4 5 6 shape=(3,2) ndim=2 1 2 4 5 7 8 3 6 9 Axis 0 Axis 1 Axis 2 shape=(3,3,2) ndim=2 dtype example 66
  • 604.
    Important Packages  matplotlibpackage Year 2022 67 AI VIETNAM All-in-One Course
  • 605.
    Important Packages  Tabulardata Year 2022 68 AI VIETNAM All-in-One Course Features Label Advertising data
  • 606.
    Important Packages  Tabulardata Year 2022 AI VIETNAM All-in-One Course Boston House Price Data Features Label
  • 607.
    Important Packages Year 2022 Google Colab and Drive https://colab.research.google.com/drive/1YrU4un s_kH9BVRDovBe8nI53qRCWd4sT?usp=sharing
  • 608.
     XML  JSON Tabular Data  Image Data  Some important libs Outline
  • 609.
    Image Data  Grayscaleimages 4 Year 2022 AI VIETNAM All-in-One Course 71 (Height, Width) Pixel p = scalar 0 ≤ p ≤ 255 Resolution: #pixels Resolution = HeightxWidth
  • 610.
    Image Data  Colorimages 4 Year 2022 AI VIETNAM All-in-One Course 72 (Height, Width, channel) Pixel p= 𝑟 𝑔 𝑏 0 ≤ r,g,b ≤ 255 RGB color image Resolution: #pixels Resolution = HeightxWidth
  • 611.
    Important Packages  PILImage Year 2022 73 AI VIETNAM All-in-One Course
  • 612.
    Important Packages Year 202274 AI VIETNAM All-in-One Course  PIL Image
  • 613.
    Important Packages Year 202275 AI VIETNAM All-in-One Course  PIL Image
  • 614.
    Important Packages Year 202276 AI VIETNAM All-in-One Course  PIL Image
  • 615.
    Important Packages 77 AI VIETNAM All-in-OneCourse Year 2022  matplotlib package
  • 616.
    Image Data  Cat-Dogdataset 6 Year 2022 AI VIETNAM All-in-One Course cats_and_dogs train validation cat dog cat dog 78
  • 617.
    Important Packages Year 202279 AI VIETNAM All-in-One Course Cat-Dog Dataset  Cat-Dog dataset
  • 618.
    Important Packages Year 202280 AI VIETNAM All-in-One Course  Cat-Dog dataset
  • 619.
    Important Packages  tqdmpackage Year 2022 81 AI VIETNAM All-in-One Course
  • 620.
    Important Packages Year 202282 AI VIETNAM All-in-One Course In Machine Learning  matplotlib package
  • 621.
    Important Packages  Imagematching: Applications Year 2022 83 AI VIETNAM All-in-One Course https://pyimagesearch.com/2018/12/17/image-stitching-with-opencv-and-python/ https://paperswithcode.com/task/image-matching
  • 622.
    Important Packages  Imagematching AI VIETNAM All-in-One Course points_img1, points_img2  SIFT_matching(img1, img2)
  • 623.
     XML  JSON Tabular Data  Image Data  Some important libs Outline
  • 624.
    Important Packages Year 202285 AI VIETNAM All-in-One Course  os package
  • 625.
  • 626.
    Important Packages  gzippackage Year 2022 87 AI VIETNAM All-in-One Course
  • 627.
    Important Packages  picklepackage Year 2022 88 AI VIETNAM All-in-One Course
  • 628.
    Important Packages Year 2022 Gradient computation + 𝑥1 𝑥2 𝑥3 𝑥4 𝑦 ∙ 2
  • 629.
    Important Packages Year 2022 AIVIETNAM All-in-One Course 𝑥 ∙ 2 ∙ 2 𝑦 𝑧  Gradient computation
  • 630.
    Important Packages Year 2022 AIVIETNAM All-in-One Course 𝑥 𝑥 𝑥 ∗ 𝑦  Gradient computation
  • 631.
    Important Packages Year 2022 AIVIETNAM All-in-One Course 𝑔 𝑥 = −3𝑥 + 4 ℎ 𝑔 = 2𝑔 + 1  Gradient computation
  • 632.
    Important Packages Year 2022 AIVIETNAM All-in-One Course 𝑔 𝑥 = 𝑥2 + 1 ℎ 𝑔 = 𝑒𝑔  Gradient computation
  • 633.
    Important Packages Year 2022 𝑔𝑥 = 𝑐𝑜𝑠 𝑥2𝑒𝑥 + 2𝑥 ℎ 𝑔 = 𝑒𝑔𝑠𝑖𝑛 𝑔  Gradient computation 94