0% found this document useful (0 votes)
11 views

Week 2 - Friday - Data Structure - Updated

Uploaded by

tranquockhanh225
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Week 2 - Friday - Data Structure - Updated

Uploaded by

tranquockhanh225
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

AI VIETNAM

All-in-One Course

Data Structure
Tuple, Set & Dictionary

Nguyen Dinh Vinh


Ph.D in Computer Science
1
Year 2023
2
Outline
 Tuple
 Set
 Dictionary
 Summarize
 Further study

3
Outline
 Tuple
 Set
 Dictionary
 Summarize
 Further study

4
•Immutable: •Mutable:
• Nhóm này gồm có: Numbers, String, Tuple, và các kiểu • Nhóm này gồm có: List, Set, Dict và các kiểu
immutable
Credit by: khác do người dùng định nghĩa
https://realpython.com/python-mutable-vs-immutable-types/ mutable khác do người dùng định nghĩa
• Giá trị không thể thay đổi • Giá trị có thể thay đổi 5
Problem in using List

Are there any data struture to


prevent a user to modify data?

Tuples
6
Solve by Tuples

7
What is a Tuples?

8
9
10
11
AI VIETNAM
All-in-One Course
Tuple
 Structure

tuple_name = (element-1, …, element-n)

Create a tuple Tuple unpacking

12
AI VIETNAM
All-in-One Course
Tuple
 Structure

tuple_name = (element-1, …, element-n)

( ) can be removed Tuple with one element

13
Do you remember zip() function
Oh No, a new terminology? What is it?

14
Image credit: https://www.freecodecamp.org/
Look back to Iteration in Python

When writing computer programs, you often need to repeat a given piece of code
multiple times. To do this, you can follow one of the following approaches:

Repeating the target code as many times Putting the target code in a loop that runs as many
as you need in a sequence times as you need

Limitations? iterables

Oh No, a new terminology? What is it? Iteration 15


When it comes to iteration in Python, you’ll often hear people
talking about iterable objects or just iterables. As the name
suggests, an iterable is an object that you can iterate over. To
perform this iteration, we might use a for loop.
1.dùng được với for
2.iter(X) không báo lỗi
3.có phương thức __iter__ 1.Y = iter(X), với X là một iterable, thì Y là một iterator
2.next(Y) sẽ trả về giá trị phần tử tiếp theo hoặc ngoại lệ
StopIteration, thì Y là iterator.
Other solution to access elemements in the
List rather than using for loop?

18
Discuss more detail in next lecture
Built-in Functions
zip()
the iterators are also iterables which act as their own iterators

1 5

data1 = 1 2 3
2 6
data2 = 5 6 7

3 7

zip(*iterables). The function takes in iterables as arguments and


returns an iterator

zip() function to perform parallel iterations on multiple


iterables
20
21
AI VIETNAM
All-in-One Course
Tuple
 + and * operators

count() - đếm số lần xuất hiện của một giá trị


index() - tìm vị trí xuất hiện của một giá trị

https://colab.research.google.com/drive/1yZIgm8v5pkCk0u2kksV9qiP_-ELGrw3q?usp=sharing
22
Dùng hàm zip() cho tuple
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

Sắp xếp các giá trị trong một tuple

23
AI VIETNAM
All-in-One Course
Tuple
 Immutable however

0 1 2
add1
t 1 2 add2

0 1

3 10

24
AI VIETNAM
list2tuple
All-in-One Course
Tuple Examples
Swapping two variables Memory requirement

tuple2list

Tuple slicing 25
AI VIETNAM
All-in-One Course
Tuple Case 1: delta<0

 Example: Solve quadratic equation

Case 2: delta>0

Case 3: delta=0

Data is protected

26
Case study
Tuple in Object Detection and Localization

Output/Kết quả chương


Input/Đầu vào
trình
AI algorihtm/Giải thuật
trí tuệ nhân tạo

Ground Truth / Kết quả mong đợi


Image coordinate system
X
(0,0)

(x1,y1)

(x2,y2)
Y
28
Case study
Tuple in Object Detection and Localization

29
Giả sử ta có 2 boxes với thông tin như sau: 𝐴
𝑥𝐴 = max(𝑥𝑚𝑖𝑛 𝑏
, 𝑥𝑚𝑖𝑛 𝑏
) = 𝑥𝑚𝑖𝑛
𝐴 𝐴 𝐴 𝐴
•Box A có tọa độ (𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 , 𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) => Tuple 𝐴
𝑦𝐴 = max(𝑦𝑚𝑖𝑛 𝑏
, 𝑦𝑚𝑖𝑛 𝑏
) = 𝑦𝑚𝑖𝑛
𝐵 𝐵 𝐵 𝐵
•Box B có tọa độ (𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 , 𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) => Tuple

