---
tags: COTAI LHP
---
CONGTHINHHH
# Lecture Notes ML4AI 2021
Course page: https://hackmd.io/@CoTAI/ml4ai1601
machinelearningcoban: https://machinelearningcoban.com/
## Final Test 24/4/2021
**Questions**
1. [**8** Points] The unified TEFPA framework to build a ML model: task $\mathcal{T}$, experience $\mathcal{E}$, function space $\mathcal{F}$, performance $\mathcal{P}$, and algorithm $\mathcal{A}$ to search. What are the elements in TEFPA framework...
- 1.1 [**2** Point, 3.1] to build a face recognition model using a DCNN?
- Task: recognize faces (input: pictures of face, output: who is the person in the picture)
- Experience: face samples
- Function Space:
- Performance: Tỉ lệ nhận diện đúng người
- Algorithm: DCNN
- 1.2 [**2** Point, 3.1] to build a RecSys? (using one of the models you have learned: item-based, user-based, content-based, MF)
- Task: tính toán sự giống nhau giữa các người dùng (input: vector những món đồ của người dùng đã mua, output: những người dùng có xu hướng mua đồ giống nhau)
- Experience: user's history shopping list sample
- Function Space: vector of features
- Performance: Độ hài lòng với giới thiệu của hệ thống
- Algorithm: KNN
- 1.3 [**2** Point, 3.1] to build a customer segmentation model using k-means?
- Task: chia nhóm khách hàng
- Experience: Dữ liệu khách hàng đã mua đồ gì
- Function Space:
- Performance:
- Algorithm: KNN
- 1.4 [**2** Point, 3.1] to build a sentiment analysis model (good, bad, neutral comments) using RNN+Softmax Classifier?
- Task: recognize faces (input: pictures of face, output: who is the person in the picture)
- Experience: labeled comments (good, bad, neutral)
- Function Space: features
- Performance: tỉ lệ dự đoán đúng comments
- Algorithm: RNN+Softmax Classifier
2. [**6** Points] Convolutional filters (or kernels)
- 2.1 [**1** Point, 1.1, 3.2] How do we extend them from dot product? Element-wise multiplication of the two matrices.
- 2.2 [**1** Point, 1.1, 3.2, 3.4] Why do we call their outputs "feature maps"? Mỗi điểm của output tượng trưng cho rất nhiều đặc trưng (features) của tấm hình ban đầu nên output được gọi là feature map
- 2.3 [**1** Point, 3.2] Explain padding: how to do & main purpose
Padding: thêm một vòng đệm ở bên ngoài input
Mục đích: tránh thất thoát thông tin ở cạnh, giữ nguyên hoặc tăng kích thước input
- 2.4 [**1** Point, 3.2] Explain pooling: how to do & main purpose
Mục đích: giảm kích thước đầu vào, giảm ảnh hưởng từ các sai lệch nhỏ
- 2.5 [**1** Point, 3.2] Explain stride: how to do & main purpose
Mục đích: đẩy nhanh tốc độ thu nhỏ dữ liệu
- 2.6 [**1** Point, 3.2, 3.4] Explain their **effective** receptive field: why do they produce highly absstract features?
Mỗi điểm của output tượng trưng cho các features của một khu vực trong input nên nó thường rất trừu tượng
3. [**6** Points] Recurrent neural networks (RNNs) can be used for sequential modeling.
- 3.1 [**1** Point, 3.2] What does sequential data mean?
Sequential data: dữ liệu mà ở đó thứ tự rất quan trọng (VD: thời gian)
- 3.2 [**1** Point, 1.1, 3.2, 3.4] Explain each element in this basic equation of RNNs $h_t = \mathsf{\gamma}(Ah_{t-1}+Wz_t)$
$h_t$: hidden layer
$\gamma$: hàm nắn không gian (relu, sigmoid,...)
$A, \space W$: bộ trọng số (không đổi)
$h_{t-1}$: output của layer trước
$z_t$: thông tin mới
- 3.3 [**2** Point, 1.3, 2.1, 3.2] WWhat does back-propagation-through-time mean, why do we need it instead of using plain back-prop, and how does it work for training RNNs?
Back-propagation-through-time: báo cáo lỗi lại với các time-steps trước trong quá trình huấn luyện
Ta cần nó để có thể cập nhật các bộ trọng số tốt hơn, cuối cùng bộ trọng số tốt nhất sẽ được đưa vào model RNN
- 3.4 [**1** Point, 1.3, 3.2] Explain vanishing gradient problem for simple RNNs.
- 3.5 [**1** Point, 3.1, 3.3] If we want to classify the sentiment of each user comment (good, bad, neutral) at the end of each sequence using RNN+Softmax classifier: explain briefly the model architecture.
4. [**6** Points] Planning in Markov Decision Process (MDP) $(S,A,T,R,\gamma)$.
- 4.1 [**1** Point, 3.1, 3.2] Explain 5 elements in MDP model (equation of each element if available).
S: trạng thái
A: hành động cần làm
T: transition, xác suát để đi từ state này sang một state khác
$\gamma$: discount factor: nhấn mạnh model lấy được reward lớn hơn thì tốt
- 4.2 [**1** Point, 3.2] Following a policy $\pi(s)$ to generate a trajectory of 10 time steps $(s_t,a_t,s_{t+1},r_{t+1})$. Compute the return. Equation of $a_t$?
$a_t = policy \space \pi (s_t)$
- 4.3 [**1** Point, 1.2, 3.2] Repeat for 10 days: from $s_0 = \text{HOME}$ take action $a_0 = \text{GET_BUS}$ with cost $r_1 = 6000 \text{VNĐ}$ then following policy $\pi(s)$ to generate $K=10$ trajectories, each with total cost $G_k$. Compute the average cost of taking bus then following $\pi$: $Q^\pi(\text{HOME, GET_BUS})$.
- 4.4 [**1** Point, 1.1, 1.3, 2.1, 3.2] How do we compute an optimal plan (i.e., optimal policy $\pi^*$) of a known MDP $(S,A,T,R,\gamma)$?
$\pi ^*= argmax \space q^\pi(s,a)$
- 4.5 [**1** Point, 3.2] Why do we say that the action value function $Q^\pi(s,a)$ gives predictions into very far future?
Vì $Q^\pi(s,a)$ phải đi từng hành động có thể trong tương lai để có thể tính được số reward và trả về.
- 4.6 [**1** Point, 1.2, 3.2] What is the meaning of action value function when we set $\gamma = 1$? $\gamma = 0$?
$\gamma = 1$: nhấn mạnh reward, khiến model cố gắng lấy được reward lớn nhất
$\gamma = 0$: đẩy độ cần thiết lấy được reward của model về 0
5. [**7** Points] Unified ML models
$\text{Input } X \xrightarrow[B_{\beta}]{\text{Features}}\text{ Embedding Coordinates }Z \xrightarrow[P_{\theta}]{\text{Predictor}}\text{ Predictions }\hat{Y} \xrightarrow[{\pi^*}]{\text{Policy}}\text{ Action }A$
- 5.1 [**2** Points] List all *taught* algorithms for feature extraction and their main ideas.
- Principle Components Analysis (PCA): create characteristic p
- Hand-crafted: tự tìm những features cần trích xuất
- Word embeddings: là một không gian vector dùng để biểu diễn dữ liệu có khả năng miêu tả được mối liên hệ, sự tương đồng về mặt ngữ nghĩa, văn cảnh(context) của dữ liệu.
- Sparse coding: Embedding coordinates with very few nonzeros (i.e., sparse) coefficients
- Convolutional kernels: Inner product + sliding in time/space of input domain = feature map
- 5.2 [**2** Points] List all *taught* algorithms for making predictions and their main ideas.
- Linear and non-linear predictor:
- Support Vector Machine (SVM):
- 5.3 [**2** Points] What are the main *general* differences between linear predictors? And in your opinion why do we need different algorithms?
- Linear and non-linear predictors: decission boundary của linear predictor là đường thẳng, còn DB của non-linear predictor là đường cong.
- 5.4 [**1** Points] For MDPs, what are the predictions $\hat{Y}$ used to make decisions $A$?
6. [**2** Points] RecSys

