![Improving Deep Neural Networks][0]
# Deep Learning Specialization
# Improving Deep Neural Networks: Hyperparameter Tuning, Regularization and Optimization
課程連結:
1. [Improving Deep Neural Networks: Hyperparameter Tuning, Regularization and Optimization][1]
2. [Structuring Machine Learning Projects][19]
3. [Convolutional Neural Networks][20]
課程作業(參考):
1. [oskird/DeepLearning.ai-Deep-Learning-Specialization][2]
## 8/25 (Jude): Practical Aspects of Deep Learning
### Setting up your ML application
#### Train/Dev/Test sets
![train/dev/test datasets][3]
一般機器學習模型都會需要有 train/dev/test 來做模型訓練。但是在深度學習上,這樣的共識會有一些不同:
* 深度學習不一定需要有 test set。主因有二:
* test set 最主要是確保模型不會有偏移,在 DL 上 dev set 即可做到這一點
* DL 太需要資料來訓練模型,省去 test set 可以增加 train set 的數量
* 對於巨量資料,不見得遵守 70/30 法則
傳統機器學習使用的資料量不會太大,需要一定量的資料來衡量模型的有效性。但是當資料量級足夠大時(> 1,000,000),儘管比例是 98/1/1,dev/test 還是足夠來衡量的
如同在傳統 ML 時進行資料分割,在**DL 更需要注意切割的資料均是來自同一個分配**,這點非常重要!
#### Bias / Variance
![high bias & variance][4]
在傳統機器學習上,bias-variance tradeoff 會是我們在意的事情。但在 DL 中,我們不常探討這件事情。主要是因為在神經網路中,有機會可以建出 high bias & high variance 的模型,也有機會可以建出 low bias & low variance 的模型。
如下圖,當建構複雜一點的深層模型並同時提供足夠的數據,或是選擇更適合的 NN 模型框架,都有機會可以既降低 bias 又不傷害 variance。這也是為什麼 DL 在監督式學習中能夠比傳統 ML 更有效。而這也不是完全沒有缺點的,建 DL 所需的時間則是硬傷。
![recipe for bias & variance][5]
### Regularizing your neural network
#### Regularization
![Regularization][6]
* 在 DL 中,加入 L2 的方式是在原本的 $dw$ 後面加上正則項。在經過整理後可以發現,計算 $w$ 迭代的 $w$ 變成 $(1-\frac{\alpha\lambda}{m})w$,這也是 L2 又稱為 weight decay 的原因。
* 在 DL 的 L2 嚴格說起來不算是 L2,正確名稱是 Frobenius norm。
* 因為 L1 可以讓 $w$ 變得稀疏,也些人聲稱這樣可以簡化模型,用更少的內存來訓練。但實際僅有些微幫助
* 理論上 DL 的參數 $w,b$ 皆可做正則化,但是 $b$ 相對於 $w$ 的數量太少,效果不大。
為何 Regularization 能有效防止 DL 模型 overfitting,主要可從兩方面看:
1. 加大正則項的 $\lambda$ 會使訓練將 $w$ 推向 0,意義上來說就是讓神經元失效
![neuron][7]
2. 在激活函數的層面上,如 tanh 激活函數,在 $w$ 趨近於 0 時,會促使 z 趨近於 0,進而導致 tanh 結果於 linear 相近
![tanh][8]
#### Dropout regularization
目前主流用的 dropout 都是指 inverted dropout,具體是在神經層設置 keep_prob,用來指定該層有多少比例的神經元會啟用,並參與 Forward/Backward propogation。要注意的是,inverted 指的是縮減的神經元計算後,要將值除以 keep_prob 以確保輸出總值不會因 dropout 而縮減。
在預測資料中,我們**不會在神經層實作 dropout**。主要原因是不希望輸出的結果是隨機的。這也是為什麼執行 inverted dropout 可以讓 test 的預測更有效率,因為 inverted 可以確保我們在不使用 dropout 時,輸出是一樣的 scale。
![why dropout works][9]
dropout 細節:
* 因為任何神經元都有可能在下一個樣本時就消失,所以不能太依賴個別神經元,因此權重都會傾向較小的值
* L2 與 dropout 帶來的效果很相似,但 L2 在不同 input 的應用更廣
* 實作 dropout 時,可以將參數過多的神經層給予較低的 keep_prob
* 在 CV ,因為樣本數通常不足,訓練出來的模型很容易 overfitting,也因此 dropout 很常在 CV 被使用。但須記住 dropout 是 overfitting 的一種應對方式,如果不是 overfitting,盡量不要使用
* dropout 的缺點是 cost function 比較不能 well-defined。因為會隨機去掉幾個 node,難以做 gradient check
#### Other regularization methods
其他正則化方式,課程中提到兩種:
1. Data augmentation
![Data augmentation][10]
2. Early stopping
![Early stopping][11]
訓練模型時,$w$ 會隨著迭代次數增加而逐漸變大,L2 就是在抑制 $w$ 變得太大,而 early stopping 則是在變大之前就停止
在模型訓練中,有所謂的[正交化方法][12],但 early stopping 違反了此方法之原則,這導致我們無法輕易在搜尋最佳解時找到最合適的參數。
* L2
* 優點: 超參數的搜索空間更容易分解,也更容易搜索
* 缺點: 優化 lambda 很花時間
* Early stopping
* 優點: 節省時間,可以嘗試不同 $w$ (大中小)
* 缺點: 違背正交化
### Setting up your optimization problem
#### Normalizing inputs
![Normalizing inputs][13]
Normalization 可以有效協助 gradient decent 趨近於最佳解,縮短訓練的迭代次數。在 input data 各特徵分配差異不大時,做不做 Normalization 影響不大。
#### Vanishing / exploding gradients
![Vanising / exploding][14]
Vanising / exploding 在深層神經網路很容易發生,而好的初始權重可以一定程度的解決這個問題。基本上來說,input 的 n 越多,權重 $w_i$ 就要越小。
建議的初始權重:
* ReLU: $\sqrt{2/n}$
* tanh: $\sqrt{1/n}$ or $\sqrt{2/(n^{[l-1]}+n^{[l]})}$ (Xavier initialization)
初始權重是可以做調參的,但相對於其他超參數來說,重要性低很多。
#### Numerical approximation of gradients
![Numerical approximation of gradients][15]
選擇 $\frac{f(\theta+\varepsilon)-f(\theta-\varepsilon)}{2 \varepsilon}$ 雖然比 $\frac{f(\theta+\varepsilon)-f(\theta)}{\varepsilon}$ 速度慢了近兩倍,但估計更精確,值得這樣做。
#### Gradient checking
![Gradient checking][16]
Gradient checking 主要是確認 $d\theta_{approx}$ 是不是趨近於 $d\theta$,以驗證 gradient decent 的計算邏輯沒有出錯。
- $$\frac{\left\|d \theta_{approx}-d \theta\right\|_{2}}{\left\|d \theta_{approx}\right\|_{2}+\left\|{d \theta}\right\|_{2}}$$
- 分母是為了將值轉換成比例,確保 $\theta$ 太大或太小時不會被影響。通常以 $\epsilon=10^{-7}$ 為基準,當此公式趨近於 $10^{-7}$,那麼可以不用太擔心。$10^{-5}$ 可以,但還是會 double check。$10^{-3}$ 估計是一定有問題了。
##### 執行 gradient checking 須注意:
* 非常耗時,確保完架構及計算邏輯沒問題後,訓練模型時要記得關掉
* 如果失敗了,就逐一確認是哪一層的哪個參數 $w,b$ 出了問題
* 如果有用 regularization,要記得將其納入 cost function,再進行檢查
* dropout 會消除對 cost function 影響大的 node,且隨機消除。這對 gradient check 的進行是非常困難的。一般會把 dropout 關掉,確保 gradient check 沒問題後,再開起來,祈禱一切沒有問題
* 固定 dropout 的 node 在計算 gradient 是可行的,但是實作起來實在大繁複,建議採用上述方式
* 雖然發生機率非常微薄,但有這個可能 $w,b$ 只有在趨近於 0 時,gradient decent 才會正確,一旦 $w,b$ 大起來,gradient decent 就會失效。 檢查方法可以在初始值時 ($w,b$ 趨近0) 時做一次 gradient check,做幾次迭代後 ($w,b$ 離開0) 再做一次 gradient check
### Quiz
![Quiz_w1][17]
### 作業
1. L1, L2 的原理
## 9/1 (Henry): Practical Aspects of Deep Learning
### Mini-batch Gradient Descent
- 課程總結
- 訓練速度 stochastic GD > mini-batch GD > batch GD
- 收斂性能 stochastic GD < mini-batch GD < batch GD
### Understanding Mini-batch Gradient Descent
- 
- mini-batch每次的訓練資料都不太一樣所以會有一點雜訊,但整體來說還是在持續往下的,所以不會是每次的 cost 都會是下降的
- mini-batch 大小
- 
- 如果你資料量太小 就直接用 batch GD < 2000 sample
- 大量的資料 64~512 盡量以2的次方數
- 另外你要去考慮到 CPU 跟 GPU 的一個記憶體,避免讀取不進來
- Exponentially Weighted Averages
- 
- 假設 E = 0.1 => 0.9 ** 10 大約等於 0.35 約等於 e 也就是第10個已經會是相對於current value 的 1/e 倍,也就是說間隔 1/(1-E) 個樣本以外的資料已經對於目前的數值影響不大
- [18]
- Bias Correction in Exponentially Weighted Averages
- 
- 
- Bias Correction in Exponentially Weighted Averages
- 
- GD with Momentent
- 
- 其中 a, b都是超參數,b的數值在0.9時有不錯的效果
- RMSprop
- root mean square prop
- 
- 在梯度較大的地方他的平方也會更大,在更新時,由於除與叫大的數也可以達到減緩的效果
- Adam
- 本質上他是 momentent + RMSprop
- 超參數的校調
- 
- Learning rate decay
- Local minima
- 
- plateaus 會讓訓練速度變慢
- 
- 
## 9/8 (Hawk): Hyperparameter Tuning, Regularization and Optimization
### Hyperparameter Tuning Process