(xA,yA)
𝐴 𝐴
(𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 )

𝐵 𝐵
(𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 )
(xB,yB)
𝐴 𝑏 𝐴
𝑥𝐵 = min(𝑥𝑚𝑎𝑥 , 𝑥𝑚𝑎𝑥 ) = 𝑥𝑚𝑎𝑥
𝐴 𝑏 𝐴
𝑦𝐵 = min(𝑦𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) = 𝑦𝑚𝑎𝑥

𝐴 𝐴
(𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 )

𝐵 𝐵
(𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 )

𝑊 = 𝑥𝐵 - 𝑥𝐴
𝐴∩𝐵 =𝑊∗𝐻
H = yB – yA
A B

Area
30
Giả sử ta có 2 boxes với thông tin như sau:
𝐴 𝐴 𝐴 𝐴
•Box A có tọa độ (𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 , 𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) => Tuple 𝐴
𝑥𝐴 = max(𝑥𝑚𝑖𝑛 𝑏
, 𝑥𝑚𝑖𝑛 𝑏
) = 𝑥𝑚𝑖𝑛
𝐵 𝐵 𝐵 𝐵
•Box B có tọa độ (𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 , 𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) => Tuple 𝐴
𝑦𝐴 = max(𝑦𝑚𝑖𝑛 𝑏
, 𝑦𝑚𝑖𝑛 𝑏
) = 𝑦𝑚𝑖𝑛
(xA,yA)
𝐴 𝐴
(𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 )

𝐵 𝐵
(𝑥𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 )
(xB,yB)

𝐴 𝑏 𝐴
𝑥𝐵 = min(𝑥𝑚𝑎𝑥 , 𝑥𝑚𝑎𝑥 ) = 𝑥𝑚𝑎𝑥
𝐴 𝑏 𝐴
𝑦𝐵 = min(𝑦𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) = 𝑦𝑚𝑎𝑥

𝐴 𝐴
(𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 )

𝐵 𝐵
𝐵
(𝑥𝑚𝑎𝑥 𝐵
- 𝑥𝑚𝑖𝑛 𝐵
) ∗ (𝑦𝑚𝑎𝑥 𝐵
- 𝑦𝑚𝑖𝑛 ) (𝑥𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 )

Area Area Area


𝐴∪𝐵 = A B

A B
𝐴 𝐴 𝐴 𝐴
(𝑥𝑚𝑎𝑥 - 𝑥𝑚𝑖𝑛 ) ∗ (𝑦𝑚𝑎𝑥 - 𝑦𝑚𝑖𝑛 )

31
# Tính diện tích của 2 box A, B
𝐴 𝐴 𝐴 𝐴
area1 = (𝑥𝑚𝑎𝑥 - 𝑥𝑚𝑖𝑛 ) ∗ (𝑦𝑚𝑎𝑥 - 𝑦𝑚𝑖𝑛 )
𝐵 𝐵 𝐵 𝐵
area2 = (𝑥𝑚𝑎𝑥 - 𝑥𝑚𝑖𝑛 ) ∗ (𝑦𝑚𝑎𝑥 - 𝑦𝑚𝑖𝑛 )

# Tìm tọa đọ của vùng giao nhau (Intersection)


𝐴 𝑏 𝑏
𝑥𝐴 = max(𝑥𝑚𝑖𝑛 , 𝑥𝑚𝑖𝑛 ) = 𝑥𝑚𝑖𝑛
𝐴 𝑏 𝑏
𝑦𝐴 = max(𝑦𝑚𝑖𝑛 , 𝑦𝑚𝑖𝑛 ) = 𝑦𝑚𝑖𝑛

𝐴 𝑏 𝐴
𝑥𝐵 = min(𝑥𝑚𝑎𝑥 , 𝑥𝑚𝑎𝑥 ) = 𝑥𝑚𝑎𝑥
𝐴 𝑏 𝐴
𝑦𝐵 = min(𝑦𝑚𝑎𝑥 , 𝑦𝑚𝑎𝑥 ) = 𝑦𝑚𝑎𝑥

# Tính diện tích vùng giao nhau


𝑊 = 𝑥𝐵 - 𝑥𝐴

H = yB – yA

intersection_area = w*h