We build item embeddings ${\bf z}_i \in \mathbb{R}^2$ as in table, and use **softmax regression** to predict ratings 1 to 5. Choose a specific user $X\in \{A,\dots,F\}$, what is the training set for learning $\theta_X$? What are the parameters $\theta_X$ to be learned (with their shapes)?
7. [**6** Points] MDP Planning for playing Chess. Let rewards = 1 for winning, -1 for losing, and 0 for a draw or unfinished game, and no discount.
- 7.1 [**2** Points] What is the range of value of the optimal action-value function $Q^*(s,a)$, and how to derive probability of win/loss from it?
- 7.2 [**2** Points] If we use all the games already played in history to compute $Q^*(s,a)$, explain the method?
- 7.3 [**2** Points] Because there are so many state and action pairs $(s,a)$, we need to use *learning* to approximate and generalize for all $(s,a)$ pairs. If we use MLP to learn $Q^*(s,a)$, what is the dataset and possible network structure?
## Mid term Test 6/3/2021
1. [**5** Point] Given a set of inputs $(X^1,\dots,X^N)$, we use PCA to represent them as $X^t = X_0 + z_1U_1+\dots+z_nU_n$ with $X_0$ the mean input and $U_i$ the orthonormal principal components.
- [**2** Points] Write down equation for $X_0$, and equations for properties of $U_i,U_j$: unit length & mutual orthogonal.
**Solution**: $X_0=\frac{X^1+X^2+...+X^N}{N}$
- [**1** Point] We need to reduce the dimensions of $X^t$ to visualize them on 2D. What is the embedding vector ${\bf z}^t$ of $X^t$ if we use only 2 first principal components to represent it? What is the last feature of ${\bf z}^t$ in this case? **Solution**: $[X^1, X^2]$
- [**1** Point] What are the main differences between representations by PCA and by sparse coding? **Solution**:
- [**1** Point] If we cluster the dataset into 3 groups with centroids $({\bf m}_1, {\bf m}_2, {\bf m}_3),$ what is the label embedding coordinates of $X^t$ if it belongs to cluster 2? **Solution**:
2. [**1** Point] If we use each song as a feature to represent the users, what is the embedding coordinates ${\bf z}_A$ of user A in the dataset below? **Solution**: $z_A = 0.99x_1 \cdot0.02x_2$