在早期的機器學習,假設有兩個超參數,會使用像左圖的格子狀方法取樣
在現在的深度學習,主要是用右圖的隨機抽樣的方法
原因是:超參數的重要程度不一樣

由粗略到細緻-->
在找超參數時,可能會找到一區是比較好的數值,之後再縮小範圍去找更細微的超參數
### Using an Appropriate Scale to pick Hyperparameters

在找尋超參數時,需要等比例抽樣

在調教指數加權平均超參數,使用線性抽樣不好的原因是因為,在指數加權平均 β越接近1時,對結果的影響會越大
### Hyperparameters Tuning in Practice: Pandas vs. Caviar
- Re-test hyperparameters occasionally

- Pandas vs. Caviar

調整超參數
### Batch Normalization
#### Normalizing Activations in a Network

對每一層還沒經過激勵函數前的值做Normalizing

每層的標準差、平均值都會隨著參數(gamma,beta)改變
#### Fitting Batch Norm into a Neural Network

#### Why does Batch Norm work?


每一層的weight都會因為前層的輸入有所改變
為了要讓這個改變減少
讓每層輸入都經過Norm
#### Batch Norm at Test Time

Batch Norm 會製造一些噪音
會有一些 Dropout 和 regularization 的效果(但效果並不大)
### Multi-class Classification
#### Softmax Regression

softmax 主要是將輸出轉換成

沒有隱藏層的softmax