# Tính diện tích phần hợp nhau


union_area = area1 + area2 - intersection_area

# Dựa trên phần giao và phần hợp để tính IoU


IoU = intersection_area / union_area
32
33
AI VIETNAM
All-in-One Course Case study:
(List and Tuple for Non-maximum Suppression)

Non-Maximum Suppression

34
Input
List P of prediction BBoxes of the form (x1,y1,x2,y2,c),
where (x1,y1) and (x2,y2) are the location of the BBox
and c is the predicted confidence score of the model.

Ouput
Return a list keep of filtered prediction BBoxes.

35
AI VIETNAM
All-in-One Course Case study
(List and Tuple for Non-maximum Suppression)

Non Maximum Suppression

Algorithm

36
https://learnopencv.com/non-maximum-suppression-theory-and-implementation-in-pytorch/
AI VIETNAM
All-in-One Course Case study
(List and Tuple for Non-maximum Suppression)

Non Maximum Suppression

List Tuple

37
https://colab.research.google.com/drive/1hqSe6gRXhrp-S6G-kLC2arNuk4cQrHTA#scrollTo=-KCCLTpGxiqH
Outline
 Tuple
 Set
 Dictionary
 Summarize
 Further study

38
39
Problem in List

how to define a list that only includes


unique elements

40
Problem in List

how to define a list that only includes


unique elements

Are there any efficient data


struture?

41
Problem in List

how to define a list that only includes


unique elements

Use Set for storing data


42
Case study 1:
Set in Finding List of Uniques Words
Appearing in the Paragraph

43
AI VIETNAM
All-in-One Course
Set
 Create a set
Items with different data types

Using curly brackets

Set comprehension

44
https://colab.research.google.com/drive/1GDLtw5mI0ZC6y-lBqJZXw3khkfee_lrY?usp=sharing
AI VIETNAM
All-in-One Course
Set

Access the items of a set Copy a set

45
List of the set operations available in Python

46
AI VIETNAM
All-in-One Course
Set
Add an item Insert a set to another set

Join two sets Not allow duplicate values

47
AI VIETNAM
All-in-One Course
Set
difference function symmetric_difference

difference_update function symmetric_difference_update

48
AI VIETNAM
All-in-One Course
Set
 Bitwise operator

49
AI VIETNAM
All-in-One Course
Set
 Remove an item
remove(item)
Remove an item from the set. Set comprehension

discard(item)
Remove an item from the set if it is present.

https://docs.python.org/3/library
/stdtypes.html?t#set

50
AI VIETNAM
All-in-One Course
Set
 Remove an item

remove(item)
Remove an item from the set. discard(item)
Raises KeyError if elem is not contained in the set. Remove an item from the set if it is present.

https://docs.python.org/3/library/stdtypes.html?t#set 51
AI VIETNAM
All-in-One Course
Set
 Create a set Trời ơi, lại 1 thuật ngữ mới? unhashable là gì
đây ta

Unordered and unindexed Cannot contain unhashable types

52
53
A hashable Python object is any object that has a hash value — an integer identificator of
that object which never changes during its lifetime. Most of Python’s immutable built-in
objects are hashable; mutable containers (such as lists or dictionaries) are not;

181

530343892119126197

5256052183123979819

54
AI VIETNAM
All-in-One Course
Set

Set  List
and Tuple

???

55
???
56
Case study 1:
Finding a List of Uniques Words
Appearing in the Paragraph

57
AI VIETNAM
AI Course
Set
 Convert text to numbers

58
Outline
 Tuple
 Set
 Dictionary
 Summarize
 Case study

59
Problem in a List, Set
• We want to store following parameters for YOLO machine learning-
based algorithms: batch size, learning rate, momentum, decay. Which
data structure we can use?

Limitations by using
List

60
Problem in a List, Set
• We want to store following parameters for YOLO machine learning-
based algorithms: batch size, learning rate, momentum, decay. Which
data structure we can use?

Solve by Dictionary
61
Case study:
Find frequency of each word
in a paragraph

62
AI VIETNAM
All-in-One Course
Dictionary
 Structure bracket

dictionary_name = {key-1:value-1, …, key-n:value-n}

element comma colon

Create a dictionary

63
64
65
AI VIETNAM
All-in-One Course
Dictionary
 Create a Dictionary

66
AI VIETNAM
All-in-One Course
Dictionary

 Update a value  Copy a dictionary

67
AI VIETNAM
All-in-One Course
Dictionary

 Hàm copy() chỉ sao chép  Sử dụng hàm deepcopy()


