antony@notes:~/learning-notes$ cat "生成式-AI-課程.md"
生成式 AI 課程
生成式 AI 課程
環境準備
Hardware
- os: windows server 2025
- cpu: 8 cores
- MEM: 32 G
- disk: 70 G
安裝軟體
- Python 3.8 以上的版本 (安裝前記得勾加入 PATH) 自行挑選:https://www.python.org/downloads/ 特定版本:https://www.python.org/downloads/release/python-3119/
- Cursor 或 Visual Studio Code Cursor:https://www.cursor.com/ (同時註冊帳號) https://cursor.directory/ VSCode:https://code.visualstudio.com/download
- Ollama https://ollama.com/download
- Docker https://www.docker.com/
以上軟體都安裝好後,
先打開 powershell 執行以下命令安裝 deepseek-r1:1.5b
ollama run deepseek-r1:1.5b執行結果 :
pulling manifest
pulling aabd4debf0c8... 100% ▕███████████████████████████████████████████████████████▏ 1.1 GB
pulling 369ca498f347... 100% ▕███████████████████████████████████████████████████████▏ 387 B
pulling 6e4c38e1172f... 100% ▕███████████████████████████████████████████████████████▏ 1.1 KB
pulling f4d24e9138dd... 100% ▕███████████████████████████████████████████████████████▏ 148 B
pulling a85fe2a2e58e... 100% ▕███████████████████████████████████████████████████████▏ 487 B
verifying sha256 digest
writing manifest
success
>>> Send a message (/? for help)在 docker desktop 執行以下指令
docker run -d -p 3000:8080 \
--add-host=host.docker.internal:host-gateway \
-v openwebui:/app/backend/data \
--name open-webui \
--restart always \
ghcr.io/open-webui/open-webui:main確認 open-web-ui 運作正常
docker ps執行結果 :
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8350f31409b2 ghcr.io/open-webui/open-webui:main "bash start.sh" About a minute ago Up About a minute (health: starting) 0.0.0.0:3000->8080/tcp open-webui打開瀏覽器,輸入 : http://localhost:3000 連到 UI

