# 深度學習網路基礎 [toc] ## Lecture 2. Concepts of Deep Learning ### Neural Networks ![image](https://hackmd.io/_uploads/BysRDM_oyl.png) 目的:從資料中學習目標的分佈 ![image](https://hackmd.io/_uploads/r1WBdMOiJx.png) 過程:利用 gradient descen 調整參數,以找到最小的損失函數θ ### Gradient Descent ![image](https://hackmd.io/_uploads/SJPiOf_i1l.png) $\nabla_\theta L(\theta)$:損失函數對參數$\theta$的梯度,表示$L(\theta)$在不同方向的變化率 * $L(\theta)$:損失函數 * 目標:在訓練過程最小化$L(\theta)$ * 沿著梯度的<font color=red>**相反方向**</font>進行更新 * $\nabla_\theta$:梯度(表示對變數 𝜃 進行微分) * positive gradient($\nabla L(\theta)>0$):正梯度(斜率為正),增加 𝜃 會增加損失 * negative gradient($\nabla L(\theta)<0$):負梯度(斜率為負),沿著梯度下降的方向才能減少損失。 $\theta^{(t+1)} = \theta^{t} - \alpha \nabla L(\theta)$:參數更新 * $\alpha$:Learning rate * 控制每次更新時,𝜃 移動的步長。 * 學習率過大:可能會錯過最佳解(掉到局部最佳解)。 * 學習率過小:收斂速度變慢,訓練時間變長。 * <font color=red>$-$</font> $\alpha \nabla L(\theta)$ * <font color=red>**反向更新**</font>,朝著降低損失的方向前進。 * 如果是負梯度($\nabla L(\theta)$為負),代表向右移動($\theta$變大),會朝向越低的方向。 ### Common Task & Loss function * Regression 預測連續的數字 * Mean Squared Error (MSE) * $L_{\text{MSE}} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ * Mean Absolute Error (MAE) * $L_{\text{MAE}} = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|$ * Huber Loss (Smooth L1 Loss) * $\begin{cases} \frac{1}{n} \sum_{i=1}^{n} \frac{1}{2} (y_i - \hat{y}_i)^2, & \text{if } |y_i - \hat{y}_i| \leq \delta \\ \frac{1}{n} \sum_{i=1}^{n} \delta \left( |y_i - \hat{y}_i| - \frac{1}{2} \delta \right), & \text{otherwise} \end{cases}$ * 結合 MSE 與 MAE * Classification 分類成離散的標籤 * Cross-Entropy Loss (for Binary Classification) * $L_{\text{CE}} = - \frac{1}{n} \sum_{i=1}^{n} \left[ y_i \log \hat{y}_i + (1 - y_i) \log (1 - \hat{y}_i) \right]$ * $L(y, \hat{y}) = -y \log \hat{y} - (1 - y) \log (1 - \hat{y})$ * 當預測信心低時,損失較大,梯度較大,更新力度更強。 * 當模型的預測值 $\hat{y}_i$ 偏離正確答案時,梯度會變大,從而對模型的更新產生較大影響。 * 假設預測值 $\hat{y}$ 和真實標籤 $y$ 如下: * 如果 $\hat{y} = 0.5$ 但 $y = 1$,則:$-\log(0.5) \approx 0.69$,變化較大 * 如果 $\hat{y} = 0.99$ 但 $y = 1$,則:$-\log(0.99) \approx 0.01$,變化較小 * 促使正確類別的預測機率接近 1。 * 當預測錯誤時,交叉熵的損失會很大(懲罰錯誤的預測)。 * 隨著訓練的進行,模型會調整權重,使得: * 當 $y = 1$ 時,$\hat{y} \to 1$ * 當 $y = 0$ 時,$\hat{y} \to 0$ * Cross-Entropy Loss(for Multiclass Classification) * $L_{\text{CE}} = - \sum_{i=1}^{n} \sum_{j=1}^{k} y_{i,j} \log \hat{y}_{i,j}$ * $L(y, \hat{y}) = - \sum_{c=1}^{C} y_c \log \hat{y}_c$ * 配合 Softmax 產生機率輸出: * Softmax 會把 logit 轉換成機率,保證所有類別的機率加總為 1。 * 假設真實標籤 $y = [1, 0, 0]$ * 假設模型的預測機率為:$\hat{y} = [0.7, 0.2, 0.1]$ * $L(y, \hat{y}) = - (1 \cdot \log 0.7 + 0 \cdot \log 0.2 + 0 \cdot \log 0.1)$ * $L(y, \hat{y}) = -\log 0.7 \approx 0.36$,較小的懲罰 * 假設模型的預測機率為$\hat{y} = [0.1, 0.8, 0.1]$ * $L(y, \hat{y}) = -\log 0.1 = 2.3$,置信低,較大的懲罰 * Kullback-Leibler Divergence (KL Divergence) * $D_{\text{KL}}(P \| Q) = \sum_{i} P(x) \log \frac{P(x)}{Q(x)}$ * 衡量兩個機率分佈之間的差異 * 用於 probabilistic models 與 variational inference ### Guide for Designing Loss Functions Key factors: 1. 可微性(Differentiability) - 允許計算梯度。 * 例如: * 隨機變數 * 離散值 * 左右極限不匹配 * Subgradient * 處理不可微的情況,直接給定一個值。 * 定義:$f(y) \geq f(x) + g (y - x), \quad \forall y$,$g$為次梯度集合 * 範例: * L1 Loss: The function $f(x) = |x|$ is non-differentiable at $x = 0$, where subgradient $g \in [-1,1]$. * $\nabla f(x) = \begin{cases} 1, & x > 0 \\ -1, & x < 0 \end{cases}$ * ReLU Activation: The function $f(x) = \max(0, x)$ is non-differentiable at $x = 0$, where subgradient $g \in [0,1]$. * $\nabla f(x) = \begin{cases} 1, & x > 0 \\ 0, & x < 0 \end{cases}$ 2. 梯度大小(Gradient Magnitude) - 避免梯度消失或爆炸。 * Choosing the Right Error Metric * MSE, MAE, Smooth L1 * Regularization to Prevent Large Gradients * L1 Regularization * L2 Regularization * Gradient Clipping to Directly Limit Gradient Size * $g' = \begin{cases} g, & \text{if } ||g|| \leq g_{\max} \\ \frac{g_{\max}}{||g||} \cdot g, & \text{if } ||g|| > g_{\max} \end{cases}$ 3. 梯度平滑性(Gradient Smoothness) - 讓優化更穩定。 * 優勢 * 避免梯度震盪 * 提高收斂速度 * 穩定學習 * 如何確保平滑 * Avoid non-differentiable points 避免不可微的點 * MAE → Smooth L1 Loss * Control sharp gradient changes 控制急遽的梯度變化 * MSE * Weighted Loss Function(加權損失函數) * $L(y, \hat{y}) = w_i (y - \hat{y})^2$ * 動態調整$w_i$,當某些樣本的誤差過大時,使用較小的權重 * Clipped Loss Function(裁剪損失函數) * $L(y, \hat{y}) = \min((y - \hat{y})^2, C)$ * 設定最大損失值 𝐶 來限制梯度,防止極端誤差影響訓練。 * Prevent vanishing gradients 防止梯度消失 4. 梯度方向(Gradient Direction) - 確保梯度正確指導更新方向。 * 原因 * 多個極小值 * 急遽變化 * 如何指導 * 自適應學習率(如 Adam、Adagrad) 5. 凸性(Convexity) - 使優化更容易找到全局最小值。 * 原因 * 非凸函數可能有多個局部最小值 * Saddle Points * 在某些方向是極小值,但在其他方向是極大值。 * 難以下降,無法離開該點 * 如何找到 * Batch Normalization * 自適應學習率(如 Adam、Adagrad) * 隨機梯度下降(SGD) ## Lecture 3. Practical Issue of Model Training - Overfitting and Underfitting ![image](https://hackmd.io/_uploads/SkVZhBusyx.png) ### Overfitting ![image](https://hackmd.io/_uploads/BJcgaSdiyl.png) * Fitting to noise 擬合到非正確的特徵 #### How to reduce overfitting 降低複雜度,但提升泛化效果跟穩定性 * Increasing the dataset * Data augmentation * Regularization * L1 Regularization * 公式:$\text{L1} = \sum_{i} |w_i|$ 加入權重總和 篩選特徵 * L2 Regularization * 公式:$\text{L2} = \sum_{i} w_i^2$ 加入權重平方的總和 讓權重變得平均 * Dropout * 隨機遮罩神經元 ![image](https://hackmd.io/_uploads/SklzaHOskl.png) 降低複雜度 ### Underfitting ![image](https://hackmd.io/_uploads/HynETruskl.png) * Noise or weakly stuctured data * 模型參數量太低 * 例如:單層感知器的XOR問題 ![image](https://hackmd.io/_uploads/HyRq3H_jyg.png) * Learning rate too high #### How to reduce Underfitting * 有規律的資料 * data cleaning 篩選掉錯誤的資料 * 優質的資料 挑選品質高的資料 * Reduce Learning rate * 增加模型參數量 ## Lecture 4. CNN Structure and Its Technical Operations ### FCN (Fully Connected Network) 1. Flattening the Image 2. Input Processing & Inference (Forward Pass) 3. Training & Optimization (Backpropagation) #### Flattening * 將圖片轉換成一維的向量 * 例如:28x28的圖片,轉換成784的向量 ![image](https://hackmd.io/_uploads/ByQ3TrOjyg.png) #### Input Processing & Inference ![image](https://hackmd.io/_uploads/H1zapSdj1e.png) Forward Propagation Workflow: * Input Layer * Hidden Layer * Activation Function * ReLU * Sigmoid * Tanh * Output Layer #### Training & Optimization Backpropagation Workflow: * Loss Function * Mean Squared Error * Cross Entropy * Optimizer * Gradient Descent * Adam #### FCN的問題 * 參數量大 * 占用大量的記憶體空間 * 計算量大 * 訓練時間長 * 容易過擬合 ### Convolutional Neural Network (CNN) #### Convolutional ![image](https://hackmd.io/_uploads/rkyBRBOokx.png) 為了能提取特徵: * Shapes and contours 邊緣和輪廓 * Colors and textures 顏色和紋理 * Relative size and proportions 相對大小和比例 * Context 上下文、鄰域的資訊 #### 不同的 kernel 提取不同的特徵 ![image](https://hackmd.io/_uploads/S1xE0BdoJg.png) * Edge Detection * Sharpen * Blur * Emboss #### Architecture ![image](https://hackmd.io/_uploads/BJ-d0Sdi1g.png) * Fully Connected * Convolutional Layer 提取特徵 * Pooling Layer 融合特徵 ##### Convolutional Layer 目的:提取出特徵圖 * Feature maps 一個二維的矩陣,代表了圖片中的特徵 * Input channels 輸入的圖片的通道數 ![image](https://hackmd.io/_uploads/SJfl1Udike.png) * RGB或是有深度的圖片 * Input channels = Filter channels * Output channels 輸出的特徵圖的通道數 ![image](https://hackmd.io/_uploads/HJIby8Oj1g.png) * 有多少個特徵圖 * N kernels, it will output N feature maps. * 參數 * Kernel Size 提取特徵的區域大小 ![image](https://hackmd.io/_uploads/rybOyUus1g.png) * 3x3 or 5x5 ... * Stride 移動的步長 ![image](https://hackmd.io/_uploads/B11wyLuj1e.png) * 1 or 2 ... * Higher stride 特徵圖變小 計算量小 * Lower stride 保留微小的變化 計算量大 * Padding 為了保持圖片大小不變 ![image](https://hackmd.io/_uploads/S1_5yL_okl.png) * Types * Same padding * Padding zeros * Valid padding * No padding * Forward Pass 步驟是:先卷積,再激活 ![image](https://hackmd.io/_uploads/S1t2yIOikg.png) * Convolution * Activation Function * ReLU * Sigmoid * Tanh * Output * Feature Maps * Backward Pass 步驟是:計算梯度,更新權重 * Loss Function * Optimizer * Update Weights ##### Pooling Layer 特徵多時,會導致參數量過大或是有冗餘、雜訊的資訊 目的:經過 Pooling Layer 可以將特徵圖縮小,並保留重要的特徵 Types: ![image](https://hackmd.io/_uploads/BkWAkU_s1l.png) * Max Pooling 取最大值 * 2x2 or 3x3 ... 圖片 * Forwards Pass * Backwards Pass * Average Pooling 取平均值 * 2x2 or 3x3 ... 圖片 * Forwards Pass * Backwards Pass * Global Pooling 取整張圖片的特徵 * Global Average Pooling * Global Max Pooling ## Lecture 5. The Variants of CNN Models ### CNN Models 1. LeNet-5 第一個cnn網路 2. AlexNet 第一個大型圖片辨識、GPU訓練、ReLU Activation的網路 3. VGGNet 提倡深度 4. GoogLeNet Inception Block融合多尺度特徵與1x1 Convolution降維 5. ResNet Skip Connection #### Backpropagation 從輸出層向輸入層傳遞誤差,並有效計算梯度的演算法。 1. Forward Pass:模型做預測 從輸入層開始,一層一層計算每層的輸出,直到產生最終預測結果。 2. Loss Function:計算誤差的方法 將模型預測結果與實際答案做比較,計算出誤差。 3. Backward Pass:模型知道錯在哪,然後修正自己 利用鏈式法則(chain rule),將誤差從輸出層往回傳遞,計算各層參數的梯度,更新參數。 ### LeNet-5 * 時代背景:SVM, KNN 等需要人工特徵 * CNN始祖:LeNet-5:用CNN(Convolutional Neural Network)自動提取特徵 * 應用:MNIST Dataset #### Architecture * Input: 32x32x1 * Convolutional Layer 1: 6@28x28 * Kernel: 5x5 * Stride: 1 * Activation: tanh * Pooling Layer 1: 6@14x14 * Convolutional Layer 2: 16@10x10 * Pooling Layer 2: 16@5x5 * Fully Connected Layer 1: 120 * Activation: tanh * Fully Connected Layer 2: 84 * Activation: tanh * Output Layer: 10 * Activation: softmax(轉成機率) 針對每個類別的機率(0~9的手寫數字) ![image](https://hackmd.io/_uploads/BJ8fT_62kx.png) #### Why LeNet-5 can work? * Feature Extraction * Convolutional Layer * Pooling Layer * Shard Weight * Fully Connected Layer * Hierarchical structure * 提取全局跟局部特徵 * 層層提取特徵 ### AlexNet * 時代背景:LeNet-5的局限性,希望達成更複雜的任務 * TanH/Sigmoid Activation leads to vanishing gradient * Key Points * ReLU Activation * 解決梯度消失問題 * GPU Training * First time to use GPU for training * Dropout Regularization * To prevent overfitting * Data Augmentation * Local Response Normalization * Overlapping Max Pooling * 提取特徵 * Stochastic Gradient Descent with Momentum * 應用:ImageNet Dataset * 1000個類別 * 1.2 million張圖片 #### Architecture * Input: 227x227x3 * Output: 1000 * Activation: softmax * Convolutional Layer for Feature Extraction * 使用更大的 Kernel Size * Fully Connected Layer for Classification * 使用更多的神經元 ![image](https://hackmd.io/_uploads/SywNa_ankl.png) ### VGGNet * 時代背景:AlexNet使用了較大的Kernel Size, * 提倡深度:VGGNet使用更多的Convolutional Layer,增加深度,而非增加Kernel Size。 #### Architecture VGGNet-11, VGGNet-13,VGGNet-16, VGGNet-19 不同的VGGNet有不同的深度 差異:Block內的Convolutional Layer數量 * Block 1: 224x224x3 * Block 2: 112x112x64 * Block 3: 56x56x128 * Block 4: 28x28x256 * Block 5: 14x14x512 * Block 6: 7x7x512 * Fully Connected Layer: 4096 * Output: 1000 * Activation: softmax ![image](https://hackmd.io/_uploads/HkBHTO631l.png) #### Why Small Kernel work better? * More Non-linear Activation * More Parameters * More Feature Extraction ### GoogLeNet * 時代背景:VGGNet的缺點,參數量過大 * 理念:使用更少的參數量,提高效率,但保持準確度 * 減少計算量 * 減少記憶體使用量 * Inception Block: multi-scale feature extraction * 將不同尺度的Kernel合併 * 1x1 Convolution * 3x3 Convolution * 5x5 Convolution * Max Pooling ![image](https://hackmd.io/_uploads/rkl0pdpnJg.png) * Concatenate: 串接在一起,將不同尺度的特徵合併 * Use 1x1 Convolution to reduce the number of channels * 能夠降維 * 降低計算量 * 降低記憶體使用量 * 保留重要的特徵,並且減少參數量 ![image](https://hackmd.io/_uploads/ByL0T_Thye.png) * Why 1x1 Convolution reduce computation? * Step1: 1x1 Convolution to reduce the number of channels * Step2: 3x3 or 5x5 Convolution on the reduced feature map * Result: Reduce the number of parameters * Example: 1x1 Convolution on 64 channels to 16 channels * 64x64x64 = 262144 * 16x64x64 = 65536 * 1/4 of the original parameters #### Architecture * Total 22 layers * Key Components * Stem * 7x7 Convolution * 3x3 Max Pooling * 3x3 Convolution * 9 Inception Blocks * Global Average Pooling + Fully Connected Layer ![image](https://hackmd.io/_uploads/Bkd1AdT3Jg.png) * Parameters: Only 6.8 million (VGGNet: 138 million) 更低的參數量,但更高的準確度 #### 問題:更深的網路,會不會有vanishing gradient的問題? * 解決方法:Auxiliary Classifier * 在中間的層加入一個分類器 * 用來幫助梯度傳播 * 但不會影響最終的預測結果 * 但在訓練時,會增加計算量 ### ResNet * 時代背景:網路越深通常越好,但是會遇到vanishing &exploding gradient、Degradation問題。 * Don't Learn Everything, just learn the difference * 專注於學習殘差 * 將輸入與輸出相加 * F(x) = H(x) - x → H(x) = F(x) + x * Residual Block * Skip connection * 避免資訊流失 ![image](https://hackmd.io/_uploads/H1gLRO62ke.png) #### Architecture 在 VGG19 的基礎上,加入了 Residual Block,設計了ResNet-34 ![image](https://hackmd.io/_uploads/H1XvRuahkg.png) ## Lecture 6. Introduction to CNN Object Detection Models ### Object detection * Object Detection * Two-stage * R-CNN * Fast R-CNN * Faster R-CNN * One-stage * YOLO #### Non-Maximum Suppression ![image](https://hackmd.io/_uploads/B15gfFa2ye.png) 從許多的候選框中,選擇出最有可能的框,並且去除掉重疊的框。 ![image](https://hackmd.io/_uploads/H1tGGKah1e.png) 1. Sorting: 排序所有的候選框,按照分數的高低 2. Selecting: 選擇分數最高的候選框,將其加入最終的結果中 3. Removing: 移除與已選擇的框重疊率(IOU)高於閾值的候選框 4. Repeat: 重複步驟2-3,直到所有的候選框都被處理 ### R-CNN ![image](https://hackmd.io/_uploads/H1hVzt6nJg.png) * Region-based Convolutional Neural Networks * two-stage object detection 1. Stage1: Region Proposal Generation * Selective Search * 可能的物件位置 * 用大小、材質、顏色等特徵,將圖片分割成不同的區域 * 將相似的區域合併 2. Stage2: CNN for classification * Support Vector Machine * 解決是否為該類別的任務 是貓、是狗、是人? * Problem * Slow * Not end-to-end * 知道是什麼物件,判斷物件的類別 * Bounding Box Regression 修正框的大小 * NMS 選擇最好的框 ![image](https://hackmd.io/_uploads/H1g9fF6hyx.png) ### YOLO ![image](https://hackmd.io/_uploads/r17RGKa2Jx.png) * You Only Look Once * 直接預測物件的類別和位置 * regression problem * Fast * Global context * Better Generalization 可以跨越資料集 * one-stage object detection 1. Grid Division 2. Bounding Box Prediction 3. Non-Maximum Suppression ![image](https://hackmd.io/_uploads/B1cJmtpnyx.png) #### Architecture ![image](https://hackmd.io/_uploads/B1FgQYThJx.png) * Input: 448x448x3 * Output: 7x7x30 * 7x7 grid * 2 bounding boxes * 20 classes * [S, S, B * 5 + C] * S: grid size * B: bounding boxes(x, y, w, h, confidence) * C: classes * 告訴我們哪些格子有物件,物件的位置,物件的類別以及信心度 #### Loss Function * Corrdinate Loss(Bound Box Prediction Loss) * $L_{coord} = \sum_{i=0}^{S^2} \sum_{j=0}^{B} 1_{ij}^{obj} [(x_i - \hat{x}_i)^2 + (y_i - \hat{y}_i)^2]$ * $L_{coord} = \sum_{i=0}^{S^2} \sum_{j=0}^{B} 1_{ij}^{obj} [(w_i - \hat{w}_i)^2 + (h_i - \hat{h}_i)^2]$ 預測的框和實際的框的差距 * Confidence Loss * $L_{conf} = \sum_{i=0}^{S^2} \sum_{j=0}^{B} 1_{ij}^{obj} (C_i - \hat{C}_i)^2 + \lambda 1_{ij}^{noobj} (C_i - \hat{C}_i)^2$ Bounding Box 內有沒有物件的信心度 * Classifcation Loss * $L_{class} = \sum_{i=0}^{S^2} 1_{ij}^{obj} \sum_{c \in classes} (p_i(c) - \hat{p}_i(c))^2$ 對於每一個格子,如果有物件,計算類別的損失 ## Lecture 7. Lightweighting Methods of CNN ### LightWeight * 問題:模型太大 * 移動端 * Real-time * Cloud Computing cost * 目標:模型輕量化 * 小模型 * 減少參數 * 方法 * Method-based * 知識蒸餾 用小模型學習大模型的行為 * Structure-based 從現有模型去優化 * 網路剪枝 * 網路量化 * 結構優化 #### Knowledge Distillation ![image](https://hackmd.io/_uploads/ry5DmFTh1l.png) * Teacher Model * 大模型 * 高精度 * Student Model * 小模型 * 低精度 讓 Student Model 學習 Teacher Model 的行為 有同樣或近似的機率分佈 * same input/ output * softmax: 得到機率分佈 * KL Divergence: 計算兩個分佈的差異 ![image](https://hackmd.io/_uploads/ByrjQFT2yg.png) #### Structure Optimization * Pruning 並不是所有的神經元都是重要的 ![image](https://hackmd.io/_uploads/ryJ1VK62Jl.png) * Weight Pruning 丟棄不重要的權重 * L1/L2 Regularization 讓權重變得平均 * Global Pruning 去除整個模型的不重要權重 * Layer-wise Pruning 去除每個層的不重要權重(如5%) * Structured Pruning 丟棄不重要的神經元 * Neuron Pruning * Filter Pruning * Block Pruning * Dynamic Pruning 動態找出沒有貢獻的神經元 * Adaptive Pruning * Gating Mechanism * Conditional Computation * Quantization ![image](https://hackmd.io/_uploads/Ski-4FT2kx.png) * 降低精度 儲存的權重從FP32到INT8 從INT8去推論 * 降低參數量 * Architecture Optimization 網路結構的優化 * Group Convolution ![image](https://hackmd.io/_uploads/ryzrVY63yg.png) * Pointwise Convolution(1x1 Convolution) ![image](https://hackmd.io/_uploads/BycSEFph1g.png) 降維,融合特徵 * Depthwise Separable Convolution ![image](https://hackmd.io/_uploads/rJokBF6hkx.png) * Depthwise Convolution * Pointwise Convolution * Bottleneck Block ![image](https://hackmd.io/_uploads/ByE-rF621g.png) * Dilated Convolution ![image](https://hackmd.io/_uploads/r11GHYp2ke.png) ## Lecture 8. Crafting Realities with Probabilistic Distribution ### Unsupervised Learning ![image](https://hackmd.io/_uploads/SJpuiIqT1x.png) - **無監督學習** - 目標:是讓模型學會資料的潛在分布或結構,即使沒有標籤,也能從中找出模式或生成類似的資料。 - 常見方法: - **Clustering**(K-Means):將資料分群,使同群內資料彼此相似、群與群之間差異大。 ![image](https://hackmd.io/_uploads/SJpMi8961x.png) - **Dimensionality Reduction**(PCA):將高維資料投影到低維空間,保留最多變異量以簡化資料結構。 - PCA 1st Dimension(主成分 1): - 是資料中變異量最大的方向(資料最「分散」的方向)。 - 投影在這個軸上可以保留最多資訊。 - PCA 2nd Dimension(主成分 2): - 是剩餘變異量最大的方向。 - 投影在這個方向補充資料中較小的變化。 ![image](https://hackmd.io/_uploads/rk7VjL9akl.png) --- ### Overview of Generative Models ![image](https://hackmd.io/_uploads/rkMZZPcTJg.png) - **目標**:生成新資料(如圖片或文字) - 常見架構: - Autoencoder (AE) - Variational Autoencoder (VAE) - GAN - Diffusion Models - **原理**: 1. 從簡單分布(如高斯分布)取樣 latent 變數 $(z)$ 2. 經過模型轉換成 output $(x)$ - **Latent Space** 是一個**結構化**的低維表示空間,它將高維數據壓縮成更少的維度,同時**保留數據中的關鍵變化和模式**,使得相似的數據在這個空間中靠近,而不同的數據則區分開來。 --- ### Autoencoder (AE) ![image](https://hackmd.io/_uploads/BkeTbvcayl.png) Autoencoder 將輸入壓縮成低維的潛在表示 $z$,再重建回輸出 $x'$,若重建效果好,代表$z$抓住了輸入的關鍵特徵。 ![image](https://hackmd.io/_uploads/HyDr7wcTJg.png) - **AE** - 離散:點對點的學習(AE 學到的是**固定、確定性(deterministic)** 的 latent 表示,每筆輸入對應唯一一個 latent 向量。) - 無法學習 latent space 的分布 - 單純的學習重建 - 無法生成新的資料:AE 雖然可以將某些 latent 向量丟入 decoder 產生資料,但因 latent space 沒有結構化,隨機抽樣結果不可控也難以合理生成。 - **架構**: - Encoder: $x \rightarrow z$ - Decoder: $z \rightarrow x'$ - **學習目標**: - 最小化重建誤差 $( \text{MSE}(x, x'))$ - **限制**: - Mapping 是 deterministic - 缺乏生成多樣性 - 無法涵蓋資料空間中未見過的區域 --- ### Variational Autoencoder (VAE) ![image](https://hackmd.io/_uploads/B1u8EPqTJx.png) - VAE - 連續性:增加 latent space 的 mapping - 透過 KL divergence 來學習 latent space 的分布 - 具有生成的能力 - Recall that Autoecoder consists of : - Encoder: $q_\phi(\mathbf{z}|\mathbf{x})$ - Decoder: $p_\theta(\mathbf{x}|\mathbf{z})$ - Maximize: $\mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})]$ - minimizing the reconstruction error - Minimize: $D_{\text{KL}}(q_\phi(\mathbf{z}|\mathbf{x}) \| p_\theta(\mathbf{z}))$ - pulling the approximated distribution closer to the prior - VAE loss - reconstruction loss + KL divergence - 引入 **機率模型**:$z \sim \mathcal{N}(\mu, \sigma^2)$ - 編碼器輸出 $\mu, \sigma$,用於生成 latent vector #### VAE 架構 - **Encoder**: $q_\phi(z|x) = \mathcal{N}(\mu_\phi(x), \sigma^2_\phi(x))$ - **Decoder**: $p_\theta(x|z)$ - **Prior**: $p(z) = \mathcal{N}(0, I)$ #### VAE 目標:最大化 Log-Likelihood 讓模型生成的資料分布盡可能接近真實資料分布 - Log-Likelihood 是衡量模型對觀察資料「解釋能力」的一個指標,用的是「對數後的機率值」。 - 數值更穩定 - 機率值通常很小,例如:0.00002。 - 多筆資料的 likelihood 是機率的連乘: $L(\theta) = p(x_1) \cdot p(x_2) \cdot \dots \cdot p(x_n)$ - **取對數後變成加總,更穩定**: $\log L(\theta) = \log p(x_1) + \log p(x_2) + \dots + \log p(x_n)$ - 方便計算梯度 - 訓練模型時常用 **梯度下降法**。 - 相乘的形式微分困難,對數轉加總後更容易對參數求導數。 - 數學性質好 - log 函數是單調遞增的,最大化 likelihood 和最大化 log-likelihood 等價。 - 但 log-likelihood 更容易優化與分析。 - VAE 透過最大化 ELBO,讓模型同時重建輸入資料並讓潛在分布接近先驗分布,以有效近似真實的資料分布。 - 因 $p(z|x)$ 難以計算,透過變分近似轉為 Evidence Lower Bound (ELBO):$\log p(x) \geq \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{\text{KL}}(q_\phi(z|x) \| p(z))$ - **重建項**:最大化 $\log p_\theta(x|z)$ - **KL 項**:最小化與先驗分布的差距 --- #### VAE Loss Function $\mathcal{L}_{\text{VAE}} = \underbrace{\mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)]}_{\text{Reconstruction Loss}} - \underbrace{D_{\text{KL}}(q_\phi(z|x) \| p(z))}_{\text{Regularization}}$ KL closed-form 表達式(高斯): $D_{\text{KL}} = \frac{1}{2} \sum_i \left( \mu_i^2 + \sigma_i^2 - 1 - \log \sigma_i^2 \right)$ --- #### Reparameterization Trick - 目標:允許對隨機變數 \( z \) 進行反向傳播 - 方法: $z = \mu + \sigma \cdot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)$ - 優點:將隨機性移出模型參數,允許 gradient 傳遞 --- ### AE & VAE ![image](https://hackmd.io/_uploads/rJxjmv56kx.png) --- ### CVAE (Conditional VAE) ![image](https://hackmd.io/_uploads/Hkgn4Dcpkx.png) 「有條件的 VAE」,能根據輸入的 條件變數(label 或 context) 控制生成結果。 - **目標**:條件生成(例如指定 class) - 修改方式: - Encoder: $q_\phi(z|x, c)$ - Decoder: $p_\theta(x|z, c)$ - **Loss Function**: $\mathcal{L}_{\text{CVAE}} = \mathbb{E}_{q_\phi(z|x,c)}[\log p_\theta(x|z,c)] - D_{\text{KL}}(q_\phi(z|x,c) \| p(z|c))$ --- ### β-VAE ![image](https://hackmd.io/_uploads/B1pRNv56kl.png) - 模型應該學到一個能夠將複雜資料(如圖像)**拆解成獨立語意因子(如狗、水、草地)** 的 latent 表示,這就是 disentangled representation 的目標。 - Disentangled representation(解耦表示) 是一種潛在表示方式,讓每一個維度對應到資料的一個獨立、可解釋的變因(factor of variation)。 - “我想讓這張狗照變成在雪地裡,但不改狗的品種或姿勢。” - 這種「變一項,其他不變」的能力 - 在 VAE 的損失函數中,加強對 latent 分布的約束,讓每個 latent 維度能學到更獨立的語意特徵。 - 在 Loss 中放大 KL 項: $\mathcal{L}_{\beta\text{-VAE}} = \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - \beta \cdot D_{\text{KL}}(q_\phi(z|x) \| p(z))$ - β > 1 時鼓勵 **disentangled representation**(獨立變因) --- ### Tilted VAE ![image](https://hackmd.io/_uploads/SJDqBv5pkg.png) - 「重新調整機率分布的形狀」,讓潛在空間的密度不再集中在中心,而是平均地分佈在球殼(spherical shell)上。 - 「改變 latent space 分布密度的結構」,讓模型能更有效使用潛在空間並產生更好的生成結果。 - 問題:高維空間下,高斯分布密度集中於殼層,表示能力不足 - 解法: - 調整 latent space 的密度,使其分布在球殼而非中心 - 增加高密度區域的體積,提高生成樣本多樣性 ![image](https://hackmd.io/_uploads/S1V2SD5a1e.png) --- ### VAE 缺點 - 重建圖像模糊: - Pixel-wise loss 無法捕捉高頻細節 - 高斯先驗導致過於平滑的 latent 空間 ## Lecture 9. GAN- Image Generation Through Competition ![image](https://hackmd.io/_uploads/Hyp3DD5a1l.png) - Generator (G): 生成器 - Discriminator (D): 判別器 ### GAN Training Process ![image](https://hackmd.io/_uploads/rJnRwv96ye.png) - Step 1: Train D - $arg \max_D D(x)$: 真實資料的機率 - $arg \min_D D(G(z))$: 生成資料的機率 - $p_{\text{data}}(x)$: 真實資料的分布 - $p_z(z)$: 隨機噪音的分布 - Maximize: $\mathbb{E}_{x \sim p_{\text{data}}(x)}[\log D(x)] + \mathbb{E}_{z \sim p_z(z)}[\log(1 - D(G(z)))]$ - 判別器的目標是讓真實資料的機率最大,生成資料的機率最小 - Step 2: Train G - Minimize: $\mathbb{E}_{z \sim p_z(z)}[\log(1 - D(G(z)))]$ - 改良後的目標函數 - Maximize: $\mathbb{E}_{z \sim p_z(z)}[\log D(G(z))]$ - 生成器的目標是讓判別器無法分辨生成資料和真實資料 - step 3: Adversarial Process - G 和 D 在訓練過程中輪流對抗。 - → G 試著生成更真實的資料,讓 D 必須變得更聰明來分辨真偽。 - $min_G max_D V(D, G) = \mathbb{E}_{x \sim p_{\text{data}}(x)}[\log D(x)] + \mathbb{E}_{z \sim p_z(z)}[\log(1 - D(G(z)))]$ ### DL divergence - **KL Divergence** 測量的是用 Q 來近似 P 會失去多少資訊,具方向性、常用於變分推論(如 VAE)。 - $D_{\text{KL}}(P \| Q) = \sum_{x \in X} P(x) \log \frac{P(x)}{Q(x)}$ - $D_{\text{KL}}(P \| Q) \neq D_{\text{KL}}(Q \| P)$ - 不具有對稱性 - $D_{\text{KL}}(P \| Q) \geq 0$ - 非負性 - $D_{\text{KL}}(P \| Q) = 0 \Leftrightarrow P = Q$ - 零值性 ### JS divergence - **JS Divergence** 是對稱的版本,適合衡量兩個分布的相似度,但在 GAN 中會有梯度消失問題。 - $D_{\text{JS}}(P \| Q) = \frac{1}{2} D_{\text{KL}}(P \| M) + \frac{1}{2} D_{\text{KL}}(Q \| M)$ - $M = \frac{1}{2}(P + Q)$ - $D_{\text{JS}}(P \| Q) = 0 \Leftrightarrow P = Q$ - $D_{\text{JS}}(P \| Q) \leq \log 2$ - 有界性 - $D_{\text{JS}}(P \| Q) = 0 \Leftrightarrow P = Q$ - $D_{\text{JS}}(P \| Q) = \log 2$ 代表 P 和 Q 完全沒有重疊(如互斥事件) - $D_{\text{JS}}(P \| Q) = \log 2$ 代表兩個分布完全不同 - 在 GAN 訓練早期,若 Generator 產出的分布與真實資料幾乎沒有重疊,會導致 JS divergence 的梯度接近 0(非無限大),這會讓 Generator 學不到東西 → 這就是所謂的「vanishing gradient problem」。 - 因此,GAN 不直接最小化 JS divergence,而是使用替代的損失(如 non-saturating loss 或 WGAN 使用 Wasserstein 距離)。 ### 問題 ⚠ GAN 中的重要觀察: 在 GAN 訓練初期,若生成器 $G(z)$ 的輸出分布與真實資料分布 $p_{data}$幾乎沒有重疊: - JS divergence 幾乎達到上限($log2$) - 這時 JS divergence 對 G 的梯度幾乎為 0 - ⛔ 這會導致 Generator 無法學習(Vanishing Gradient Problem) ✅ 解法: - 原始 GAN 改用 non-saturating loss - **Non-saturating loss** 是 GAN 中為了避免 Generator 的梯度消失而設計的替代損失函數,透過最大化 $\log D(G(z))$ 提供更穩定的學習訊號。 - 更進一步的改進 → WGAN 改用 Wasserstein Distance,解決 JS divergence 的梯度問題 ### WGAN - WGAN: Wasserstein GAN - 設計一個更穩定的損失函數 - 用 Wasserstein 距離來取代 JS divergence - 因為 JS divergence 在某些情況下會有梯度消失的問題 - 如果分布完全不重疊,JS divergence 的梯度會接近 0 - 這樣會導致 Generator 學不到東西 - Wasserstein 距離 - $W(P, Q) = \inf_{\gamma \in \Pi(P, Q)} \mathbb{E}_{(x, y) \sim \gamma}[||x - y||]$ - $\Pi(P, Q)$: 所有聯合分布為 P 和 Q 的集合 - $\inf$: infimum,即所有可能值中的最小上界(不一定能被實際達到)![image](https://hackmd.io/_uploads/SkAuOvqpJx.png) - 找到一個最佳的對應方式,使得兩個分布之間的距離最小 - Wasserstein 距離也被稱為 Earth Mover’s Distance,代表把一堆「土」從一個分布移動到另一個分布所需的最小「成本」。 ### Conclusion - 希望判別器(Discriminator, D)能夠分辨真實資料與生成資料。 - 希望生成器(Generator, G)能夠生成越來越真實的資料。 - GAN 在訓練過程中可能會面臨以下挑戰: - **Training Instability**:訓練過程不穩定,難以收斂 - **Mode Collapse**:生成器只學會產生少數樣本模式,缺乏多樣性 - **Lack of Theoretical Guarantees**:缺乏完整的收斂理論基礎 - GAN 是一個兩個模型(G 與 D)彼此對抗的訓練過程,最終目標是達成一種納許平衡(Nash Equilibrium)。 - **WGAN** 使用 **Wasserstein 距離** 取代 JS divergence,有效解決 JS divergence 在分布不重疊時產生的 **梯度消失問題**,使訓練更穩定。 ## Lecture 11. Transfomer: Sequential Model ### Sequence-to-Sequence with Attention - **序列的前後關係具有重要意義**。 - **輸入序列與輸出序列的長度可以不同**。 - **架構說明**: - **Encoder**:將輸入序列(例如英文句子)編碼成一個**上下文向量(Context Vector)**,提取其特徵。 - **Hidden Representation**:將上下文向量轉換為輸出所需的**隱藏特徵表示**(例如抽象的語義與文法結構)。 - **Decoder**:根據上下文向量和隱藏特徵表示,逐步產生輸出序列(例如中文翻譯)。 ### Sequential Model vs Generative Model #### 1. 核心概念 - **Generative Model**: - 目標是**模擬資料的真實分佈**(Learning Data Distribution)。 - 從學到的分佈中**抽樣**,**生成新的樣本**。 - 著重於「資料的可能性」以及「創造全新資料」的能力。 - **Sequential Model**: - 目標是**建模資料的順序性結構**(Modeling Temporal/Sequential Dependencies)。 - 理解序列中**前後元素之間的關聯與演變規律**。 - 著重於「元素間的連貫性」與「時間上的依賴關係」。 - **Example**: - 差異在於: - **Generative Model**:試圖「**生成**」符合某個分佈的資料。 - **Sequential Model**:試圖「**預測**」序列中下一個正確的元素。 - 具體例子: - **GAN**:直接生成一句自然的句子,例如 "The cat sat on the mat." - **Sequential Model**:在混亂的輸入中推理正確的順序,例如從 "The mat cat sat the on." 預測正確的排列。 --- #### 2. 對比整理 | | Sequential Model | Generative Model | | :-- | :-- | :-- | | **核心目標** | 捕捉資料中元素之間的順序依賴 | 模擬資料的生成分佈 | | **關注重點** | 時序結構(Temporal/Sequential Structure) | 整體資料分佈(Data Distribution) | | **輸出特性** | 根據過去的資訊預測或理解未來元素 | 生成與訓練資料類似的新資料 | | **典型範例** | RNN, LSTM, GRU, Transformer (for sequential tasks) | GAN, VAE, Diffusion Models, Autoregressive Models (like GPT) | | **交集** | 可用於建立序列型生成模型(如 GPT、WaveNet) | 在序列資料上,許多生成式模型也採用 sequential 架構 | --- #### 3. 簡單總結 > **Generative Model 是在模擬「資料的分布」,Sequential Model 是在建模「資料的順序依賴」。** > 在處理序列資料時,兩者常常結合使用,例如:以自回歸(Autoregressive)的方式逐步生成新資料。 ### Introduction to Sequence-to-Sequence Model #### 1. The Basic Sequence Model: RNN - **RNN**: - **Recurrent Neural Network**:循環神經網路。 - **優點**: - 能夠處理**變長的序列資料**。 - **缺點**: - **記憶力有限**,難以捕捉**長期依賴關係**(Long-term Dependencies)。 - 隨著時間步(time steps)增加,容易發生**梯度消失或梯度爆炸**的問題,導致訓練不穩定。 - **計算效率低**,不易並行化處理。 - 因為每個時間步的計算結果**依賴於前一個時間步**,無法同時計算。 #### 2. Improvement of RNN: LSTM - **LSTM**: - **Long Short-Term Memory**:長短期記憶網路。 - 相較於 RNN,LSTM 能夠**更有效地篩選與保留重要資訊**。 - **結構**: - **Cell State**:負責**儲存長期記憶**。 - **Input Gate**:控制**新資訊的寫入量**。 - **Forget Gate**:控制**舊資訊的遺忘比例**。 - **Output Gate**:控制**輸出的資訊內容**。 - **優點**: - 能夠**捕捉長期依賴關係**,緩解梯度問題。 - 相較於傳統 RNN,**計算更穩定**,部分步驟可實現**並行加速**。 - **缺點**: - 結構較為複雜,導致**計算量增加**。 - **訓練時間較長**,資源需求較高。 #### 3. 兩者的問題 - **結構差異**: - 雖然 RNN 和 LSTM 架構大體相似,但 LSTM 在每個時間步引入了更多的**門控機制**,以更有效地控制資訊流動。 - **共同問題**: - **長期依賴問題**依然存在: - "The cat jumped onto the branch and saw the bird's colorful feathers." - 在非常長的序列中,早期重要資訊(如 "cat")容易在多次狀態更新後逐漸消失,導致無法有效連結遠距離的元素(如 "feathers")。 - **難以並行處理**: - 由於序列資料需要**逐步處理**,每個時間步依賴前一步結果,因此無法有效並行,特別在長序列下效率低下。 ### Transformer - **結構特點**: - 保留**Encoder–Decoder**架構,但**不再使用 RNN 或 LSTM**。 - 改用: - **自注意力機制(Self-Attention Mechanism)** - **多頭注意力(Multi-Head Attention)** - **關鍵優勢**: - **無需循環結構**,可以**同時處理整個序列**(並行運算)。 - 大幅提升計算效率。→平行化處理。 - 更容易捕捉長距離的依賴關係(Long-Range Dependencies)。→不會忘記早期的資訊。 - **運作方式**: - **Encoder**:處理輸入序列,將其轉換成**上下文表示(Contextual Representations)**。 - **Decoder**:在每個步驟中,同時關注(Attend)**Encoder的輸出**與**先前已生成的輸出(Past Tokens)**,逐步產生新的序列。 #### Key Components of Transformer Architecture ##### 1 Attention Mechanism - **功能**:根據輸入序列中各元素的關係,動態分配注意力權重。 - **簡單例子**: - 當翻譯句子 "The cat sat on the mat",在翻譯 "sat" 時,模型會特別關注 "cat",因為動作與主詞有關。 - **補充**: - Attention 可以讓模型即時選擇重要資訊,而不是平均處理所有詞。 - **self-attention**: - 在同一序列內部計算注意力權重,強調詞與詞之間的關聯性。 - Self-Attention 是將當前位置的 Query 向量與所有位置的 Key 向量相乘以計算注意力權重,並利用這些權重加權該位置的 Value 資訊,從而表示該 Query 與其他位置的關聯性。 - **計算方式**: - **Query**、**Key**、**Value**: - Query:當前詞的表示。 - Key:其他詞的表示。 - Value:其他詞的實際內容。 - **計算公式**: - **Attention(Q, K, V) = $softmax(\frac{QK^T}{\sqrt{d_k}})V$** - Q:Query 向量。 - K:Key 向量。 - V:Value 向量。 - d_k:Key 向量的維度,用於縮放。 - **計算步驟**: 1. 計算 Query 和 Key 的相似度(通常用 dot product)來獲得注意力權重。 2. 將注意力權重應用於 Value,得到加權平均的輸出。 --- ##### 2 Add & Layer Normalization - **功能**:加速訓練並穩定模型,防止梯度爆炸或消失。 - **簡單例子**: - 每個子層(例如 Attention 或 Feedforward)執行完後,會把輸出加回原輸入(Add Residual),然後做 Layer Normalization。 - **補充**: - **Add**:保留原始訊息。 - **Layer Norm**:讓每層的輸出分布更穩定,加快收斂速度。 --- ##### 3. Feedforward Network (FFN) - **功能**: - 在每個位置(token)上**獨立應用的小型神經網路**,用來提升模型的表達能力。 - 對每個字(token)施加**位置內(position-wise)變換**,引入非線性,增加模型的擬合與理解能力。 - **簡單例子**: - 對每個字(token)單獨套用一個兩層的 MLP(例如:先升維、再降維),以更精細地描述該 token 所蘊含的語意資訊。 - **補充說明**: - **Shared Weights**:所有位置的 FFN 使用**相同的參數**,但**彼此獨立運算**,不會跨位置混合資訊。 - **作用目的**: - **引入非線性變換**:Attention 機制本身偏線性,缺少非線性會使模型無法學習如強調(emphasis)、否定(negation)、情感轉折(sentiment shift)等抽象概念。 - **賦予每個 token 獨立處理能力**:Attention 讓 token 互相學習,FFN 則讓每個 token 能夠**自行加工自己的表達**,猶如給每個 token 一個「思考過程」。 - **加強層與層之間的轉換能力**:若缺少 FFN,每層模型的計算將過於類似,難以隨深度推進進行更豐富的特徵變換,削弱了模型的表達深度。 - **小提醒**: - FFN 是 Transformer 中的重要組件,去除後會大幅限制模型的表達能力和理解力。 --- ##### 4. Cross-Attention - **功能**: - 在 Decoder 端,讓每個輸出位置能夠**關注 Encoder 的輸出資訊**。 - 有助於將**輸入序列的重要資訊**正確地整合到輸出中。 - 是**序列到序列任務(Sequence-to-Sequence Tasks)**(如翻譯)的關鍵機制。 - **簡單例子**: - 當 Decoder 要產生 "牠"(it)時,會查詢 Encoder 輸出的資訊,例如 "cat",以決定 "牠"實際指的是「貓」。 - **補充說明**: - **目的(Purpose)**: - 使 Decoder 能夠直接「查看」Encoder 的輸出,以提取必要的上下文資訊。 - 協助對齊(align)並融合(incorporate)輸入序列的內容,提升生成品質。 - **運作機制(Mechanism)**: - **Query** 來自 Decoder 的當前狀態。 - **Key** 和 **Value** 來自 Encoder 的輸出。 - Decoder 將自己的 Query 與 Encoder 的 Key 進行比對,計算出**注意力權重(Attention Weights)**。 - 這些權重決定**從 Encoder 的每個位置取用多少 Value 的資訊**。 - 最後輸出為**加權和**(Weighted Sum of Values),並傳遞到 Decoder 的下一層。 - **學習行為**: - Decoder 透過 Cross-Attention,學習在每個生成步驟中,**應該聚焦 Encoder 輸入的哪個部分**。 - 最終形成的輸出向量,捕捉了**與原始輸入序列對齊的語意資訊(Context-Aware Representation)**。 --- ##### 5 Masked Self-Attention - **功能**:在 Decoder 裡,避免「偷看」未來的詞,保證自回歸性(Autoregressive)。 - **簡單例子**: - 產生第三個字時(例如 "sat"),只能看到前兩個字 "The cat",不能看到後面的字。 - **補充**: - 透過「遮罩」(Mask)將未來資訊遮掉,確保訓練與推論一致。 --- ##### 6 From Representation to Prediction - **功能**:將 Transformer 輸出的向量轉成實際的預測結果。 - **簡單例子**: - 將最後的 hidden state 通過線性層(Linear Layer),映射到字典大小(Vocabulary Size),做 softmax 預測下一個單字。 - **補充**: - 這是最後一層,將高維表示(Representation)轉為具體輸出(Prediction)。 ---