每日一推 --> https://leemeng.tw/index.html
# Structuring Machine Learning Projects
## 9/15 (Barry):ML Strategy (1)
### Orthogonalization

想讓監督式學習模型表現好,常要調整模型系統的旋鈕(knob)以達到下面四件事,而每個knob都有不同適合的狀況:
* Training set的表現要超過一定的門檻
* 某些應用中甚至要和人類的表現差不多
* bigger NN、better optimisation algorithm(Adam), etc.
* 在Dev set表現良好
* Training set表現好,Dev set不好 -> Regularisation、bigger Train set
* 在Test set的表現也良好
* maybe overtune the Dev set
* Dev set比現好,Test set不好 -> maybe overtune the Dev set -> bigger Dev set
* 模型能套用到真實世界 (5:33)
* (Training)/Dev set's distributions isn't set correctly
* cost function isn't measuring right
* either change Dev set or the cost function
盡量不用early stopping,會同時影響兩件事情,Training set的訓練(訓練次數變少),Dev set的表現會變好(lost一上升就停止訓練)
### Single Number Evaluation Metric

* Improve the efficiency of making decision
* 怎麼同時比較A、B兩個或更多classifiers base on precision and recall? -> F1 score(Harmonic mean)
* precision(準確率) : 預測正樣本中多少為實際正樣本
* recall(召回率) : 所有正樣本中能預測多少正樣本
* $$F-score=\frac{(1+\beta^2)precision \times recall}{\beta^2 precision+recall},\;where\;\beta=1$$
#### Another Example

### Satisficing and Optimizing Metric

* maximize acc subject to Running time <= 100ms
* Accuracy : optimizing metric
* Running time : satisfying metric
* N metrics :
* one optimizing
* N-1 satisfying
* Trigger word example :
* optimizing metric : Accuracy of trigger word detection system
* satisfying metric : # false positive (<= a particular number per one/several hour(s))
### Train/Dev/Test Distribution

* Dev and Test set come from the same dist.
* Bad idea : seperate dataset by regions
* targets aren't the same
* Recommended idea : shuffle data into two sets
* come from the same distribution of the mixed data
#### Example

#### Guideline

### Size of the Dev and Test Sets
#### Old way of splitting data

#### Size of test set

* Train-dev split
* Recommend to gave test set to get unbiased estimation
* It's ok to have simply training and dev set if having a very large dataset and not overfitting the dev set.
### When to Change Dev/Test Sets and Metrics?
#### Example

* In this case, we care about not only accuracy but false positive samples.
* Add a weight term to punish them
* Change the denominator accordingly
* When to change metric :
* Metric is not giving the correct rank order preference for actual better algorithm
#### Orthogonalisztion

* Step 1 : place the target
* Step 2 : consider how to shoot at the target
#### Example

### Why Human-level Performance?
* The performance of ML become competitive with human-level performance
* Make workflow more efficient
#### Comparing to human-level perfoormance

* Bayes error : the very best theoretical function for mapping from x to y that can never be surpassed
* Reason why progress slows down :
* Human-level performance is close to Bayes error
* Tools (tactics) no longer improve performance when progress surpass human-level performance

### Avoidable Bias
Gap btw Bayes error and training error.

* Classifier 1 :
* reduce bias : bigger neural network or run training set longer
* Tactics could help to do that (8% -> 1%)
* Classifier 2 :
* reduce variance : more data or regularization
* not much headroom to for reducing training error
* much more room for 2% gap
### Understanding Human-level Performance
#### Hunam-level error as a proxy for Bayes error

Define the proxy of Bayes error according to different purposes.
Appropriate goal : looking for the proxy for Bayes error?
#### Error analysis example

* 1st example : focus on bias reduction
* 2nd example : focus on variance reduction
* 3rd example : difficult to know whether to try to fit training set even better
#### Summary

* Comparing training error to 0% :
* Bayes error is nearly 0 (cat recognition)
* Set a proxy for Bayes error
* Noisy data (speech recognition on noisy audio)
### Surpassing Human-level Performance

Still be able to make progress but tools are no longer working.

* Structured data:
* System could have looked at far more data than any human could possibly look at
* Human does better on natural perception task
### Improving your Model Performance
#### The two fundamental assumptions of supervised learning

* Achieve low avoidable bias
* Variance is not too bad
#### Redicing (avoidable) bias and variance

## 9/22 (Poor Barry again):ML Strategy (2)
### Carrying Out Error Analysis

- 決定是否要往某個方向改善模型時,可以在dev set抽樣,做error analysis檢查改善的方向是否符合效益。
- 可以同時做不同方向的error analysis(辨識貓圖片為例)
- 狗
- 大型貓科
- 模糊圖片
- 濾鏡
- 
### Cleaning Up Incorrectly Labeled Data

- DL對隨機錯誤的分類能力強,但對系統性的錯誤分類能力較弱
- 
- 這類的錯誤能讓模型在dev set表現大幅提升時再去針對這些incorrects labels處理
- dev跟test set都要做一樣的事情,確保兩個資料及來自同分佈
- 不只檢查那些被分錯的樣本,被分對的樣本也要檢查(?0900)
- Training set 跟 dev/test set的分配會稍微不同,但通常合理
### Build your First System Quickly, then Iterate

先建一個粗糙的模型,做完error analysis後再針對遇到的情況去改進模型
### Training and Testing on Different Distributions

- 當資料來源不平衡,可以將target data set 拆一點到training set,而dev/test set全由target data set組成,讓訓練可以朝著想要的方向進行
- 舉例 : 語音辨識
- 
### Bais and Variance with Mismatched Data Distribution

- Training-dev set : 辨別training set和dev set之間的error是出在哪裡?
- Avoidable bias
- Variance
- Data mismatch problem