3. [**3** Point] From the general form of linear predictors: $\hat{y}=\mathsf{s}(Wz+b)$ with $\mathsf{s}(\cdot)$ a transfer function for desired output interpretation.
- [**1** Point] What is $W$ for:
- 1 dimentional linear regression? **Solution**: $W$ là một con số
- sofmax regression with 3 classes? **Solution**: $W$ là một mảng chứa các hệ số tối ưu sao cho giá trị của đầu ra là chính xác nhất
- [**1** Point] What is function $\mathsf{s}(\cdot)$ for
- 1 dimentional linear regression? **Solution**: không có s
- SVM binary classification? **Solution**: argmax giữa 2 support vectors
- [**1** Point] Why logistic regression (for binary classification) has only 1 probability output while there are 2 classes? **Solution**:
Ta sử dụng hàm sigmoid để cho ra output.
Nếu output của hàm sigmoid >= 0,5 thì điểm đó thuộc class 0, còn < 0.5 thì điểm đó thuộc class 1.
4. [**2** Points] Evaluation procedure
- [**1** Point] Explain the main use of the train--dev (validation)--test sets. **Solution**:
Train set dùng để huấn luyện (fit) model.
Validation set dùng để đánh giá lại model sau mỗi lần huấn luyện.
Test set dùng để đánh gia model cuối cùng
- [**1** Point] What are the main similarity and differences between linear SVM and logistic regression? **Solution**:
- Giống nhau:
+ Đều là các mô hình linear giải quyết các bài toán classification và regression.
+ Đều tốn ít thời gian và tài nguyên để xử lí và tính toán.
- Khác nhau:
+ SVM tìm margin (khoảng cách giữa các đường với các support vetors) để giảm lỗi trong dữ liệu.
+ Logistic regression tìm decision boundary với các weights sao cho gần điểm tối ưu nhất.
5. [**2** Points] There are **1100 items** and **one million users**. We need to build a content-based RecSys by extracting **120 features** ${\bf z}_i$ describing each item $i$ then learn a classifier ${\bf \theta}_j$ for each user $j$ to predict **ratings from 1 to 5 stars** of each user for each item.

