<p>?</p><p/><h1>人工智能之核心技術(shù) 深度學(xué)習(xí)</h1><p/><p>第二章 神經(jīng)網(wǎng)絡(luò)訓(xùn)練與優(yōu)化</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-18b4b7fc1fba2b32.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p>
<h1>整體訓(xùn)練過程概覽</h1><p>神經(jīng)網(wǎng)絡(luò)的訓(xùn)練是一個<strong>迭代優(yōu)化過程</strong>,其核心是通過<strong>反向傳播</strong>計算梯度,并利用<strong>優(yōu)化算法</strong>更新參數(shù),以最小化<strong>損失函數(shù)</strong>。同時,為防止過擬合和數(shù)值不穩(wěn)定,需引入<strong>正則化</strong>與<strong>穩(wěn)定技術(shù)</strong>。</p><p>完整的訓(xùn)練流程如下:</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-0cace929f230e2df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p><strong>訓(xùn)練循環(huán)偽代碼</strong></p><pre>for?epoch?in?range(max_epochs):????for?batch?in?dataloader:????????#?1.?前向傳播????????pred?=?model(batch.x)????????#?2.?計算損失????????loss?=?loss_fn(pred,?batch.y)????????#?3.?清零梯度????????optimizer.zero_grad()????????#?4.?反向傳播????????loss.backward()????????#?5.?梯度裁剪(可選)????????clip_gradients(model)????????#?6.?參數(shù)更新????????optimizer.step()????#?7.?調(diào)整學(xué)習(xí)率????scheduler.step()????#?8.?驗證?&?早停????val_loss?=?evaluate(model,?val_loader)????if?early_stop(val_loss):?break</pre><blockquote><p>??<strong>關(guān)鍵思想</strong>:</p><ul><li><p>??<strong>前向傳播</strong>決定“當(dāng)前做得多差”</p></li><li><p>??<strong>反向傳播 + 優(yōu)化器</strong>決定“如何改進”</p></li><li><p>??<strong>正則化 + 調(diào)度 + 早停</strong>確?!皩W(xué)得穩(wěn)、泛化好”</p></li></ul></blockquote>
<p><strong>模型初始化(Initialization)</strong></p><p><strong>為什么重要?</strong>
糟糕的初始化會導(dǎo)致梯度消失/爆炸,使訓(xùn)練無法開始。</p><p><strong>常用方法:</strong></p><p/><p/><blockquote><p>???<strong>實踐建議</strong>:現(xiàn)代框架(PyTorch/TensorFlow)默認初始化已較合理,但自定義層時務(wù)必注意。</p></blockquote>
<p><strong>一、前向傳播(Forward Pass)</strong></p><ul><li><p>? 輸入數(shù)據(jù)通過網(wǎng)絡(luò)逐層計算:</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-2b5b6f3201b4fb85.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p></li><li><p>? 最終輸出用于計算損失。</p></li><li><p>??<strong>無參數(shù)更新</strong>,僅用于評估當(dāng)前模型性能。</p></li></ul>
<p><strong>二、損失函數(shù)(Loss Function)</strong></p><p>損失函數(shù)衡量模型預(yù)測值與真實值之間的差距,是訓(xùn)練的“指南針”。</p><p><strong>2.1 分類任務(wù)</strong></p><p><strong>(1)交叉熵損失(Cross-Entropy Loss)</strong></p><ul><li><p>??<strong>適用</strong>:多分類(Softmax + CrossEntropy)或二分類(Sigmoid + BCE)</p></li><li><p>??<strong>公式(二分類)</strong>:</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-2d99773e733a5589.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p></li><li><p>??<strong>優(yōu)點</strong>:梯度平滑、對錯誤預(yù)測懲罰大</p></li><li><p>??<strong>PyTorch 實現(xiàn)</strong>:<strong>nn.BCELoss()</strong>(需先 Sigmoid)、<strong>nn.CrossEntropyLoss()</strong>(內(nèi)部含 Softmax)</p></li></ul><p><strong>(2)Focal Loss(解決類別不平衡)</strong></p><ul><li><p>??<strong>動機</strong>:當(dāng)正負樣本極度不均衡時(如目標檢測中背景 vs 目標),標準交叉熵會讓模型“偷懶”只學(xué)多數(shù)類。</p></li><li><p>??<strong>公式</strong>:</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-4e8906ce4795981c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p></li><ul><li><p>??:正確類別的預(yù)測概率</p></li><li><p>??:聚焦參數(shù)(越大,越忽略易分樣本)</p></li><li><p>??:類別權(quán)重</p></li></ul><li><p>??<strong>效果</strong>:讓模型更關(guān)注“難分樣本”</p></li></ul><blockquote><p>??<strong>選擇原則</strong>:</p><ul><li><p>? 均衡數(shù)據(jù) → 交叉熵</p></li><li><p>? 極度不平衡(如醫(yī)學(xué)圖像、目標檢測)→ Focal Loss</p></li></ul></blockquote>
<p><strong>2.2 回歸任務(wù)</strong></p><p/><p/><pre>分類是否回歸少多任務(wù)類型類別是否平衡?交叉熵Focal?Loss數(shù)據(jù)是否有異常值?MSEMAE?或?Huber</pre>
<p><strong>三、優(yōu)化算法</strong></p><p>目標:通過調(diào)整參數(shù)??最小化損失?</p><p><strong>3.1 梯度下降家族</strong></p><p/><p/><p><strong>3.2 自適應(yīng)優(yōu)化器(自動調(diào)學(xué)習(xí)率)</strong></p><p/><p/><blockquote><p>???<strong>實踐建議</strong>:</p><ul><li><p>? 默認用?<strong>AdamW</strong>(比 Adam 更穩(wěn)定)</p></li><li><p>? 學(xué)習(xí)率初始值:AdamW 常用?<strong>1e-3</strong>?~?<strong>5e-4</strong></p></li></ul></blockquote><p><strong>3.3 學(xué)習(xí)率調(diào)度(Learning Rate Scheduling)</strong></p><p>固定學(xué)習(xí)率易陷入局部最優(yōu)或震蕩。動態(tài)調(diào)整更高效:</p><p/><p/><pre>#?PyTorch?示例:余弦退火scheduler?=?torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,?T_max=100)</pre>
<p><strong>四、反向傳播算法(Backpropagation)</strong></p><p><strong>4.1 核心原理:鏈式法則</strong></p><p>神經(jīng)網(wǎng)絡(luò)是一個復(fù)合函數(shù):</p><p/><p>求梯度??需層層回傳:</p><p/><blockquote><p>???<strong>關(guān)鍵</strong>:從輸出向輸入逐層計算梯度,避免重復(fù)計算。</p></blockquote><p><strong>4.2 梯度問題與解決方案</strong></p><p/><p/><p><strong>權(quán)重初始化方法</strong></p><ul><li><p>??<strong>Xavier 初始化</strong>:適用于 Sigmoid/Tanh
</p></li><li><p>??<strong>He 初始化</strong>:適用于 ReLU
</p></li></ul>
<p><strong>五、正則化技術(shù)(防止過擬合)</strong></p><p><strong>5.1 參數(shù)正則化</strong></p><p/><p/><blockquote><p>?? 注意:PyTorch 中?<strong>weight_decay</strong>?參數(shù)實現(xiàn)的是?<strong>L2 正則化</strong></p></blockquote><p><strong>5.2 隨機丟棄技術(shù)</strong></p><p/><p/><pre>#?Dropout?示例nn.Sequential(????nn.Linear(128,?64),????nn.ReLU(),????nn.Dropout(0.5),???#?50%?神經(jīng)元隨機失活????nn.Linear(64,?10))</pre><p><strong>5.3 Batch Normalization(BN)</strong></p><p><strong>原理</strong>:對每個 mini-batch 的激活值做標準化:</p><p/><ul><li><p>??:batch 均值與方差</p></li><li><p>??:可學(xué)習(xí)的縮放與偏移參數(shù)</p></li></ul><p><strong>作用</strong>:</p><ul><li><p>? 緩解內(nèi)部協(xié)變量偏移(Internal Covariate Shift)</p></li><li><p>? 允許更高學(xué)習(xí)率</p></li><li><p>? 有一定正則化效果(可減少 Dropout 使用)</p></li></ul><blockquote><p>???<strong>LayerNorm</strong>:對單個樣本的所有特征做歸一化,適用于 RNN/Transformer</p></blockquote><p><strong>5.4 早停(Early Stopping)</strong></p><ul><li><p>? 監(jiān)控驗證集損失</p></li><li><p>? 當(dāng)驗證損失連續(xù) N 輪不再下降,提前終止訓(xùn)練</p></li><li><p>? 防止過擬合 + 節(jié)省計算資源</p></li></ul>
<p><strong>六、配套代碼實現(xiàn)(完整訓(xùn)練流程)</strong></p><pre>import?torchimport?torch.nn?as?nnimport?torch.optim?as?optimfrom?torch.optim.lr_scheduler?import?CosineAnnealingLR#?1.?模型定義(帶?Dropout?和?BN)class?Net(nn.Module):????def?init(self,?input_dim,?num_classes):????????super().init()????????self.fc1?=?nn.Linear(input_dim,?128)????????self.bn1?=?nn.BatchNorm1d(128)????????self.fc2?=?nn.Linear(128,?64)????????self.dropout?=?nn.Dropout(0.5)????????self.fc3?=?nn.Linear(64,?num_classes)????def?forward(self,?x):????????x?=?torch.relu(self.bn1(self.fc1(x)))????????x?=?self.dropout(torch.relu(self.fc2(x)))????????x?=?self.fc3(x)????????return?x#?2.?數(shù)據(jù)(模擬)X?=?torch.randn(1000,?10)y?=?torch.randint(0,?2,?(1000,))#?3.?設(shè)置model?=?Net(input_dim=10,?num_classes=2)criterion?=?nn.CrossEntropyLoss()optimizer?=?optim.AdamW(model.parameters(),?lr=1e-3,?weight_decay=1e-4)scheduler?=?CosineAnnealingLR(optimizer,?T_max=50)#?4.?訓(xùn)練循環(huán)(含早停)best_val_loss?=?float('inf')patience?=?10trigger_times?=?0for?epoch?in?range(100):????model.train()????optimizer.zero_grad()????pred?=?model(X)????loss?=?criterion(pred,?y)????loss.backward()????????#?梯度裁剪(防爆炸)????torch.nn.utils.clip_grad_norm_(model.parameters(),?max_norm=1.0)????????optimizer.step()????scheduler.step()????#?模擬驗證(此處用訓(xùn)練損失代替)????val_loss?=?loss.item()????if?val_loss?<?best_val_loss:????????best_val_loss?=?val_loss????????trigger_times?=?0????else:????????trigger_times?+=?1????????if?trigger_times?>=?patience:????????????print(f"Early?stopping?at?epoch?{epoch}")????????????breakprint("Training?finished.")</pre>
<p><strong>七、總結(jié)圖譜</strong></p><pre>訓(xùn)練目標損失函數(shù)優(yōu)化算法反向傳播正則化分類:?CrossEntropy?/?Focal回歸:?MSE?/?MAE?/?HuberSGD?家族自適應(yīng):?AdamW學(xué)習(xí)率調(diào)度鏈式法則梯度穩(wěn)定:?初始化?+?BNL1/L2DropoutEarly?StoppingBatchNorm</pre><blockquote><p>??<strong>黃金組合推薦</strong>:</p><ul><li><p>? 優(yōu)化器:<strong>AdamW</strong></p></li><li><p>? 學(xué)習(xí)率:<strong>余弦退火 + warmup</strong></p></li><li><p>? 正則化:<strong>Dropout + Weight Decay + Early Stopping</strong></p></li><li><p>? 歸一化:<strong>BatchNorm(CNN) / LayerNorm(Transformer)</strong></p></li></ul></blockquote>
<h1>資料關(guān)注</h1><p>公眾號:咚咚王
gitee:https://gitee.com/wy18585051844/ai_learning</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-11dcc9dc028e97c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p>《Python編程:從入門到實踐》
《利用Python進行數(shù)據(jù)分析》
《算法導(dǎo)論中文第三版》
《概率論與數(shù)理統(tǒng)計(第四版) (盛驟) 》
《程序員的數(shù)學(xué)》
《線性代數(shù)應(yīng)該這樣學(xué)第3版》
《微積分和數(shù)學(xué)分析引論》
《(西瓜書)周志華-機器學(xué)習(xí)》
《TensorFlow機器學(xué)習(xí)實戰(zhàn)指南》
《Sklearn與TensorFlow機器學(xué)習(xí)實用指南》
《模式識別(第四版)》
《深度學(xué)習(xí) deep learning》伊恩·古德費洛著 花書
《Python深度學(xué)習(xí)第二版(中文版)【純文本】 (登封大數(shù)據(jù) (Francois Choliet)) (Z-Library)》
《深入淺出神經(jīng)網(wǎng)絡(luò)與深度學(xué)習(xí)+(邁克爾·尼爾森(Michael+Nielsen)》
《自然語言處理綜論 第2版》
《Natural-Language-Processing-with-PyTorch》
《計算機視覺-算法與應(yīng)用(中文版)》
《Learning OpenCV 4》
《AIGC:智能創(chuàng)作時代》杜雨+&+張孜銘
《AIGC原理與實踐:零基礎(chǔ)學(xué)大語言模型、擴散模型和多模態(tài)模型》
《從零構(gòu)建大語言模型(中文版)》
《實戰(zhàn)AI大模型》
《AI 3.0》</p><p>?</p><p/><p/><p/><p/><p/>