- Training/training-dev set檢查variance的程度
- dev/test set檢查過度配適的程度
- 
如果把dev/test set放到模型訓練結果得到跟human level error差不多的數字,說明之前的模型經訓練得不錯。
### Addressing Data Mismatch
- 以人工方式去分析training set與dev/test set之間的差異
- 聲音辨識中噪音來自人、車
- 街道名稱/號碼辨識錯誤
- 在training set中蒐集更多類似的資料來訓練(人工合成或網路蒐集)
- 
- 
### Transfer Learning

- 拿掉最後一層和進最後一層的權重,隨機初始化最後一層的權重後重新訓練新的資料集
- 資料集小 : 可以只訓練最後幾層
- 資料足夠 : 可以重新訓練整個神經網路(Pre-training->fine-tuning)
- 也可以不只新增一層網路或outputs(取決於資料多寡)
- 前一次學習到的資訊對下一次訓練會有幫助
- 圖片資料結構、學習完應該長怎樣...等等
- 語音辨識 : 不同trigger word
- Transfer Learning 可能沒有用 : 新資料樣本比原本的訓練資料集多(根據目的不同,資料的重要度也不同)
- 使用時機 : (Task A -> Task B)
- A跟B的input (X)一樣
- A的樣本比B多
- 經由學習A,對學習B也會有幫助(同樣都是辨識圖片OR語音辨識)
### Multi-task Learning