實作 : 利用 PyTorch 建立一個 Word2Vec 詞嵌入模型
$ mkdir llm0207打開 cursor 並進入 llm0207 專案,產生 requirements.txt 檔案 (檔名要一模一樣)
pandas
numpy
matplotlib
seaborn
scikit-learn
transformers
torch
torchvision按 Ctrl + s 存檔,再按 Ctrl + shift + p
> Python: Create Environment
> 選擇 Venv type
> Use Existing
> 選 requirements.txt 按 ok 就會安裝或是可以直接執行以下指令安裝
pip install -r requirements.txt
用指令檢查有沒有安裝成功
pip list執行結果 :
Package Version
------------------ ------------
backports.tarfile 1.2.0
build 1.2.2.post1
CacheControl 0.14.2
certifi 2025.1.31
charset-normalizer 3.4.1
cleo 2.1.0
colorama 0.4.6
contourpy 1.3.1
crashtest 0.4.1
cycler 0.12.1
distlib 0.3.9
dulwich 0.22.7
fastjsonschema 2.21.1
filelock 3.17.0
fonttools 4.55.8
fsspec 2025.2.0
huggingface-hub 0.28.1
idna 3.10
importlib_metadata 8.6.1
installer 0.7.0
jaraco.classes 3.4.0
jaraco.context 6.0.1
jaraco.functools 4.1.0
Jinja2 3.1.5
joblib 1.4.2
keyring 25.6.0
kiwisolver 1.4.8
MarkupSafe 3.0.2
matplotlib 3.10.0
more-itertools 10.6.0
mpmath 1.3.0
msgpack 1.1.0
networkx 3.4.2
numpy 2.2.2
packaging 24.2
pandas 2.2.3
pillow 11.1.0
pip 25.0
pkginfo 1.12.0
platformdirs 4.3.6
poetry 2.0.1
poetry-core 2.0.1
pyparsing 3.2.1
pyproject_hooks 1.2.0
python-dateutil 2.9.0.post0
pytz 2025.1
pywin32-ctypes 0.2.3
PyYAML 6.0.2
RapidFuzz 3.12.1
regex 2024.11.6
requests 2.32.3
requests-toolbelt 1.0.0
safetensors 0.5.2
scikit-learn 1.6.1
scipy 1.15.1
seaborn 0.13.2
setuptools 65.5.0
shellingham 1.5.4
six 1.17.0
sympy 1.13.1
threadpoolctl 3.5.0
tokenizers 0.21.0
tomlkit 0.13.2
torch 2.6.0
torchvision 0.21.0
tqdm 4.67.1
transformers 4.48.2
trove-classifiers 2025.1.15.22
typing_extensions 4.12.2
tzdata 2025.1
urllib3 2.3.0
virtualenv 20.29.1
zipp 3.21.0產生檔案 : 01_word2vec.py
01_word2vec.py
"""
Word2Vec 實作模組
使用 Skip-gram 模型實作詞向量訓練。
此模組提供基本的詞嵌入訓練功能,並包含相似詞查詢和視覺化功能。
主要功能:
1. 文本預處理
2. Skip-gram 模型訓練
3. 詞向量相似度計算
4. 詞向量視覺化
"""
# 匯入需要的套件
import torch # PyTorch 深度學習框架
import torch.nn as nn # 神經網路模組
import torch.optim as optim # 優化器模組
import numpy as np # 數值計算套件
from collections import Counter # 用於計算詞頻
import matplotlib.pyplot as plt # 繪圖套件
from sklearn.metrics.pairwise import cosine_similarity # 餘弦相似度計算
from sklearn.decomposition import PCA # 主成分分析
from typing import List, Tuple, Dict # 型別提示
# 設定 matplotlib 中文字型
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei'] # 設定Windows預設中文字型
plt.rcParams['axes.unicode_minus'] = False # 修正負號顯示問題
# 檢查系統可用的中文字型
def check_chinese_fonts():
fonts = [f.name for f in fm.fontManager.ttflist] # 取得所有可用字型
print("系統可用的中文字型:")
chinese_fonts = [f for f in fonts if ('Microsoft' in f) or ('微軟' in f) or ('Arial' in f)]
for f in chinese_fonts:
print(f)
# 定義模型訓練的超參數
WINDOW_SIZE: int = 2 # 上下文窗口大小
EMBEDDING_DIM: int = 10 # 詞向量維度
EPOCHS: int = 200 # 訓練回合數
LEARNING_RATE: float = 0.005 # 學習率
class SkipGram(nn.Module):
"""
Skip-gram 模型類別
用於學習詞向量的神經網路模型,包含一個嵌入層和一個輸出層。
"""
def __init__(self, vocab_size: int, embedding_dim: int) -> None:
"""
初始化模型架構
參數:
vocab_size: 詞彙表大小(有多少不同的詞)
embedding_dim: 詞向量的維度
"""
super(SkipGram, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim) # 詞嵌入層
self.output_layer = nn.Linear(embedding_dim, vocab_size) # 全連接輸出層
self.log_softmax = nn.LogSoftmax(dim=-1) # 對數 Softmax 激活函數
def forward(self, target: torch.Tensor) -> torch.Tensor:
"""
前向傳播函式
參數:
target: 目標詞的索引張量
回傳:
模型預測的機率分布(取對數後)
"""
embed = self.embeddings(target) # 將輸入轉換為詞向量
output = self.output_layer(embed) # 通過輸出層
return self.log_softmax(output) # 計算對數機率
def preprocess_text(corpus: str) -> Tuple[List[str], Dict[str, int], Dict[int, str]]:
"""
預處理文本資料
參數:
corpus (str): 原始文本
回傳:
Tuple[List[str], Dict[str, int], Dict[int, str]]:
- 處理後的單詞列表
- 單詞到索引的映射
- 索引到單詞的映射
"""
words = corpus.lower().replace('.', '').split()
word_counts = Counter(words)
vocab = list(word_counts.keys())
word_to_ix = {word: i for i, word in enumerate(vocab)}
ix_to_word = {i: word for word, i in word_to_ix.items()}
return words, word_to_ix, ix_to_word
def generate_training_pairs(words: List[str], window_size: int) -> List[Tuple[str, str]]:
"""
生成訓練用的詞對
參數:
words (List[str]): 單詞列表
window_size (int): 上下文窗口大小
回傳:
List[Tuple[str, str]]: 目標詞和上下文詞的配對列表
"""
pairs = []
for idx, word in enumerate(words):
for neighbor in range(-window_size, window_size + 1):
if neighbor == 0:
continue
neighbor_idx = idx + neighbor
if 0 <= neighbor_idx < len(words):
pairs.append((word, words[neighbor_idx]))
return pairs
def find_similar_words(word: str,
word_embeddings: np.ndarray,
word_to_ix: Dict[str, int],
ix_to_word: Dict[int, str],
top_n: int = 3) -> List[str]:
"""
尋找與目標詞最相似的詞
參數:
word (str): 目標詞
word_embeddings (np.ndarray): 詞向量矩陣
word_to_ix (Dict[str, int]): 單詞到索引的映射
ix_to_word (Dict[int, str]): 索引到單詞的映射
top_n (int): 要返回的相似詞數量
回傳:
List[str]: 最相似詞的列表
"""
target_vector = word_embeddings[word_to_ix[word]].reshape(1, -1)
similarities = cosine_similarity(target_vector, word_embeddings)
similar_indices = np.argsort(similarities[0])[::-1][1:top_n+1]
return [ix_to_word[i] for i in similar_indices]
def main():
"""
主程式執行流程
"""
# 建立語料文本
corpus = "I am happy because I am learning. I am excited to learn. Happy students are learning quickly."
# 資料預處理
words, word_to_ix, ix_to_word = preprocess_text(corpus)
pairs = generate_training_pairs(words, WINDOW_SIZE)
training_data = [(word_to_ix[target], word_to_ix[context]) for target, context in pairs]
# 初始化模型
vocab_size = len(word_to_ix)
model = SkipGram(vocab_size, EMBEDDING_DIM)
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
# 訓練模型
for epoch in range(EPOCHS):
total_loss = 0
for target, context in training_data:
target_tensor = torch.tensor([target], dtype=torch.long)
context_tensor = torch.tensor([context], dtype=torch.long)
optimizer.zero_grad()
output = model(target_tensor)
loss = criterion(output, context_tensor)
loss.backward()
optimizer.step()
total_loss += loss.item()
if (epoch + 1) % 10 == 0:
print(f'訓練週期 {epoch+1}, 損失值: {total_loss:.4f}')
# 取得訓練後的詞向量
word_embeddings = model.embeddings.weight.data.numpy()
# 顯示相似詞結果
print("與 'happy' 最相似的詞:", find_similar_words("happy", word_embeddings, word_to_ix, ix_to_word))
print("與 'learning' 最相似的詞:", find_similar_words("learning", word_embeddings, word_to_ix, ix_to_word))
# 視覺化詞向量
pca = PCA(n_components=2)
reduced_embeddings = pca.fit_transform(word_embeddings)
plt.figure(figsize=(8, 6))
for i, word in enumerate(word_to_ix.keys()):
x, y = reduced_embeddings[i]
plt.scatter(x, y)
plt.text(x + 0.01, y + 0.01, word, fontsize=12)
plt.xlabel("PCA 第一維度")
plt.ylabel("PCA 第二維度")
plt.title("Word2Vec Skip-gram 詞向量視覺化")
plt.show()
if __name__ == "__main__":
main()按 Ctrl + s 儲存
執行程式
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/01_word2vec.py執行結果 :
訓練週期 10, 損失值: 113.0977
訓練週期 20, 損失值: 101.9441
訓練週期 30, 損失值: 98.7468
訓練週期 40, 損失值: 97.5221
訓練週期 50, 損失值: 96.9120
訓練週期 60, 損失值: 96.5535
訓練週期 70, 損失值: 96.3194
訓練週期 20, 損失值: 101.9441
訓練週期 30, 損失值: 98.7468
訓練週期 40, 損失值: 97.5221
訓練週期 50, 損失值: 96.9120
訓練週期 60, 損失值: 96.5535
訓練週期 70, 損失值: 96.3194
訓練週期 50, 損失值: 96.9120
訓練週期 60, 損失值: 96.5535
訓練週期 70, 損失值: 96.3194
訓練週期 80, 損失值: 96.1548
訓練週期 90, 損失值: 96.0326
訓練週期 100, 損失值: 95.9380
訓練週期 110, 損失值: 95.8620
訓練週期 120, 損失值: 95.7993
訓練週期 130, 損失值: 95.7463
訓練週期 140, 損失值: 95.7004
訓練週期 150, 損失值: 95.6601
訓練週期 160, 損失值: 95.6241
訓練週期 170, 損失值: 95.5915
訓練週期 110, 損失值: 95.8620
訓練週期 120, 損失值: 95.7993
訓練週期 130, 損失值: 95.7463
訓練週期 140, 損失值: 95.7004
訓練週期 150, 損失值: 95.6601
訓練週期 160, 損失值: 95.6241
訓練週期 170, 損失值: 95.5915
訓練週期 160, 損失值: 95.6241
訓練週期 170, 損失值: 95.5915
訓練週期 180, 損失值: 95.5618
訓練週期 190, 損失值: 95.5345
訓練週期 200, 損失值: 95.5090
與 'happy' 最相似的詞: ['learning', 'excited', 'to']
與 'learning' 最相似的詞: ['happy', 'because', 'excited']然後會 show 出一張圖