- [**1** Point] How many classes do we need? **Solution**: 1100
- [**1** Point] What is the size of $W$ if we use softmax regression $\hat{y}=s(Wz+b)$ for to classify ratings? **Solution**: ((1000000, 120) , 1100)
6. [**2** Points] Nonlinear predictors have general form $\hat{y}=s(W'\phi(z)+b')$. For Multilayer Perceptrons (MLP) in particular: $\phi(z) = \gamma(Wz+b)$ recursively, each called a "hidden layer".
- [**1** Point] Give explicit equation of an MLP with 2 hidden layers. **Solution**: $\phi(z) = \gamma(Wz'+b) =\gamma(W\cdot \beta(Wz''+b'')+b)$
- [**1** Point] What are the parameters of the fully-connected layer in your equation? **Solution**:
7. [**2** Points] Kernel machines use "kernel trick" $\phi(z_i)\cdot\phi(z_j) = \kappa(z_i,z_j)$.
- [**1** Point] Explain why kernel trick is useful. **Solution**:
Thay vì tính trực tiếp tọa độ của các điểm trong không gian mới ta chỉ cần tính tích vô hướng giữa hai điểm bất kì trong không gian mới.
Lợi ích:
. Giảm bộ nhớ và thời gian xử lí tính toán.
- [**1** Point] Explain how we can use kernel trick in feature-space prediction $\hat{y}=s(W^\phi\phi(z)+b)$ to turn a linear predictor into a nonlinear one. **Solution**:
Để có được mô hình phi tuyến, ta cần biến đổi bằng hàm phi tuyến biến đổi đặc trưng.
## Session 1 -- Linear Predictors
- [Slide](https://hackmd.io/@CoTAI/S154-Ofkd#/)
## Session 2 -- Feature Extraction (TRÍCH XUẤT ĐẶC TRƯNG)
Slide: https://hackmd.io/@CoTAI/B1hrnbjJO#/
Lab: https://colab.research.google.com/drive/1de76nxHVMz8iWEoUaF9dRqrUTJTDNKf3
Homework: https://colab.research.google.com/drive/1xlKH5-ikJQPsKtRRB99nwwbKu-ncDWBA?usp=sharing
**Ôn tập:**
- KNN, linear predictor
- Softmax, cross-entropy, y^ là kết quả hàm softmax và y là thực tế so sánh bằng hàm cross-entropy
- Các hàm linear predictor dùng để trích xuất đặc trưng
1. Hand crafted (engineered features):
- Các đặc trưng đặc trích xuất thủ công rồi so sánh bằng template matching
2. Sparse coding:
4. PCA (Principal Component Analysis):
- Mục đích: (Update: không giảm chiều mà chỉ phân tích thành nhiều thành phần, mình dùng nó để giảm chiều dữ liệu)
- Khi dữ liệu có quá nhiều chiều, ta cần giảm chiều dữ liệu để tăng tốc quá trình tính toán. Hàm PCA chỉ dữ lại một phần các phần tử quan trọng nhất của dữ liệu.
- Sau khi tách các thành phần trong một bức hình, ta có thể thấy tầm quan trọng của từng thành phần khác nhau rõ rệt, ta có thể bỏ qua những thành phần ít quan trọng nhất.
- Ứng dụng:
- Các PCA filter (line detection, sparse coding, ...) rồi trích xuất ra các đặc trưng nhỏ
- PCA (global)
- Cách hoạt động:
- Một hình sẽ được biểu diễn bằng 1 hình trung bình (B) và các thành phần chính (B1, B2, Bn,...)
- Giảm chiều dữ liệu: keep only first K components (mấy thành phần chính đầu tiên chứa nhiều thông tin quan trọng) -> dim image
5. Convolutional Operator (Tích chập):
- So khớp một ma trận lớn (input image) với ma trận nhỏ (kernel) bằng phương pháp trượt qua từng hàng để trích xuất các đặc trưng được feature maps.
6. Hàm flatten: Chuyển một vector có nhiều hàng, nhiều cột thành vector chỉ có một hàng hay một cột
7. Khái niệm embedding và standardlize
## Session 3 -- Nonlinear Predictors
Slide: https://hackmd.io/@CoTAI/By8dotTkO#/
Lab: https://drive.google.com/file/d/1wm0ZvW05FZkLwHTpkPuXneU9J2ziHwPz/view?usp=sharing
Homework:
1. Decision Boundary
- Vùng mà không quyết định được điểm đó thuộc class nào(niềm tin bằng nhau)
- Linearly separable (DB là đường phẳng, mặt phẳng)
- Nonlinearly separable (DB là đường cong, mặt phẳng cong)
- Non-separable (không có DB) => Phải có các thuật toán để biến đổi mặt phẳng để tính được các đường DB
Phương pháp: **trải**, **gỡ rối** các dữ liệu xoắn vào nhau (chuyển không gian Z thành Z') bằng các cách xoay, lật, dãn.
$x\overset{features}{\to}z\overset{transformation}{\to} z'\overset{P}{\to}\hat{y}$
2. Nonlinearly Predictors
## Session 4 -- Recommender Systems (RecSys)
- Applicantions:
- Amazon’s — “Customers who bought this item also bought…”
- Netflix’s — “Other Movies You May Enjoy…”
- Spotify’s — “Recommended songs…”
- Google’s — “Visually Similar Images…”
- YouTube’s — “Recommended Videos…”
- Facebook’s — “People You May Know…”
- LinkedIn’s — “Jobs You May Be Interested In…”
- Coursera’s — “Recommended courses…”
- Waze’s — “Best Route…”
- Intergrated in virtual assistant, robots, cobot (colaborative robots),...
1. Để robot có khả năng recommend thì cần có các khả năng:
- Generalization (khái quát hóa): quan sát các người dùng chung
- Personaliztion (cá nhân hóa)
-> Long-tail issues: less popular -> less items sold but better customer experience/satisfaction
2. RecSys: Đặt vấn đề
- Cần dự báo độ hứng thú của khách hàng với sản phẩm.
- Đầu vào là **USERS** và **ITEMS** (**Tùy theo bài toán cụ thể** mà đầu vào có thể khác nhau cho phù hợp)
- Đầu ra là **PREDICTIONS**.
3. RecSys: Cách giải quyết
* User-based filtering: dựa vào những người dùng khác mua những món đồ tương tự
* Item-based filtering: dựa vào những mặt hàng có nhiều người mua
* Chủ yếu dựa vào so sánh độ giống nhau giữa các features.
*************************

Collaborative filtering (CF) -- Memory-based: Dựa vào các thông tin chung, thống kê chung
- Item-based CF
- Key idead: users as features -> compute item-item similarity matrix
- Advantage: items don't change much as users
**Step 1**: transform user-item ratings into a matrix (xem người dùng là đặc trưng)
**Step 2**: calculate consine similarity for each pairs of matrix
**Step 3**: predict
- User-based CF
- Key idea: items as features -> compute user-user similarity matrix
## Session 9: Recurrent Neural Networks (RNNs)
- [Slide](https://hackmd.io/@CoTAI/B188QSnNO#/)
- [Lab](https://)
- [Homeword](aaaaaa)
Xử lí và đưa ra dự báo có tính chuỗi (như phim ảnh, âm thanh, giọng nói, time series như giá vàng, nhu cầu mua sắm, ...) (sequential data)
Ứng dụng: GANs
Lo mà tóm tắt đi đm
Crawl dataaaaaaaa