- 以自駕車為例,一張圖片要辨識出不同東西(行人、車輛...等等)
- Loss function :$\frac{1}{m}\sum_{\#of\;samples}\mathbf{\sum_{\#of\;classes}}L(\hat{y_{j}^{(i)}}, y_{j}^{(i)})$
- Useful logistic loss : $-y_{j}^{(i)}ln\hat{y_{j}^{(i)}}-(1-y_{j}^{(i)})ln(1-\hat{y_{j}^{(i)}})$
- 和softmax不同,softmax一張圖片只會有一個label,Multi-task可以有不只一個
- Multi-task 對只有一部分子集的資料集也可以進行訓練 ($\sum_{\#of\;classes}$只對0/1進行加總)
- Multi-task使用時機 :
- 各種task之間的資料特徵可以互相分享
- 每種task的資料量都差不多,且其他所有task樣本數>>單一task樣本數
- 資料量足夠多(網路要夠大),不然單個task訓練效果會更好
### What is End-to-end Deep Learning?

Pipeline,input資料後直接output結果

- 臉部辨識為例 :
- 找出人臉位置
- 剪裁整張圖使人臉在中間後再學習
- input兩張圖,output兩張人臉是否為同一人(boolean)
- 將步驟拆開能訓練的資料更多,效果有時比end-to-end learning效果還好
- Examples :
- 自動翻譯 : 資料量足夠多,end-to-end learning表現好
- 手骨辨識年齡(X光) : 將每跟骨頭分開辨識(subtasks)表現比直接用end-to-end辨識年齡效果好(資料不足)
### Whether to use End-to-end Deep Learning
- 優點
- Let the data speak(減少人為干預)
- 不用花時間去手刻一些需要的元件(特徵OR intermediate representation)
- An IR is any data structure that can represent the program without loss of information so that its execution can be conducted accurately
- 缺點
- 資料需求量大
- 排除可能有用的手刻元素(data給的insight不夠時,人們直接給的資訊對訓練有幫助)

- 用MD或ML去學習各別的component
- 選好X->Y的mapping的資料類型
- pure end-to-end learning對於現今的DL,效果沒有各別學習這麼好
# Convolutional Neural Networks
## 9/29 (Jude): Foundations of Convolutional Neural Networks
### What is Convolutional Neural Networks

一般來說,Convolutional Neural Networks 比較常用在 Computer Vision 的領域。主要因為圖片資料的維度相對一般資料大很多,Convolution 的方法可有效在有限維度下擷取特徵,並且保留空間資訊。
#### Edge Detection

Convolution 的應用主要從 edge detection 發展而來,透過特定的 filters ,可以擷取輪廓特徵,以及相應的亮度資訊。


Convolution 主要是一種計算手法,透過 filters 對原特徵的逐步相乘加總,產生新的特徵。
需要注意的是在數學定義上的 convolution 與這裡所說的 convolution 不大相同。嚴格來說,這裡的計算方式應該稱為 cross-correlation;而真正的 convolution 在相乘需先對 filter 的水平及垂直項反轉,以確保其結合律(associative property)。但因為 DL 的計算中不須有結合律特性,因此約定俗成免去此一操作,仍稱之為 convolution。

在傳統視覺處理上(DL 尚未流行前),要實施邊緣檢測通常是透過水平及垂直項檢測後再加權平均:
1. 轉成灰階
2. 對 x 方向做邊緣檢測
3. 對 y 方向做邊緣檢測
4. x, y 方向的邊緣檢測後的圖各以一半的權重進行合成

為了讓邊緣檢測能夠抓出更細節或更彈性的特徵,也有不少學術論文發展出不同的 filters 來做邊緣檢測。而在 DL 逐漸盛行後,filters 的權重也由人為決定變為讓 Backward-propagation 更有效的更新。
### Why We Need Convolutional Neural Networks

最主要採用 CNN 的原因,是因為圖片/影像的輸入通常非常龐大,導致在計算時的參數過多。即便現在的計算效能可以負荷,卻無法進行更深入的變化或特徵擷取。

而採用 CNN 不但能有效降低計算量,還保有一些特性:
1. Parameter sharing: 同樣的 filter 在圖片的各處皆可擷取有效的特徵。
2. Sparsity of connections: CNN 產出結果通常僅關聯特定數量的輸入參數,可讓模型更 robust。
3. translation invariance: 綜合上述特性,欲偵測的物件即便移動到圖片的其他地方,也能有效抓到。(更多說明參考[這裡](https://stats.stackexchange.com/questions/208936/what-is-translation-invariance-in-computer-vision-and-convolutional-neural-netwo),感謝 Barry carry~)
### How Does the Convolutional Neural Networks Work

詳細的運作邏輯可以看下面這張圖比較清楚:

#### Padding
Convolution 有兩個壞處:
1. 緯度不斷縮減
2. 邊角的 cell 只會被計算一次
為了避免這樣的問題,我們可以透過同時在左右外層加數值,來抵銷這個影響。

常見的 padding 方式有兩種:
1. Valid: 不做 padding
2. Same: 增加 pad 使得輸入和輸出的維度為持一致
為了避免僅做單邊的 pad 造成計算上的麻煩,filter 通常都會是奇數維度;另一方面,奇數維度的 filter 對找中心點也比較方便。
#### Strided Convolutions

移動 filters 的單位,舉例來說,如果 stride 為 2,那麼向右或向下移動,一次都一定要移動兩格。
要注意的是,如果移動後超出原特徵維度就不予計算。也因此計算 output 維度會對小數點後數值無條件捨去。
#### Output Size of CNN

### Pooling Layers
#### Max Pooling

雖然說 max pooling 名義上是希望把最大有用的特徵取出,但是不是為真的原因其實不得而知。比較多是因為用了有效。
#### Average Pooling

#### Summary of Pooling

**Average-pooling**
減少鄰域大小受限造成的估計值方差,保留更多的圖像背景信息
**Max-pooling**
減少卷積層超參數與 Feature maps 造成的估計均值偏移,保留更多的紋理信息
### CNN Example


一般來說,人們會把有 weight 跟 bias 需要 train 的 layer 才稱為 layer,依此邏輯來看,max pooling 不算 layer,通常會跟 conv 綁在一起看
activation size 如果下降太快,通常對表現不會太好
## 10/06 (Hawk): Case Studies

使用在,灰階數字辨識

激勵函數改為relu
有使用到LRN (Local Response Nomalization)
不希望太多神經元有太高的啟動值
現在的神經網路 已經不太使用



理論上 越深的網路error 會越來越低
但實際上反而會越訓練越差


ResNet 的感覺有點像 先把前面的input備份下來放到後層,
如果後層沒有學好,但還是保持原本的input
[Resnet](https://medium.com/@hupinwei/%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92-resnet%E4%B9%8B%E6%AE%98%E5%B7%AE%E5%AD%B8%E7%BF%92-f3ac36701b2f)


#### 1x1 convolution 作用:
1. 提高維度或降低維度
2. 處理各通道之間的合成



Inception Network 主要是 **小孩子才選擇 我全都要的概念**
使用各種filter 在將output合併在一起
但會遇到運算資料太大量的問題
就可以使用 1x1 convolution 減少運算量






Depthwise
對於 Input 中的每層 channel(depth) 各自單獨做 Convolution
pointwise convolution
從Depthwise中的output 進行1x1 convolution 的運算 得到想要的feature深度


1. 接收一個經過壓縮的 low-dimension representation
2. 此 module 會將此 representation 擴展成 high-dimension representation(Expansion)
3. 透過 depthwise 進行捲積
4. 將此 high-dimension representation 壓縮成 low-dimension representation(projection)

深度(depth)、寬度(width)、輸入圖片解析度(resolution)
針對不同的設備的計算量可以改變不同的網路架構
- 使用強化學習演算法實現的MnasNet模型生成基準線模型EfficientNet-B0。
- 採用複合縮放的方法,在預先設定的記憶體和計算量大小的限制條件下,對EfficientNet-B0模型的深度、寬度(特徵圖的通道數)、圖片大小這三個維度都同時進行縮放,這三個維度的縮放比例由網格搜索得到。最終輸出了EfficientNet模型。





電腦視覺的資料取得相對來說非常困難,所以在這方面才會有這麼複雜的網路
依賴很多人工標記
兩種方式在電腦視覺贏得比賽
- Ensembling
- Multi-crop at test time
用切圖去predict 在平均得到預測值
## 20211013 Henry
#### Object Localization
- 
- 
#### Object Detection
- 
- 運算成本
- Stride、Step + 正確率 -
- sliding window
#### Convolutional Implementation of Sliding Windows
- 
- 
#### Bounding Box Predictions
- 
- 
- 所以在偵測的時候他的高與寬有可能大於 1
#### Intersection Over Union
- 
#### Non-max Suppression
- 
1. 找最大pc
2. 找有與最大pc重疊的 bounding object 去抑制
- 
#### Anchor Boxes
- 
- 
- k-means 錨框
#### YOLO Algorithm
- 
- 
#### Region Proposals
##### R-CNN
- 
- 
#### Semantic Segmentation with U-Net
- 
#### Transpose Convolutions
- 
#### U-Net Architecture Intuition
- 
- 
### Question
- transpose conv overlap problem
## 10/20 (Sam): Face recognition & Neural Style Transfer - Week 4
### Face recognition
#### What is Face Recognition

The task of you having a face picture and want to verify the input face picture would be similar or not. -> Face Verification
The task of you having multiple face pictures and want to recognize the face input picture whether having similar one or not. -> Face recognition
#### One shot learning
Difficulty: We only have a few sample of correct person.
Solving idea: Using similarity or differ function.

#### Siamese Network & Triplet Loss correction
Network structure

* Chi square for loss function.
* b parameter to adjust loss function prevent all zero situation.
* Softmax for y-hat to classify 1 and 0.
idea: Using similar picture to train the net, which whould help the trainning process.



### Neural Style Transfer
#### What is neural style transfer?

#### What are deep ConvNets learning?

[paper-link](21)
* Shallow layer visualization -> small range and simple image
* Deep layer visualization -> huge range and complex similar image
#### Cost Function
**Target: Find a generated image(G) which close to input image content(C) and also similar to image style(S)**
$$
Equation => \{ Min(J(G)),J(G) =\alpha J_{content}(C,G) + \beta J_{style}(S,G) \}
$$
*Method: gradient decent*
#### Content cost fucntion
* You can use pretrained ConvNet (E.g., VGG network )

#### Style cost function
$$
J_{style}^{[l]}(S,G) = \frac{1}{(2n_H^{[l]}n_W^{[l]}n_C^{[l]})} \sum_k \sum_{k'}(G_{kk'}^{[l](S)}-G_{kk'}^{[l](G)})^2
$$

* Each G is the sum up of each activation$$(a_{ij})$$ times corresponding activation $$(a'_{ij})$$ of its channel $$k$$ in same layer $$l$$.
#### 1D and 3D Generalizations
##### 1D

##### 3D

## Homework Answer
- [inception softmax 問題](https://qastack.cn/stats/274286/google-inception-modelwhy-there-is-multiple-softmax)
- [Convolutional Transpose](https://towardsdatascience.com/understand-transposed-convolutions-and-build-your-own-transposed-convolution-layer-from-scratch-4f5d97b2967)
As we known, the convolutional network pooling with padding, and that is the reason the idea that on the reverse way we should still do the overlapping.
# Sequence Models
## 10/26 Rio: Recurrent Neural Networks


任何一个词t,设为x^t,都代表一个one hot vector 只有一个1其余为0

- $x^{<Tx>}$和 $y^{<Ty>}$长度不一样
- large input layer

将上一步计算结果作为其输入信息a^<1>, 在第零步的时候人为设a^<0>(random/0)
Wax,Waa,Wya 为参数
缺点:只用之前的参数来预测

g activation function: Tanh (common)Signoid(binary)k类分类(softmax)

简化矩阵

倒传递累积时间法


不同长度的input和output的many to many architecture



softmax function计算一个词汇出现在句子里的概率
根据上一步结果继续计算下一个词汇出现概论

用np.random.choice取sample
如果不想要unknown token出现在result里就reject所有unknown

优点:不用担心unknown 缺点:更长的序列,不适合找出句首和句尾的长距离关系,计算更复杂

result无法被较早的input所影响

c tilde is candidate for replacing c of t.compute this with tanh activation function
gate is called gamma u, u stands for update gate(0/1),using signoid(very close to 0 or very close to 1)
gate 决定要不要update c

r stands for relevant

a^t is no more equals to c^t, not using gamma r
two update gates gamma u and gamma f(for gate k)
output gate gamma o
use seperate update gate and forget gate

黄色:yhat3 example

## 11/3 (Barry) : Natural Language Processing & Word Embeddings
### Introduction to Word Embeddings
#### Word Representation

- One-hot representation : 無法知道label之間的關係,因為向量間相乘結果皆為0。圖中就算模型學到orange要接juice,但不會知道apple跟orange的關係相比其他的單字近,出現apple時又得重新學習。

- Featurized representation : 設計一連串的特徵並衡量每個單字對每個特徵的分數,讓模型在學習時可以透過特徵向量,增加對同種單字之間的辨識及聯想。

- [TSNE](https://mropengate.blogspot.com/2019/06/t-sne.html)
- [TSNE&PCA](https://medium.com/d-d-mag/%E6%B7%BA%E8%AB%87%E5%85%A9%E7%A8%AE%E9%99%8D%E7%B6%AD%E6%96%B9%E6%B3%95-pca-%E8%88%87-t-sne-d4254916925b)
#### Using Word Embeddings
##### Named Entity Recognition Example(專有名詞辨識)

- Transfer learning : 運用藉由網路上(或其他途徑)取得的資料(unlabel)訓練word embedding,再套用到要訓練的任務中。
- BRNN : 如果今天要訓練的任務是專有名詞辨識,用BRNN效果較佳。
##### Transfer Learning & Word Embedding
1. 在大量的語料庫(corpus)中訓練word embedding,或直接下載訓練好的。
2. 將結果transfer learning 到要訓練的任務上。
- 也能使用維度相對低的feature vector (10k one-hot vector -> 300 dimensional vector)
3. 選擇性地繼續微調word embedding(通常資料夠大時才會做)

- 人臉辨識最後的flatten layer(encoding),跟embedding有異曲同工之妙,一個比對兩張臉是否相同,一個比對兩個單字的性質。
#### Properties of Word Embeddings

- $e_{man} - e_{woman} \approx e_{King} - e_{w}$

- vector difference : difference in gender
- 許多研究中會有類比精準度(30-75%),因為只有配對到正確的單字才能算analogy attempt correct。
- TSNE降維後,左邊平行四邊形會被破壞,因為高維到低維的映射會打破點與點之間的位置關係。
##### cosine similarity
$sim(u,v) = \frac{u^Tv}{||u||_2||v||_2}$

透過Embedding matrix E 和one-hot vector相乘,可以把單字的特徵取出來。
[餘弦相似性](https://zh.wikipedia.org/wiki/%E4%BD%99%E5%BC%A6%E7%9B%B8%E4%BC%BC%E6%80%A7)
### Learning Word Embeddings: Word2vec & GloVe

- 句子經過embedding matrix後將向量當作NLP的input,再用softmax算出最有可能的output
- Fixed Historical Window : 設置一個超參數決定一次要取前幾個單字當作NLP的input
- $w$跟$b$可以透過倒傳遞和梯度下降去更新和學習。

- language model : last 4 word
- learn word embedding : other context
#### Word2Vec

- 隨機選取一個字當作context,再隨機選取任意window外的單字當作target

- Problems :
1. Computational Speed
- Hierarchical softmax classifier : 常見的字會被分類到較淺的位置,而少見的通常會在樹較深的位置。
- Negative Sampling
- How to Sample Context : 如果用均勻分配,常見的字會一直被選到;調整分配讓少見的字也能被選到。
#### Negative Sampling

1. 從字典中隨機選取單字當作negative sample
2. 將結果轉為監督式學習任務
3. 小資料集選5-20的單字,大資料集選2-5

假設原本句子有n個單字,模型要訓練n個Binary Logistic Regression,抽k個negative samples後剩k+1個模型。
how do u select negative samples
1. Empirical frequency in the corpus : 常見的字容易一直被選
2. $P(w_i)=\frac{f(w_i)^{3/4}}{\sum_{n}^{j=1}f(w_i)^{3/4}}$,其中$f(w_i)$是單字出現的頻率。
#### GloVe Word Vectors

- $X_{ij}$ : 計算i出現在j上下文的次數
- 當定義target和context會出現在彼此的$\pm n$個字內時,$X_{ij}=X_{ji}$

- 用梯度下降求 $\theta$ 和 $e$
- Weighting term $f(X_{ij})$ : 除了避免$X_{ij}=0$的情況,也避免讓常見單字(the, is, a ...)比重高,和少見單字(durian, cultivator, ...)比重太高 
- $\theta$ 和 $e$ 不完全對稱 : 均勻地初始化$\theta$ 和 $e$後執行梯度下降,再取平均
- $b_i$ 和 $b_j'$ 分別是 $e_{w_i}^{(final)}$ 和 $e_{w_j}^{(final)}$嗎 [info](https://thinkwee.top/2019/01/13/glove/)

- 無法保證embedding內的每個元件都能被解釋
- 每條軸(特徵)代表的可能是不只一個元素,很難只看單個元素去解釋某個特徵
- 線性代數裡面的A代表?
### Applications Using Word Embeddings
#### Sentiment Classification

- 訓練資料不夠 : 透過word embedding matrix E,可以有許多不常見的單字或不在訓練集的單字的資訊。
- 忽略字詞之間的順序 : 很多good會讓sum的模型判定為正面評價 -> RNN
#### Debiasing Word Embeddings

* Bias : 性別、種族、職業等等的刻板印象
1. Identify bias direction : 平均數、[SVD](https://ccjou.wordpress.com/2009/09/01/%E5%A5%87%E7%95%B0%E5%80%BC%E5%88%86%E8%A7%A3-svd/)
2. Neutralisation :
- 除了本質上非中立的單字(father、mother...)
- 映射至non-bias direction
3. Equalisation :
- 讓girl、boy、father...等單字的embedding之間的差別只有性別
- 訓練一個分類器來分辨哪些單字要Neutralisation(線性模型)哪些要Equalisation
## 11/10 (Jude): Sequence Models & Attention Mechanism
### Beam Search

Machine translation 又稱 Conditional language model,就是在給定 input 的情況下,預測 output 的序列結果。為了不讓每次產出的結果都會隨機變動,我們會期望結果是最大機率值如下:
$$
\underset{y^{<1>}, \ldots, y^{<T y>}}{\arg \max } P\left(y^{<1>}, \ldots, y^{<T_{y}>} \mid x\right)
$$
但因為 y 的排列組合隨句子長度越長,計算的時間複雜度也會指數成長。採用 heuristic 的演算法來嘗試找尋估計最佳解會是折衷的方式。
這裡要注意的是,我們不適合用 Greedy Search 來做最佳化演算,主要原因是 greedy search 每一步選擇中都採取在當前狀態下最好或最佳的解,以下方例子來說,Jane is _ 的單字,going 出線的機率一定比 visiting 高,然而這卻不是我們想要的答案。

Beam Search 會是尋求此問題最佳解的一種合適方法。演算法中會需要設定 Beam Width 來做為每一階段的最佳解候選。以下以 Beam Width = 2 說明。

- First Position
考慮模型在第一個位置的輸出。它以“\<START\>”標記開始,獲取每個單詞的概率。它現在選擇該位置的兩個最佳字符。例如。 “A”和“C”。
- Second Position
當到 Second Position 時,它重新運行模型兩次,通過將可能的字符固定在 First Position 來生成概率。換句話說,它將第一個位置的字符限制為“A”或“C”,並生成具有兩組概率的兩個分支。具有第一組概率的分支對應於 First Position 的“A”,具有第二組概率的分支對應於 First Position 的“C”。
現在,它根據前兩個字符的組合概率從兩組概率中選擇總體上最好的兩個字符對。所以它不會只從第一組中選擇一個最好的字符對,從第二組中選擇一個最好的字符對。例如。 “AB”和“AE”
- Third Position
當到 Third Position 時,它會重複該過程。它通過將前兩個位置限制為“AB”或“AE”來重新運行模型兩次,並再次生成兩組概率。
再一次,它根據兩組概率中前三個字符的組合概率來選擇總體上最好的兩個字符三元組。因此,我們現在有前三個位置的兩個最佳字符組合。例如。 “ABC”和“AED”。
- Repeat till END token
它繼續這樣做,直到它選擇一個“\<END\>”標記作為某個位置的最佳字符,然後結束該序列的分支。
計算的概率皆以 softmax 去跑過所有詞彙,進而找出最佳候選。也因此當 Beam Width 越大,計算的成本就越高,但精準度也會相對越高。
### Length Normalization
計算 Beam Search 的機率時,會隨預測的句子越長,導致機率相乘後數值變得非常小。
$$
\arg \max _{y} \prod_{t=1}^{T_{y}} P\left(y^{<t>} \mid x, y^{<1>}, \ldots, y^{<t-1>}\right)
$$
我們可以透過 $log$ 來對式子做調整,因為只是要取 y 的組合,不影響最後輸出。
$$
\arg \max _{y} \sum_{t=1}^{T_{y}} \log P\left(y^{<t>} \mid x, y^{<1>}, \ldots, y^{<t-1>}\right)
$$
但上述式子仍有問題,因為句子越短相加後的數值越大,但這樣的現象並不是我們樂見的狀況。因此我們會透過增加 $\alpha$ 這個參數來調整。以經驗法則來說,$\alpha = 0.7$ 結果不錯。
$$
\arg \max _{y} \frac{1}{T_{y}^\alpha} \sum_{t=1}^{T_{y}} \log P\left(y^{<t>} \mid x, y^{<1>}, \ldots, y^{<t-1>}\right)
$$
### Error Analysis on Beam Search
因為 Beam Search 是 heuristic 演算法,也因此並不能保證最佳解。這也會導致我們在遇到表現不佳時,較難判定是 RNN 模型本身的問題,還是 Beam Search 演算法造成的狀況。
我們可以透過*人翻譯的結果*比對*模型產出的結果*,來判斷狀況。

透過比較多個結果,就可以進一步推估需要往哪個方向調整。

### Bleu Score
在處理文字翻譯問題不像處理影像,影像的最佳解很清楚,要馬是貓要馬是狗,不會介於有或沒有之間。但文字不同,同樣一句話可以有好幾種不同的翻譯方式,沒有對錯或誰好誰壞,遇到這樣的狀況就可以使用 Bleu Score 讓模型評估準確度。

在 bigrams 的情況,我們可以計算 Count (在 MT output 出現次數) 及 Count Clip (該字詞於各 Reference 出現的最大次數) 的比值,做為 modified precision 來評估。

計算上,我們可以取多個 n-grams 做評估標準。值得注意的是,當預測的句子就等於 Reference 時,這 n-grams 機率都為 1。因為 Bleu Score 也會有句子越短越精準的狀況,也因此加入 B 這個參數作為懲罰參數。當預測的句子長度比 Reference 多時,懲罰參數為 1,惟有在預測句子短於 Reference 時才會有懲罰項影響。
### Attention
當需要翻譯的句子變得很長時,模型的結果也會越變越差。就像人類一樣,一次給一個很長的句子是很難翻譯好的,通常都是一部分一部分翻,Attention 就是這樣的概念。


進入 decoder 之前,每個 encoder 進來的 input 都會乘上一個 attention 的係數加權平均。實際上的係數則是透過一個小的神經網路層計算而來。因此計算量非常龐大,但是相對精準。詳細可參考[這裡](https://medium.com/chiukevin0321/sequence-models-week-3-601e5e9529c4)。

### Speech Recognition



CTC 一般建議輸出長度要是目標字詞的 $2n+1$ 長。
### Trigger Word Detection

### 上週作業
1. Hirarchical softmax classifier 怎麼放到模型
https://www.quora.com/What-is-hierarchical-softmax
2. activation word embedding
Word embedding has no activation function.
3. inception network 為什麼要那麼多 softmax,為什麼可以防止 overfitting
https://www.analyticsvidhya.com/blog/2018/10/understanding-inception-network-from-scratch/
### 補充
1. self-attention
https://www.youtube.com/watch?v=hYdO9CscNes&ab_channel=Hung-yiLee
## 2021/11/17 Henry
### Transformer Network intuition
- 
- Attention + cnn
- self-attention
- multi head attention
- 循序型的模型,模型天生無法平行化運算,所以 GPU 就無用武之地,只能靠 CPU 慢慢跑。
### self attention
- 
- 
- 
- 
- 
- 
### multi-head attention
- 
- 多頭注意力機制(Multi-head Attention)是將輸入序列中的每個位置的 q、k 和 v 切割成多個 qi、ki 和 vi 再分別各自進行注意力機制。各自處理完以後把所有結果串接並視情況降維。這樣的好處是能讓各個 head 各司其職,學會關注序列中不同位置在不同 representaton spaces 的資訊。
- 
### transformer network
- 
- Position encoding
- 不是學出來的而是人設置的
- Masked Multi-head Attention
- 做Attention,Masked表示只會attend到已經產生出來的sequenc e,再經過Add & Norm Layer
- [參考資料](https://hackmd.io/@abliu/BkXmzDBmr#Multi-head-Self-attention)
- [看起來可能是酷東西](https://ithelp.ithome.com.tw/articles/10206464)
- [RNN 之死](https://towardsdatascience.com/the-fall-of-rnn-lstm-2d1594c74ce0)
------
<!-- links -->
<!-- 請把 links 保留在最下面,謝謝 -->
[21]:https://arxiv.org/pdf/1311.2901.pdf
[20]:https://www.coursera.org/learn/convolutional-neural-networks/home/welcome
[19]:https://www.coursera.org/learn/machine-learning-projects?specialization=deep-learning
[18]:http://zh.gluon.ai/chapter_optimization/momentum.html
[17]:https://i.imgur.com/N5hMRuQ.png
[16]:https://i.imgur.com/OnNs7JQ.png
[15]:https://i.imgur.com/tikRMZJ.png
[14]:https://i.imgur.com/3VtQRxO.png
[13]:https://i.imgur.com/D8RWHf4.png
[12]:https://baozoulin.gitbook.io/neural-networks-and-deep-learning/di-san-men-ke-jie-gou-hua-ji-qi-xue-xi-xiang-mu-structuring-machine-learning-projects/di-san-men-ke-structuring-machine-learning-projects/di-yi-zhou-ml-strategy/12-zheng-jiao-hua-ff08-orthogonalization
[11]:https://i.imgur.com/bbx8ORQ.png
[10]:https://i.imgur.com/6iMkFO5.png
[9]:https://i.imgur.com/8YaIrw6.png
[8]:https://i.imgur.com/e0Lt3ud.png
[7]:https://i.imgur.com/ZqtZSEx.png
[6]:https://i.imgur.com/Rqi7BeQ.png
[5]:https://i.imgur.com/fKb1ZjI.png
[4]:https://i.imgur.com/FfOWpM5.png
[3]:https://i.imgur.com/00ZKeej.png
[2]:https://github.com/oskird/DeepLearning.ai-Deep-Learning-Specialization
[1]:https://www.coursera.org/learn/deep-neural-network?specialization=deep-learning
[0]:https://i.imgur.com/FGvatkx.png