範例 2
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/02_stochastic_gradient_descent.py執行結果
訓練週期 10/100, 損失值: 0.1400
訓練週期 20/100, 損失值: 0.0093
訓練週期 30/100, 損失值: 0.0078
訓練週期 40/100, 損失值: 0.0078
訓練週期 50/100, 損失值: 0.0078
訓練週期 60/100, 損失值: 0.0078
訓練週期 70/100, 損失值: 0.0078
訓練週期 80/100, 損失值: 0.0078
訓練週期 90/100, 損失值: 0.0078
訓練週期 100/100, 損失值: 0.0078
訓練完成!最終模型參數:
參數 linear.weight: 3.0012
參數 linear.bias: 2.0036範例 3
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/03_vanishing_gradient_problem.py執行結果
練週期 10/100, 損失值: 0.6906, 第一層梯度: 0.000054
訓練週期 20/100, 損失值: 0.6904, 第一層梯度: 0.000054
訓練週期 30/100, 損失值: 0.6902, 第一層梯度: 0.000055
訓練週期 40/100, 損失值: 0.6899, 第一層梯度: 0.000056
訓練週期 50/100, 損失值: 0.6897, 第一層梯度: 0.000057
訓練週期 60/100, 損失值: 0.6894, 第一層梯度: 0.000058
訓練週期 70/100, 損失值: 0.6892, 第一層梯度: 0.000059
訓練週期 80/100, 損失值: 0.6889, 第一層梯度: 0.000061
訓練週期 90/100, 損失值: 0.6887, 第一層梯度: 0.000062
訓練週期 100/100, 損失值: 0.6884, 第一層梯度: 0.000064
訓練完成!
觀察結果:由於使用 Sigmoid 激活函數,
深層網路中的梯度在反向傳播過程中逐漸消失,
這會導致較早層的權重更新緩慢,影響模型的學習效果。範例 4
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/04_vanishing_gradient_problem_fixed.py執行結果
訓練週期 10/100, 損失值: 0.0300, 第一層梯度: 0.002530
訓練週期 20/100, 損失值: 0.0108, 第一層梯度: 0.002441
訓練週期 30/100, 損失值: 0.0057, 第一層梯度: 0.002390
訓練週期 40/100, 損失值: 0.0026, 第一層梯度: 0.000645
訓練週期 50/100, 損失值: 0.0015, 第一層梯度: 0.000145
訓練週期 60/100, 損失值: 0.0010, 第一層梯度: 0.000119
訓練週期 70/100, 損失值: 0.0007, 第一層梯度: 0.000088
訓練週期 80/100, 損失值: 0.0005, 第一層梯度: 0.000051
訓練週期 90/100, 損失值: 0.0004, 第一層梯度: 0.000034
訓練週期 100/100, 損失值: 0.0003, 第一層梯度: 0.000029
測試結果:
輸入: [[ 0.5 0.5]
[-0.5 -0.5]]
預測: [[9.9999988e-01]
[1.6248593e-07]]
改進總結:
1. ReLU 激活函數避免了梯度消失
2. 批次正規化幫助穩定訓練過程
3. Xavier 初始化提供了更好的起始權重
4. Adam 優化器提供了自適應學習率範例 5
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/05_lstm.py執行結果
開始序列處理,顯示各時間步的計算結果:
=== 時間步 1 ===
輸入 x: [[-1.266819 -0.23635459 -1.2682884 1.1461157 ]]
遺忘門 (Forget gate) f_t:
[[0.6572256 0.36749864 0.42991826]]
輸入門 (Input gate) i_t:
[[0.59915054 0.5485195 0.48892254]]
候選記憶單元 (Candidate cell) c_candidate:
[[-0.240163 -0.3913692 -0.25401673]]
更新後的記憶單元 (Memory cell) c:
[[-0.1438938 -0.21467364 -0.1241945 ]]
輸出門 (Output gate) o_t:
[[0.5153311 0.620698 0.5811946]]
更新後的隱藏狀態 (Hidden state) h:
[[-0.07364536 -0.13123764 -0.07181233]]
-------------------------------
=== 時間步 2 ===
輸入 x: [[-1.5957438 0.4445498 -0.543539 -1.4150689]]
遺忘門 (Forget gate) f_t:
[[0.41003838 0.46972215 0.5150182 ]]
輸入門 (Input gate) i_t:
[[0.64580995 0.36331752 0.47042245]]
候選記憶單元 (Candidate cell) c_candidate:
[[-0.5844555 0.17626989 -0.62574565]]
更新後的記憶單元 (Memory cell) c:
[[-0.43644914 -0.03679502 -0.35832724]]
輸出門 (Output gate) o_t:
[[0.47196326 0.3124301 0.48176473]]
更新後的隱藏狀態 (Hidden state) h:
[[-0.19383381 -0.01149069 -0.1656017 ]]
-------------------------------
=== 時間步 3 ===
輸入 x: [[ 0.05293205 -0.77091706 -0.7147509 0.17642277]]
遺忘門 (Forget gate) f_t:
[[0.57225716 0.4478708 0.4592267 ]]
輸入門 (Input gate) i_t:
[[0.5396667 0.5573089 0.4244663]]
候選記憶單元 (Candidate cell) c_candidate:
[[-0.43210194 -0.06478254 -0.06248397]]
更新後的記憶單元 (Memory cell) c:
[[-0.48295218 -0.0525833 -0.19107577]]
輸出門 (Output gate) o_t:
[[0.4559599 0.6255029 0.47814628]]
更新後的隱藏狀態 (Hidden state) h:
[[-0.2045458 -0.03286073 -0.0902663 ]]
-------------------------------
=== 時間步 4 ===
輸入 x: [[-0.1387624 -0.6167944 1.6499552 -1.0031953]]
遺忘門 (Forget gate) f_t:
[[0.50970256 0.6360289 0.41048098]]
輸入門 (Input gate) i_t:
[[0.62627995 0.5196672 0.30097124]]
候選記憶單元 (Candidate cell) c_candidate:
[[-0.13491811 -0.45510677 -0.3899505 ]]
更新後的記憶單元 (Memory cell) c:
[[-0.33065847 -0.26994857 -0.19579686]]
輸出門 (Output gate) o_t:
[[0.45622295 0.3666553 0.6378727 ]]
更新後的隱藏狀態 (Hidden state) h:
[[-0.14558636 -0.0966419 -0.12332159]]
-------------------------------
=== 時間步 5 ===
輸入 x: [[ 0.26633266 -0.82728124 -0.04644813 -0.32036436]]
遺忘門 (Forget gate) f_t:
[[0.54177433 0.52325344 0.4516588 ]]
輸入門 (Input gate) i_t:
[[0.5455653 0.55652875 0.38952616]]
候選記憶單元 (Candidate cell) c_candidate:
[[-0.36856094 -0.08281524 -0.14614902]]
更新後的記憶單元 (Memory cell) c:
[[-0.38021633 -0.18734059 -0.14536224]]
輸出門 (Output gate) o_t:
[[0.43234622 0.56785136 0.50058883]]
更新後的隱藏狀態 (Hidden state) h:
[[-0.15689641 -0.1051543 -0.07225849]]
-------------------------------
LSTM 運作機制說明:
1. 遺忘門決定要遺忘多少舊的記憶
2. 輸入門決定要記住多少新的資訊
3. 候選記憶單元產生新的資訊
4. 記憶單元結合舊記憶和新資訊
5. 輸出門控制要輸出的資訊量範例 6
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/06_tensor_explain.py執行結果
PyTorch 張量維度展示:
純量張量 : 42
形狀 : torch.Size([])
維度數 : 0
資料型態 : torch.int64
--------------------------------------------------
向量張量 : [1 2 3 4 5]
形狀 : torch.Size([5])
維度數 : 1
資料型態 : torch.int64
--------------------------------------------------
矩陣張量 : [[1 2 3]
[4 5 6]
[7 8 9]]
形狀 : torch.Size([3, 3])
維度數 : 2
資料型態 : torch.int64
--------------------------------------------------
三維張量 : [[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]
[[10 11 12]
[13 14 15]
[16 17 18]]]
形狀 : torch.Size([2, 3, 3])
維度數 : 3
資料型態 : torch.int64
--------------------------------------------------
四維張量 : [[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]]
[[[ 9 10]
[11 12]]
[[13 14]
[15 16]]]]
形狀 : torch.Size([2, 2, 2, 2])
維度數 : 4
資料型態 : torch.int64
--------------------------------------------------
張量維度的實際應用說明:
0D 張量(純量):
- 單一數值,如損失函數的輸出值
- 準確率計算的結果
1D 張量(向量):
- 一維特徵向量
- 單字的詞嵌入表示
2D 張量(矩陣):
- 批次的特徵向量
- 灰階圖片
- 全連接層的權重矩陣
3D 張量:
- RGB 彩色圖片 (高度 × 寬度 × 色彩通道)
- 時間序列資料 (序列長度 × 批次大小 × 特徵維度)
4D 張量:
- 影像批次 (批次大小 × 高度 × 寬度 × 色彩通道)
- 影片資料 (幀數 × 高度 × 寬度 × 色彩通道)
注意事項:
1. 張量的維度數決定了它可以表示的資料複雜度
2. 在深度學習中,正確理解張量維度對於模型設計至關重要
3. PyTorch 支援自動微分,使得張量運算更加方便範例 7 : 實作 LSTM 模型來處理給定的文本
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/07_lstm_generate.py執行結果
開始訓練模型...
訓練週期 10/100, 損失值: 2.8676
訓練週期 20/100, 損失值: 2.8103
訓練週期 30/100, 損失值: 2.7176
訓練週期 40/100, 損失值: 2.0817
訓練週期 50/100, 損失值: 1.1766
訓練週期 60/100, 損失值: 0.5819
訓練週期 70/100, 損失值: 0.2223
訓練週期 80/100, 損失值: 0.1094
訓練週期 90/100, 損失值: 0.0700
訓練週期 100/100, 損失值: 0.0548
使用種子文本 'Hello' 生成的文本:
Hello, this is a sample text for LSTM text for LSTM text for LSTM text for LSTM text for LSTM text for LS範例 7
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/04_vanishing_gradient_problem_fixed.py執行結果
訓練週期 10/100, 損失值: 0.0300, 第一層梯度: 0.002530
訓練週期 20/100, 損失值: 0.0108, 第一層梯度: 0.002441
訓練週期 30/100, 損失值: 0.0057, 第一層梯度: 0.002390
訓練週期 40/100, 損失值: 0.0026, 第一層梯度: 0.000645
訓練週期 50/100, 損失值: 0.0015, 第一層梯度: 0.000145
訓練週期 60/100, 損失值: 0.0010, 第一層梯度: 0.000119
訓練週期 70/100, 損失值: 0.0007, 第一層梯度: 0.000088
訓練週期 80/100, 損失值: 0.0005, 第一層梯度: 0.000051
訓練週期 90/100, 損失值: 0.0004, 第一層梯度: 0.000034
訓練週期 100/100, 損失值: 0.0003, 第一層梯度: 0.000029
測試結果:
輸入: [[ 0.5 0.5]
[-0.5 -0.5]]
預測: [[9.9999988e-01]
[1.6248593e-07]]
改進總結:
1. ReLU 激活函數避免了梯度消失
2. 批次正規化幫助穩定訓練過程
3. Xavier 初始化提供了更好的起始權重
4. Adam 優化器提供了自適應學習率範例 8
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/04_vanishing_gradient_problem_fixed.py執行結果
訓練週期 10/100, 損失值: 0.0300, 第一層梯度: 0.002530
訓練週期 20/100, 損失值: 0.0108, 第一層梯度: 0.002441
訓練週期 30/100, 損失值: 0.0057, 第一層梯度: 0.002390
訓練週期 40/100, 損失值: 0.0026, 第一層梯度: 0.000645
訓練週期 50/100, 損失值: 0.0015, 第一層梯度: 0.000145
訓練週期 60/100, 損失值: 0.0010, 第一層梯度: 0.000119
訓練週期 70/100, 損失值: 0.0007, 第一層梯度: 0.000088
訓練週期 80/100, 損失值: 0.0005, 第一層梯度: 0.000051
訓練週期 90/100, 損失值: 0.0004, 第一層梯度: 0.000034
訓練週期 100/100, 損失值: 0.0003, 第一層梯度: 0.000029
測試結果:
輸入: [[ 0.5 0.5]
[-0.5 -0.5]]
預測: [[9.9999988e-01]
[1.6248593e-07]]
改進總結:
1. ReLU 激活函數避免了梯度消失
2. 批次正規化幫助穩定訓練過程
3. Xavier 初始化提供了更好的起始權重
4. Adam 優化器提供了自適應學習率範例 9
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/04_vanishing_gradient_problem_fixed.py執行結果
訓練週期 10/100, 損失值: 0.0300, 第一層梯度: 0.002530
訓練週期 20/100, 損失值: 0.0108, 第一層梯度: 0.002441
訓練週期 30/100, 損失值: 0.0057, 第一層梯度: 0.002390
訓練週期 40/100, 損失值: 0.0026, 第一層梯度: 0.000645
訓練週期 50/100, 損失值: 0.0015, 第一層梯度: 0.000145
訓練週期 60/100, 損失值: 0.0010, 第一層梯度: 0.000119
訓練週期 70/100, 損失值: 0.0007, 第一層梯度: 0.000088
訓練週期 80/100, 損失值: 0.0005, 第一層梯度: 0.000051
訓練週期 90/100, 損失值: 0.0004, 第一層梯度: 0.000034
訓練週期 100/100, 損失值: 0.0003, 第一層梯度: 0.000029
測試結果:
輸入: [[ 0.5 0.5]
[-0.5 -0.5]]
預測: [[9.9999988e-01]
[1.6248593e-07]]
改進總結:
1. ReLU 激活函數避免了梯度消失
2. 批次正規化幫助穩定訓練過程
3. Xavier 初始化提供了更好的起始權重
4. Adam 優化器提供了自適應學習率範例 10
& c:/Users/bigred/llm0207/.venv/Scripts/python.exe c:/Users/bigred/llm0207/04_vanishing_gradient_problem_fixed.py執行結果
訓練週期 10/100, 損失值: 0.0300, 第一層梯度: 0.002530
訓練週期 20/100, 損失值: 0.0108, 第一層梯度: 0.002441
訓練週期 30/100, 損失值: 0.0057, 第一層梯度: 0.002390
訓練週期 40/100, 損失值: 0.0026, 第一層梯度: 0.000645
訓練週期 50/100, 損失值: 0.0015, 第一層梯度: 0.000145
訓練週期 60/100, 損失值: 0.0010, 第一層梯度: 0.000119
訓練週期 70/100, 損失值: 0.0007, 第一層梯度: 0.000088
訓練週期 80/100, 損失值: 0.0005, 第一層梯度: 0.000051
訓練週期 90/100, 損失值: 0.0004, 第一層梯度: 0.000034
訓練週期 100/100, 損失值: 0.0003, 第一層梯度: 0.000029
測試結果:
輸入: [[ 0.5 0.5]
[-0.5 -0.5]]
預測: [[9.9999988e-01]
[1.6248593e-07]]
改進總結:
1. ReLU 激活函數避免了梯度消失
2. 批次正規化幫助穩定訓練過程
3. Xavier 初始化提供了更好的起始權重
4. Adam 優化器提供了自適應學習率