kiểu shallow trong module copy

68
AI VIETNAM
All-in-One Course
Dictionary
 Get keys and values
Get keys
Get keys

Get keys and values


Get values

69
AI VIETNAM
All-in-One Course
Dictionary
 Get a value by a key

Get value using get() function Get value and delete the corresponding item

70
AI VIETNAM
All-in-One Course
Dictionary
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

71
AI VIETNAM
All-in-One Course
Dictionary
 Key that does not exist

Try to delete a non-existing item Try to get an item by a non-existing key

72
AI VIETNAM
All-in-One Course
Dictionary

setdefault() function example

Result ???

73
AI VIETNAM
All-in-One Course
Dictionary
 Get a value via a key

Method 1 Method 2

74
AI VIETNAM
All-in-One Course
Dictionary
Merge two dictionaries Check if a key exists

Remove empty items Dictionary comprehension

75
Case study:
Find frequency of each word
in a paragraph

76
77
AI VIETNAM
All-in-One Course Case study:
(Dictionary in Image Histogram)

Histogram Algorithm

78
AI VIETNAM
All-in-One Course Case study:
(Dictionary in Image Histogram)

Histogram Algorithm

255 0 255 255 255 0 255


255 0 0 255 255 0 255
255 0 0 0 0 0 255
0 0 255 255 255 0 0
0 0 255 255 255 0 0
255 0 255 255 255 0 255
255 255 0 0 0 255 255

79
AI VIETNAM
All-in-One Course Case study:
(Dictionary in Image Histogram)

Histogram Algorithm

80
AI VIETNAM
All-in-One Course Case study:
(Dictionary in Image Histogram)

Histogram Algorithm

81
Outline
 Tuple
 Set
 Dictionary
 Summarize
 Further study

82
83
AI VIETNAM
All-in-One Course
Summarize
PYTHON TUPLES VS LISTS

TUPLES LIST
The items are surrounded in Syntax The items are surrounded in
parathesis () square brackets []

Tuples are immutable in Mutability List are mutable in nature


nature
In dictionary, we can create Usability In dictionary, we can not
keys using tuples use lists as keys

84
AI VIETNAM
All-in-One Course
Summarize

Data Structure Ordered Mutable Constructor Example

List Yes Yes [] or list() [5. 7, ‘yes’, 5.7]

Tuple Yes No () or tuple() (5.7, ‘yes’, 5.7)

Set No Yes {} or set() {5.7, ‘yes’ }

Dictionary No Yes {} or dict{} {‘key’: value}

85
Outline
 Tuple
 Set
 Dictionary
 Summarize
 Further study

86
AI VIETNAM
AI Course Case study (at home):
(Set in Text Classification)
 Text classification - 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- positive
time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the
entire piece…..”
“This show was an amazing, fresh & innovative idea in the 70's when it first aired. The first 7 or 8 negative
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….”
“I thought this was a wonderful way to spend time on a too hot summer weekend, sitting in the air positive
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)….”
“BTW Carver gets a very annoying sidekick who makes you wanna shoot him the first three negative
minutes he's on screen.” 87
AI VIETNAM
AI Course Case study (at home):
(Set in Text Classification)
 Text classification

Preprocessing
Text Sigmoid
Sample (standardization & 𝑧 activation
Output
vectorization)

Preprocessing Embedding Fully-connected layer

88
Embedding
- Example corpus
sample1: ‘We are learning AI’
sample2: ‘AI is a CS topic’
(1) Build vocabulary from corpus

index 0 1 2 3 4 5 6 7 8
word pad are ai we topic learnin is cs a
g
(2) Transform text into features
We are learning AI AI is a CS topic

Standardize

we are learning ai ai is a cs topic

Vectorization

3 1 5 2 0 2 6 8 7 4
89
AI VIETNAM
All-in-One Course
Sorting item=7

sorted(iterable, key=None, reverse=False)

90
AI VIETNAM
item=(‘g’, 13)
All-in-One Course
Sorting

91
AI VIETNAM
item=(‘g’, 13)
All-in-One Course
Sorting

list1 = a g e h b

list2 = 16 13 18 11 15

a g e h b
list3 =
16 13 18 11 15

item
92
AI VIETNAM
All-in-One Course
Lambda function

 Take any number of arguments


 Can only have one expression

Syntax
lambda arguments : expression

93
AI VIETNAM
item=(‘g’, 13)
All-in-One Course
Sorting
Using lambda function

94
95

You might also like