# 機器學習 2022
> 這是一個關於機器學習的筆記[name=簡志融]
> * [YouTube @HungyiLeeNTU / 機器學習2022](https://www.youtube.com/watch?v=7XZR0-4uS5s&list=PLJV_el3uVTsPM2mM-OQzJXziCGJa8nJL8&pp=iAQB)
> * [Machine Learning 2022 Spring](https://speech.ee.ntu.edu.tw/~hylee/ml/2022-spring.php)
# 摘要
[TOC]
# Lecture 1 :Introduction of Deep Learning
> Q : 什麼是機器學習 ?
> A : 就是叫機器找一個**人類寫不出來**的複雜函式
## Preparation
* 機器學習類型與輸出
| Regression | Classification | Structured Learning |
| ---------- | ------------------ | -------|
| scalar | a class of classes | create sth with structure (img、text)|
### 基礎機器學習(訓練)的步驟
1. 寫出一個帶有未知參數的函數 (Model)

2. 從 training data 定義 Loss function (算出預測誤差,判斷預測有多好)


3. 最佳化 (Optimization,找出最好的b、w)
* Gradient Desent (learning rate 是 hyperparameters,需要自己設)
1. 選一個起始點
2. 計算移動點的微分(斜率)
3. 迭代更新 (直到不想做了 or 零向量無法更新)

(這個方法的真正問題不是 local minima,痛點是[???]())

> 透過 domain knowledge(對於預測本身了解) 修改模型,嘗試讓 Loss 變得更低
### 進階機器學習的步驟
> 預測中,X 與 Y 之間可能有更複雜的關係,Linear model 太過簡單,將關係視做一條直線
> 而這種限制稱為 **Model Bias**,無法模擬真實狀況
#### 寫出更複雜的函數
> 用 Piecewise linear curve 逼近任何連續函數
> 而 Piecewise linear curve 又可以用一堆藍色加起來
1. 用 sigmoid 寫出要加總的函數
* w : 改變中間斜率
* b : 左右位移
* c : 改變高度

2. 用一些**函數加總+常數**模擬 (對象越複雜需要越多函數加總)

3. 得到新的 Model

#### 複雜的 Loss

#### 多維最佳化
> 跟原本相比,只是更多的參數需要新
> 微分斜率相加 = gradient (梯度)

> 資料很多時,會分成數個 Batch,參數更新的次數取決於 Batch size 的大小

#### Activation Function
> ReLU (Rectified Linear Unit)

### Deep Learning
> 因為很多隱藏層 >>> 很深 >>> 深度學習
> 為何不斷讓神經網路變深,而不是把它排開變胖 ?

#### Overfitting
> 在訓練時變好,測試時變差
## Lecture
### 深度學習 : 用**類神經網路**做出這個函式
* 輸入
* 向量 (vector)
* 矩陣 (matrix) : 影像辨識
* 序列 (sequence) : 語音辨識、翻譯
* 輸出
* 數值
* 類別
* 其他 : 文字、圖片
### 如何找出函式 ?
* **Supervised Learning** : 蒐集一大堆訓練資料並要標記,但標記曠日廢時
* **Self-supervised Learning** : 收集無標記資料,先 Pre-train 學習基本能力,在下游任務就能得到好的結果
* *Pre-trained Model (Foundation Model) vs. Downstream Tasks* : Like OS & App,做好基礎架構,不用重頭開發
* **Generative Adversarial Network** : 使用大量不成對 X、Y,讓機器自動把關聯找出來
* **Reinforcement Learning (RL)** : 不知道如何標記資料,但可以判斷好壞(獎懲)就可以用
> Famous Pre-trained Model : [BERT](https://leemeng.tw/attack_on_bert_transfer_learning_in_nlp.html),340M parameters
### 其他需要關注的事
* **Anomaly Detection** : 賦予機器回答"**我不知道**"的能力
* **Explainable AI (可解釋性 AI)** : 讓機器說明為什麼知道答案
* **Model Attack** : 加入如:雜訊,導致模型判斷錯誤
* **Domain Adaptation** : 如果訓練與測試使用分佈不一樣的圖片,可能導致正確率暴跌
* **Network Compression** : 壓縮模型,使其可以跑在手機或穿戴式裝置上
* **Life-long Learning** : 讓機器不斷學習的夢想
* **Meta Learning** : 讓機器學習如何學習,從大量的任務中自己發明新演算法
* *Few-shot Learning* : 用很少標記的資料進行學習
# Lecture 2 : What to do if my network fails to train
## Preparation
### 機器學習任務攻略
#### Framework of ML
> Training Data : [[X1, Y1], [X2, Y2]...]
> Testing Data : [X1, X2,...]
#### 好壞分析
> 基礎架構就是前面機器學習的步驟
* **檢查 training data 的 loss**
* **大**
* **model bias**,須讓 model 變的複雜、增加輸入資料量
* **optimization**,先用簡單的model,再試複雜的model比較loss
* **小**,檢查 testing data 的 loss
* **大**
* **overfitting**
* 增加訓練資料,e.g. Data augmentation
* 降低 model 彈性,e.g. constrained model
* 減參數、共用參數
* 減特徵
* early stopping
* regularization
* dropout
* **mismatch**,分布不同造成,無法透過調整改善
* **小**,成功 :)
##### model bias vs. optimization issue
| 問題 | model bias | optimization |
| ---- | ----------------- | ------------ |
| 原因 | 沒有解,找不到 | 有解,撈不到 |
| 解決 | 讓 model 變的複雜 | Next Lecture |
> 透過不同模型比較,得知是哪個問題

> 用較淺的網路做比較,如上圖,56層的36層都不做事,也不會比20層差
> 代表它並未找出最優解
##### Why overfitting ?
> model 彈性太大導致
> 解法要降低彈性給限制,但限制太多又會導致 model bias

#### 如何合理的選擇 model
> 如果怕資料分割的不好,可以使用 N-ford 版
> 應該根據 validation 的 loss 調整 model

### 局部最小值與鞍點
> 為何優化會失敗 ?
> 對 loss 不滿意、loss 一直下不去 (grdient為0)
> 卡在 critical point
| local minima | saddle point |
| ------------ | ------------ |
| no way to go | can escape |
#### Taylor Series Approximation
* 在 crtical point 時,gradient 為零,前項可以消掉

* 計算 hessian (紅色框框)
* All Eigen value > 0 : local minima
* All Eigen value < 0 : local maxima
* Eigen value 時大於時小於 0 : saddle point

> 如果在 saddle point,H 可以作為更新參數的參考
> 只要跟著**負的 eigen value**,找出它的 eigen vector,跟著更新參數

> Saddle point vs. local minima
> 事實上,在維度很多時,不容易卡在 local minima,更容易是 saddle point
### 批次與動量
#### Batch
> 為什麼要 batch ?
| large batch | small batch |
| -------------------- | ------------------ |
| 每次更新步伐大~~但慢~~,優化可能有問題 | 每次更新步伐小~~但快~~,優化更簡單 |
| 使用同一個 loss fn,容易卡住 | noisy update 對 training 有幫助,也對 testing 有幫助 |

> local minima 也有分好壞,在平坦(flat)的較在峽谷(sharp)裡的好
#### Momentum
> 不只考慮梯度,也考慮之前的方向調整參數
> 或許可以衝出當前的困境

### 自動調整學習速率
> loss 不動但 norm of gradient 會跳,可能是在山谷之間震盪
> learning rate 應為每個參數可製化
> gradient 平坦 >>> learning 高
> gradient 陡峭 >>> learning 低
* Root Mean Square

* RMSProp : α 自己調整,代表當前梯度的重要性

#### Learning Rate Scheduling
> Decay : 隨時間變小,可以解決累積暴走的問題
> Warm Up : 先變大再變小;一開始先摸索,後面再提升 learning rate

> 都會考慮過去所有的 gradient
> momentum 考慮方向,σ 只考慮大小

### 損失函數
> 可以把分類看成一種回歸問題
> 
> 但這個方式表達不好
* softmax類似於一種normalize

> 當 loss 很大的時候,cross-entropy有斜率
> MSE 比較平坦,可能會卡住,traning 起步較困難
## Lecture
> 在訓練時,無法得知樣本總數,因此只能在現有的做採樣
### 如何讓理想跟現實接近 ?
> 找到一個具有代表性的 D<sub>train</sub>,讓**training data**跟**所有的資料**分布接近時候可以達到
> 採樣到夠好的資料,理想跟現實就會很接近,反之不然 (δ自己決定要多小)

### 失敗的可能性
> 把可以**訓練資料變多**或**減少可選的函式**(Model)都可以把失敗的機率降低

> 通常 |𝓗| 都非常大,算出來的上界會大於1
 
### Modle Complieity
> Q : 線性問題中 |𝓗| 可能是連續且無窮大,算出來只能證明上界<=無窮大 ?
> A-1 : 在電腦的計算都是離散的,精度有限,式子偶爾還是能用
> A-2 : VC-dimension
| 做法 | 增加訓練資料 | 減低模型的複雜度 |
| --- | --------------------- | ------------------ |
| 問題 | 無法自己決定,耗費更多成本 | loss很大,理想崩壞 |
| 選大模型 | 選小模型 |
| ---------------- | ---------------------------- |
| 理想與現實差距大 | 理想與現實差距小,但表現糟糕 |
# Lecture 3 : Image as input
## Preparation
### 卷積神經網路
> 卷積神經網路 (CNN, Convolutional Neural Networks)
> 卷積層包含很多 filter,要在圖片裡抓 pattern
> 電腦將圖片視為 3-D 的 tensor : 長、寬、channel
#### 對影像辨識的觀察
1. 不需要看整張圖片,出現某些重要的特徵就可以確定物件
* receptive field : 可以任意設計,位置、形狀

2. 讓不同部分可能出現一樣的特徵
* parameter sharing (filter) : 讓兩個 neurons 共享參數

> 上述兩者結合 >>> Convolutional layer (**For image**, large model bias)
3. 把大圖片做subsamlping,圖片縮小還是一樣看的出來
* pooling : 偵測小細節容易丟失
## Lecture
### 用了驗證集卻還是過擬合?
> validation 可以看作一種 training
> 抽到不好的 traning data 會有不能接受的差距
> 同理,抽到不好的 validation data 會有不能接受的差距
> 原因:
> 1. validation set 大小
> 2. 模型複雜度大(通常希望要很小)
> |𝓗| 找出一個模型,𝓗 不多且都很好(loss 低),方可兼顧
> 
### 魚與熊掌可以兼得的深度學習
> Q : 為什麼要 hidden layer ?
> A : 可以透過一個 hidden layer 就可以找到所有可能的 function
> 矮胖 network v.s. 高瘦 network : 在同樣的參數量下,變高的效果比變胖好
> Q : 為何 Deep learning ?
> A : 用較少的參數,得到一樣效果 >>> 更難 overfitting
> Deep network 在複雜且有規律的 function 上表現佳,e.g. image、speech
# Lecture 4 : Sequence as input
## Preparation
### 自注意力機制 Self-attention
* Self-attention (***運算量非常大***)
* input : vector set,e.g. sentence、sound、graph
* output : sequence labeling、whole set a label
* 考慮整個 input sequence 產生出來的

* 用 α 代表兩者的關聯性

* α 的計算
* Dot-product

* Additive

* 也需要與自己計算關聯性

* 從結果提取重要資訊,**v 的 sum** 即是輸出結果

* ***Multi-head Self-attention***

* Positional Encoding : 如果位置的資訊重要可以加入
* Truncated Self-attention : 只看一部分的資料,加快運算

> CNN 可視為簡化版的 Self-attention
> * CNN 彈性小,在資料少的時候好,資料多到無法取得好處
> * Self-attention 彈性大,資料要多,資料少容易 overfitting
* RNN v.s. Self-attention
| RNN | Self-attention |
| ---------- | ----------- |
| 非平行處理 | 平行處理 |
| 無法考慮很遠的輸入 | 可以輕易抽取資訊 |

# Lecture 5 : Sequence to sequence
## Preparation
### 批次標準化 Batch Normalization
> 在 linear model 中,輸入資料各 dimension 的 scale 差距大時,就可能產生崎嶇的 error surface
> Batch Normalization 可以把崎嶇的 error surface 弄平
* Feature Normalization

[看不懂](https://www.youtube.com/watch?v=BABPWOkSbLE)
### Transformer
> A seq2seq model, output determined by model.
> 很多 NLP 的任務都可以想像成 QA 問題,QA 可用 seq2seq model 解
> 但這些任務客製化模型,往往會得到更好的結果
> e.g. Multi-label classification、object detection

#### seq2seq model
* encoder : 處理 input,丟給 decoder

* decoder : 決定輸出;Masked Self-attention 只能參考左邊的資料

* Error prapgation

* cross attention

* AT v.s. NAT

#### Training : 要讓 cross entropy 最小;答案當 Decoder 輸入

* Guided Attention : 讓 model 好好讀 input

* Beam Search : **時而有用(答案絕對時),時而沒用(需要創造力的任務)**

> TTS 生成時,加入雜訊,結果會更像真人
* 為解決 exposure bias,scheduled sampling 在訓練時加入一些錯誤的東西

## Lecture
> 最大的問題是要處理 N x N 的 attention matrix
> Input sequence 非常長時,以下才可能發揮效用
1. local attention / truncated attention : 只看鄰居,其他設 0

2. stride attention : 跳著看

3. gobal attention : 先在整個 input 加入 token,根據 token 蒐集資料

4. Clustering : 先進行分類,相近的才計算,遠的則設為0

5. sinkhorn sorting network : 輸入數個vector共用,相當於降解析度

6. Linformer : 把重複的刪除,留下有代表性的

**挑有代表性的Key,保證輸出長度(用 linear combination 挑)**

> [Synthesizer](https://arxiv.org/abs/2005.00743) 不需要 q 跟 k 也可以產生 attention matrix
> Attention Free : [FNet](https://arxiv.org/abs/2105.03824)、[Pay attention to MLPs](https://arxiv.org/abs/2105.08050)、[MLP-Mixer](https://arxiv.org/abs/2105.01601)
* Summary

# Lecture 6 : Generation
## Preparation
### 基本概念介紹
* **GAN 以難 train 聞名**
> [The GAN Zoo](https://github.com/hindupuravinash/the-gan-zoo)
> 生成式對抗網路 (Generative Adversarial Network, GAN)有什麼特別的 ?
> 輸入除了 X,還會有一個隨機生成的 Z,Z 要夠簡單且能夠 sample,輸出一個**分布**
> **找出一個 function,同樣的輸入不同的輸出,且這些輸出都是對的**

> * GAN
> * generator : 生成圖片
> * discriminator : 輸入圖片,判斷好壞
1. 定住 generator,更新 discriminator,教 discriminator 分辨

2. 定住 discriminator,更新 generator,想辦法騙過 discriminator

3. 反覆執行上述步驟

> * [The first GAN](https://arxiv.org/abs/1406.2661) : 原始 GAN
> * [Progressive GAN](https://arxiv.org/abs/1710.10196) : 生成高畫質的人臉
### 理論介紹與WGAN
#### GAN 的目標
> 找出一個 generator 讓 P~G~ 跟 P~data~ 的 Divergence 最小
> (Divergence 相當於 Loss function)

> * objective function 的最大值與 divergece 有關

#### 特性
* 多數情況下,P~G~ 跟 P~data~ 重疊的部分非常少
1. 圖片是高維空間中低維的manifold
2. 對 P~G~ 跟 P~data~ 理解來自 sample
* JS divergece 只要沒有重疊,算出來都是 log2

* 所以改用 wasserstein distance
#### WGAN
* Wasserstein distance
* P 變成 Q 的平均距離
* 因為有無限多的方法,所以窮舉所有方法,取最短的

* 當分布相近時,因為平滑的限制,數值不會差太多,wasserstein distance 就小

#### GAN Types
* Original WGAN : 限制 w 於 c 和 -c 之間
* [Improved WGAN](https://arxiv.org/abs/1704.00028) : Gradient Penalty

* [SNGAN](https://arxiv.org/abs/1802.05957) : Keep gradient norm smaller than 1 everywhere
### 生成器效能評估與條件式生成
> generator 跟 discriminator 只要有一方停止進步就沒辦法繼續訓練了
#### GAN training Tips
* [soumith / ganhacks](https://github.com/soumith/ganhacks)
* [Unsupervised Representation Learning with DCGAN](https://arxiv.org/abs/1511.06434)
* [Improved Techniques for Training GANs](https://arxiv.org/abs/1606.03498)
* [Large Scale GAN Training for High Fidelity Natural Image Synthesis](https://arxiv.org/abs/1809.11096)
#### GAN for Sequence Generation
* Distribution 的微小改變在 token 無法展現,會看不出變化

> 要訓練,先pre-train;或是爆調參數
> * [Training language GANs from Scratch](https://arxiv.org/abs/1905.09922)
> 用監督式學習的方式,用圖片對應向量去訓練
> * [Optimizing the Latent Space of Generative Networks](https://arxiv.org/abs/1707.05776)
> * [Gradient Origin Networks](https://arxiv.org/abs/2007.02798)
#### 評估
* 直接找人來看(早期)
* 影像辨識分類系統
* Mode Collapse : discriminator 的盲點,可以一直騙過 discriminator

* Mode Dropping : 生成資料的分布與原始的不同

* 指標
* IS : 透過分類器,計算平均分數

* FID : 圖片丟進 inception network,在最後輸出前拿出向量當圖片輸出

#### Conditional Generation
> 操控 x(condition) 的輸入,生成對應條件的輸出
* general : generator 會用清晰的圖片騙過 discriminator,但跟輸入 x 無關
因此要訓練輸入包含 x 跟圖片的 discriminator

* Image translation (pix2pix) : 真實但想像力偏大

* sound2image

### Cycle GAN
> 使用不成對的資料訓練

> 有可能學到奇怪的轉換,但通常不太會發生,並表現的不錯

#### GANs
* Image
* [Disco GAN](https://arxiv.org/abs/1703.05192)
* [Dual GAN](https://arxiv.org/abs/1704.02510)
* [Cycle GAN](https://arxiv.org/abs/1703.10593)
* [StarGAN](https://arxiv.org/abs/1711.09020)
* [SELFIE2ANIME](https://arxiv.org/abs/1907.10830)
* Text
* [Unsupevised Summaries](https://arxiv.org/abs/1810.02851)
* [Word Translation](https://arxiv.org/abs/1710.04087)
* [Unsupervised Neural Machine Translation](https://arxiv.org/abs/1710.11041)
* [Unsupervised Phoneme Recognition](https://arxiv.org/abs/1804.00316)
* [Unsupervised Speech Recognition](https://arxiv.org/abs/1812.09323)
* [Completely Unsupervised Speech Recognition](https://arxiv.org/abs/1904.04100)
# Recent Advance of Self-supervised learning for NLP
## Preparation
### 自督導式學習 (Self-supervised Learning)

### BERT
> 自己跟自己學,產生label

> [BERT](https://arxiv.org/abs/1810.04805) 就是 transfomer 的 encoder
1. Masking input : 蓋住填空

2. Next sentence predicition : 任務可能太簡單了,其實這招幫助不大
* [RoBERTa](https://arxiv.org/abs/1907.11692)
* [SOP](https://arxiv.org/abs/1909.11942)

* 只要一點標記資料,就可以微調(Fine-tune)分化成下游任務

#### How to use BERT
1. sentiment analysis

2. POS tagging

3. Nature Language Inference

4. Extraction-based QA : 找出答案的位置

> [Pretrained Language Model Embryology: The Birth of ALBERT](https://arxiv.org/abs/2010.02480)
> 把模型挖空的方法
> 
### BERT的奇聞軼事
> Q : 為何 BERT 有用
> A : 意思相近的 token 有 similar embedding;訓練時挖空,透過上下文填空

* 模型沒有把語言的資訊抹除,某種程度上不同語言同樣的詞彙有對應的關係

### GPT的野望
> GPT 用龐大的資料訓練預測下一個 token 的模型

## Lecture
### Background
* Pre-trained Language Models
* Neural Language Models
* Autoregressive Language Models (ALMs) : GPT series

* Transfomer-based ALMs

* Masked Language Models (MLMs) : BERT series

* Fine-tuning : Using the pre-trained weights of the PLM to initialize a model for a downstream task
### Problems
1. 下游任務資料缺乏
2. 模型太大且不斷增大中
* 針對不同任務微調後,所需空間成倍增長
* 模型推理時間過長
### Solutions
1. Data-Efficient Fine-tuning
* Prompt Tuning
1. prompt template

2. PLM
3. verbalizer

* Few-shot learning
* LM-BFF : prompt + demonstration

* Semi-supervised learning : 少量標註資料+大量未標註資料
* Pattern-Exploiting Training (PET)
1. Use different prompts and verbalizer

2. Predict the unlabeled dataset and combine the predictions from different models

3. Use a PLM with classifier head to train on the soft-labeled data set

* Zero-shot : GPT-3 model is larger enough
2. Parameter-Efficient Fine-tuning
* Adapter : small trainable submodules inserted in transformers
(會稍微增加層數,增加推理的時間)

* LoRA : Low-Rank Adaption (平行於層之間)

* Prefix Tuning

* Soft Prompting : Prepend the prefix embedding at the input layer

* Early Exit : dynamically reduce the number of layers used during inference

### Benefits

1. 顯著減少特定任務參數
2. 更不容易過擬合,在其他資料上表現更好
3. 對於資料少的資料集更好微調
### Other problems
* Why does self-supervised pre-training work
* Interpretability of the model's prediction
* Domain adaptation
* Continual learning/lifelong learning
* Security and privacy
# Lecture 7 : Self-supervised learning for Speech and Image
## Lecture
* Image
* image recognition
* object detection
* semantic segmentation
* visual navigation
### Training strategy
1. Generative Approaches : 文字上已經非常成功的方法
* Masking : 語音跟影像包含很多細節,較難生成完整

2. Predictive Approaches
* Predicting Rotation

* Context Prediction : 輸出相對位置

* Predict Simplified Objects

3. Contrastive Learning : 在不產生東西的情況下進步
* SimCLR

* MoCo : memory bank & momentum encoder

* CPC / Wav2vec

* VQ-wav2vec+BERT

* Wav2vec 2.0

4. Bootstrapping Approaches : 不需要 negtive example 的學習
* BYOL

* SimSiam
* Data2vec
5. Simply Extra Regularization : 不需要 negtive example 的學習

# Lecture 8 : Auto-encoder / Anomaly Detection
## Preparation
### Auto-encoder
> 類似於 [Cycle GAN](https://hackmd.io/@Jung217/LhyML2022#Cycle-GAN),主要目的是把高維轉低維
> 圖片表面上複雜,但事實上變化有限

* De-noising Auto-encoder : 嘗試去除雜訊


#### Feature Disentanglement
> 模型輸出的多維向量將很多特徵糾纏在一起,試圖將其分開

* voice conversion

#### Discrete Latent Representation

* 根本就是 Cycle Gan

#### More application
* Generator : Decoder 就是,把向量還原成圖片

* Compression : 會失真

* Anormaly Detection

### Anormaly Detection
> 有一組訓練資料 [x^1^, x^2^ ... x^n^]
> 要找出一個 function 可以判斷輸入是否**相似於**訓練資料
> 
> 因為異常的資料不好蒐集且種類繁多
> 所以異常偵測並非簡單的二元分類問題
* Training data
* *with labels* : classifier can output unknown >>> **Open-set recognition**
* *without labels*
* **Clean** : all data is normal
* **Po0llute** : some data is anormal
#### Case 1
* 透過簡單的方式決定信心分數,但有些特徵比原類別更強還是可能錯

* 可以透過生成異常的資料來訓練 classifier

#### Case 2
* 透過 anormal detector 建立模型輸出機率 P(X),threshold 決定是否異常


# Lecture 9 : Explainable AI
## Preparation
> 能得到正確的答案不代表機器真的很聰明
| Linear Model | Deep Network |Decision tree |
| -------- | -------- | -------- |
| 可解釋性較強 (weights) | 如同黑箱 | Interpretable 但非常複雜 |
| 弱、限制多 | Powerful | Powerful |
### Goal of Explainable ML
> 人其實就是需要一個令人高興的理由
* Processing input data
* Visulization : 人看

* Probing : 通常是 classifier,有可能 train 壞無法分辨

* Local Explanation : 這張圖片為何是...
* critical component

* Noisy Gradient : SmoothGrade

* Gradient Saturation : Integrated Gradient

* Global Explanation : 什麼樣的圖片叫做...
* Gradient ascent : 要看到好的成果要加上諸多限制和爆調參數 (人類的偏好)

* Other
* 用簡單的模型模仿困難模型一部分的行為

## Lecture
### Attack in NLP
> 在自然語言中,詞彙是離散的,輸入會先轉成連續高維向量
> 要攻擊只能在輸入的句子動手
### Evasion attack
> 加上不易察覺的雜訊
1. Goal
* untargeted classification : 分錯類
* targeted classification : 指定分錯的類別
* universal suffix dropper : 攻擊讓輸出丟失

* wrong parse tree in dependency parsing

2. Transformations
* world level
* substitution
* WordNet synonyms : 一詞有多義,換掉意思可能變微妙
* Counter-fitted GloVe embeding space

* BERT reconstruction
* inflectional form : 改時態,不改意思
* gradient of embeding space

* insertion based on BERT MLM
* word deletion : 易影響原意
* character
* swap : 交換字母順序,team >>> taem
* substitution : 抽換字母,team >>> txam
* deletion : team >>> tem
* insertion : team >>> tream
3. Constraints : 與攻擊目標高度相關
* Overlapping
* Levenshtein edit distance

* Maximum percentage of modified words

* Grammaticality
* Part of speech (POS,詞性) consistency

* Fluency scored by the perplexity of a pre-trained language model

* Semantic preserving
* Distance of the swapped and the original word's embedding

* Similarity between the transformed and the original sample's sentence

4. Search Method
* Greedy Search : 找出變化大的詞,依序替換

* word importance ranking (WIR) : 找最重要的字先換

* WIR + leave-one-out (LOO) : 每次拿掉一個,看成效

* WIR + gradient of word embedding : 要有模型才能算,不常用

* Genetic Algorithm : 依適合的程度挑選和進化

# Lecture 10 : Attack
## Preparation
#### How to attack
> 加入**雜訊**可以誤導模型輸出錯誤結果

* 遠離原本的答案
* 接近攻擊目標答案
* 最小化雜訊 (以人類的感知做決定)
> 差距的計算方式以人類的感知為主,需要 domain knowledge
* 圖片差距計算
* L2-norm : 計算每維的差距
* L-infinity : 找出差距最大的維度
* 更新輸入的圖片,不更新參數,超出範圍拉回
e.g. [Fast Gradient Sign Method (FGSM)](https://arxiv.org/abs/1412.6572)

#### Attack types
* White Box Attack : 需知道網路的參數,計算 gradient
* Black Box Attack : 用相同或類似的資料訓練模型攻擊,可能起到作用

* Ensemble Attack : 同一張圖片可以騙過多個模型
> 為何攻擊容易成功 ?
> 可能因為對於不同模型同樣東西區域類似,所以攻擊的方向近似
* Image
* [one pixel attack](https://arxiv.org/abs/1710.08864)
* [universal adversarial attack](https://arxiv.org/abs/1610.08401)
* Speech
* detect synthesized speech
* Text
* natural language processing
* Real world

* 在訓練階段就攻擊 (小心公開資料集)
[](https://arxiv.org/abs/1806.11146)[](https://arxiv.org/abs/1804.00792)
#### Defence
* Passive : 既強也不強,被知道可以躲掉
* smoothing : 可以將一些攻擊的雜訊抹除
* compression : 壓縮失真的同時,雜訊也失真
* generator : 生成再偵測,generator 沒看過的雜訊也生不出來
* randomization : 加上隨機性,增加防禦性
* Proactive
* data augmentation
* Adversarial training : 找出模型的漏洞,加強防禦,用被攻擊過的資料也訓練
* 缺點 : 擋不住新的攻擊、需要較多的運算資源
## Lecture
### Examples of Evasion attack
> 攻擊成功有可能源自於不合理的檢驗標準,只是成功騙過了檢驗的限制
> 攻擊不一定是真正最危險的問題,真實情境下有更多方法破壞系統
* Synonym Substitution Attack
* TextFooler

* TF-Adjusted : 更多限制的 TextFooler
* Probability Weighted Word Saliency (PWWS) : 沒有限制,品質可能比較有問題

* BERT-Attack

* Genetic Algorithm

* Morpheous : 改變時態和詞性的攻擊

* Universal Trigger : 找出一段特定文字能讓模型改變輸出

# Lecture 11 : Adaptation
## Preparation
### 領域自適應 (Domain Adaptation)
> Domain shift : 訓練與測試資料的分布不同
> Domain Adaptation : 讓訓練的模型可以用在不同的測試資料,並不好做
* 讓來自不同分布資料的特徵分布接近一樣

* 如果要做得好,要讓特徵分布遠離分界 (輸出的類別單一集中)
* [DIRT-T](https://arxiv.org/abs/1802.08735)
* [Maximum Classifier Discrepancy](https://arxiv.org/abs/1712.02560)

* Domain generalization : 想辦法生成多類資料嘗試解決

## Lecture
### Cross-lingual
> 透過 embedding 可以找出潛在的語言資訊

> 雖然有關係,但對應依舊有差異
### Cross-discipline
> pre-train model 在不同的資料也能表現的很好
> pre-train model 可以增強 optimization 的能力

### Pre-training with artificial data
* 資料扮演重要的角色,人工產生的資料也能有好的效果

# Lecture 12 : Reinforcement Learning
## Preparation
### 增強式學習 (Reinforcement Learning, RL)
> 在人也不知道最佳解的問題時,就是考慮用 RL 的時候
* 在環境互動下得到最高的獎勵

1. Function with unknown
* input : 對環境的觀察
* output : 動作

2. Define loss : 將 -return 作為 episode 的 loss

3. Optimization : 最佳化存在隨機性,是訓練的難點

* 產生成對的資料表示期待的程度,讓 actor 執行人想要的行為

#### Policy Gradient
* V0 : 短視近利,會沿生諸多問題
* 行為並非獨立,都會影響後續
* 有時需犧牲短期獎勵以換取更大的獎勵

* V1 : 累積獎勵,相對合理,但過程冗長時,會怪

* V2 : 加入權重,降低較早動作的影響力

* V3 : 標準化,調整動作的期待程度

* V3.5 : 只拿一個 sample 減掉平均,會不準

* V4 : Advantage Actor-Critic,平均減平均

* 蒐集資料在迴圈內,每次更新要重新蒐集資料,對於當下的結果調整

* **TIPS** : actor and critic 可以共用參數

| On-Policy | Off-Policy |
| -------- | -------- |
| 互動、訓練同 actor | 互動、訓練不同 actor |
| Policy Gradient | Proximal Policy Optimization (PPO) |
* Exploration : 訓練過程中需包含隨機性,不然都會是一樣的動作

#### Actor-Critic
> 用於評估 actor 的好壞
> 用以下兩者評估,因假設不同,會有微妙的差異
* Monte-Carlo (MC) based approach : 與環境互動,看完整場靠近結果

* Temporal-difference (TD) approach : 不用看完整場,適用於無盡的遊戲

#### Reward shaping
> 憑人類的理解進行,設置額外的獎勵引導 agent
> Curiosity : 機器看到有意義的新東西就獎勵
> [Curiosity-driven Exploration by Self-supervised Prediction](https://arxiv.org/abs/1705.05363)
#### Limination learning
> 在某些任務中,定義獎勵很困難
> 人定義的獎勵可能導致奇怪的行為
> 從與環境的互動學習

* Behavior Cloning : 讓機器學習人類的行為
* 但人跟機器的視角不同,無法處理未知情況
* 機器會"完全"複製行為,包含如:個人習慣
##### Inverse RL
> 從 expert 的示範反推 reward function

> 老師的行為是最棒的(非完全模仿)
> 示範的得分要高於 actor 的

# Lecture 13 : Network Compression
## Preparation
> 前四個方法並非互斥,可以一起使用
> 為了隱私及延遲問題,將模型壓縮做邊緣運算是必要的
> 大的 Network 比較好訓練,小的並不比大的 Pruning 完的好 ([Lottery Ticket Hypothesis](https://arxiv.org/abs/1803.03635))
> [Rethinking Pruning](https://arxiv.org/abs/1810.05270) : Small lr & unstructured 可以讓小的 Network 表現比肩大的 Pruning
* Network Pruning : 將沒用的參數找出來剪掉, 一次剪掉太多參數可能會無法復原
* weight pruning : 可能讓網路變慢、難訓練

* neuron pruning : 較有效,只須改 in / out 的 dim

* Knowledge Distillation : 跟大模型學習,可以學到額外的資訊
加上 Temperature 讓模型學的更好

* Parameter Quantization
* 用較少的儲存空間存參數
* [Binary Weights](https://arxiv.org/abs/1511.00363)
* weight clustering

* Huffman encoding
* Architecture Design
* Depthwise Separable Convolution : 透過 Low rank approximation 減少參數使用

* Dynamic Computation : 讓 Network 自由調整運算量
* depth

* width : 訓練完後決定要使用多少參數

# Lecture 14 : Life-long Learning
## Preparation
> 災難性遺忘(Catastrophic Forgetting)讓模型分開學習任務,前面的任務會變差
* multi-task traininig : 要把所有任務的資料留著,每訓練新的任務,資料就要加上
* one task one model : 存不了所有模型,不同模型的資料無法互通
### evaluation
> 用後面的與前面相減,算出針對特定任務記住的程度

### solutions
#### Selective Synaptic Plasticity
> 讓網路中某些神經具有可塑性,某些則固化
> ***b~i~*** 通常是人為設置的,是主要的研究方向 (讓機器學習怎麼設,=0會壞掉)
> * 太大,遺忘前面任務
> * 太小,不妥協,不學新的

> 改變任務的順序也會影響表現,需存模型進行比較
##### Gradient Episodic Memory
> 需存一些過去的資料以決定前進的方向(稍違背LLL的初衷)

#### Additional Neural Resource Allocation
##### Progressive Neural Networks
> 不會有災難性遺忘,但增加任務會讓模型增長,任務不多適用

##### PackNet
> 先開一個大的模型,每個任務用一點參數,但最後還是會耗盡

##### Compacting, Picking and Growing (CPG)
> 既增加參數,又只保留部分參數

#### Memory Reply
##### Generating Data
> 效果逼近 multi-task traininig

# Lecture 15 : Meta Learning
## Preparation
> meta X = X about X
> meta learning = learn to learn
> 很多 few-shot learning 是從 meta Learning 找到的
1. 找出要被學的東西,e.g. 模型架構、初始化參數
2. 找出 learning algorithm 的 loss : 用多個同類型的任務的 loss 平均

3. 找出 loss 最小的 learning algorithm

### Machine v.s. Meta

#### Common point
* Overfitting on training tasks
* Get more training tasks to improve performance
* Task augmentation
* There are also hyperparameters when learning a learning algorithm
* Development task
### 優化
#### learn to initialize
* [Model-Agnostic Meta-Learning (MAML)](https://arxiv.org/abs/1703.03400)

* [Almost No Inner Loop (ANIL)](https://arxiv.org/abs/1909.09157) : 跟結果接近

* First Order MAML (FOMAML)
* [Reptile](https://arxiv.org/abs/1803.02999)
#### Optimizer
> 透過更好的優化讓表現更好

#### Network Architecture Search (NAS)
> 學出更好的架構

* Reinforcement Learning
* Barret Zoph, et al., Neural Architecture Search with Reinforcement Learning, ICLR 2017
* Barret Zoph, et al., Learning Transferable Architectures for Scalable Image Recognition, CVPR, 2018
* Hieu Pham, et al., Efficient Neural Architecture Search via Parameter Sharing, ICML, 2018
* Evolution Algorithm
* Esteban Real, et al., Large-Scale Evolution of Image Classifiers, ICML 2017
* Esteban Real, et al., Regularized Evolution for Image Classifier Architecture Search, AAAI, 2019
* Hanxiao Liu, et al., Hierarchical Representations for Efficient Architecture Search, ICLR, 2018
* [Differentiable Architecture Search (DARTS)](https://arxiv.org/abs/1806.09055)

#### Data Augmentation

* Yonggang Li, Guosheng Hu, Yongtao Wang, Timothy Hospedales, Neil M. Robertson, Yongxin Yang, DADA: Differentiable Automatic Data Augmentation, ECCV, 2020
* Daniel Ho, Eric Liang, lon Stoica, Pieter Abbeel, Xi Chen, Population Based Augmentation: Efficient Learning of Augmentation Policy Schedules, ICML, 2019
* Ekin D. Cubuk, Barret Zoph, Dandelion Mane, Vijay Vasudevan, Quoc V. Le, AutoAugment: Learning Augmentation Policies from Data, CVPR, 2019
#### Sample Reweighting

* Jun Shu, Qi Xie, Lixuan Yi, Qian Zhao, Sanping Zhou, Zongben Xu, Deyu Meng, Meta-Weight-Net: Learning an Explicit Mapping For Sample Weighting, NeurIPS, 2019
* Mengye Ren, Wenyuan Zeng, Bin Yang, Raquel Urtasun, Learning to Reweight Examples for Robust Deep Learning, ICML, 2018
#### Learning to compare
> 不靠梯度優化,用一個網路把訓練跟測試搞定

## Lecture
### Meta Learning vs. Self-supervised Learning
> 都是找初始化的參數
| MAML | BERT |
| -------- | -------- |
| 為了好的任務結果訓練 | 預訓練跟下游任務存在差距 |
| 運算量大,需標註資料 | 可用未標註資料 |
### Meta Learning vs. Domain Generalization
> 先訓練大的老師模型,再訓練小的學生模型
> 好的老師模型不見得擅長教學
> 調整老師的參數讓學生學得更好

### Meta Learning vs. Knowledge Distillation
> 擅長解 few-shot learning
> 用訓練任務學習出學習演算法,用於不同 domain 的狀況 (domain adaptation)
### Meta Learning vs. Life-long Learning
> 以不忘記為目標找出學習演算法
