聊天視窗

Beyond Pixels:人機融合的未來操作手冊 - 第 2782 章

第二章:AI 核心:機器學習與深度學習基礎

發布於 2026-03-18 11:54

# 第二章:AI 核心:機器學習與深度學習基礎 本章將從理論與實務兩個層面,拆解機器學習與深度學習的核心概念,並說明其在影像、語音與行為生成中的具體應用。 --- ## 1. 基本概念與術語 | 名稱 | 定義 | 典型應用 | |------|------|-----------| | **監督式學習** | 給定輸入 X 與對應標籤 y,訓練模型 f 使得 f(X) ≈ y | 圖像分類、語音識別 | | **非監督式學習** | 只給輸入 X,模型自行發掘結構或分群 | 聚類、降維 | | **強化學習** | 智能體透過與環境互動獲得獎勵,調整策略 | 走路機器人、AlphaGo | | **轉移學習** | 將已學的模型參數遷移至新任務 | 小樣本圖像分類 | | **可解釋 AI (XAI)** | 讓模型決策過程可被人類理解 | 醫療診斷、金融風控 | --- ## 2. 神經網路架構 ### 2.1 前饋神經網路 (Feed‑Forward NN) 最簡單的深度學習模型,層層相連的全連接層,常用於 **數值預測**。 python import torch.nn as nn class SimpleFF(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super().__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_dim, output_dim) def forward(self, x): return self.fc2(self.relu(self.fc1(x))) ### 2.2 卷積神經網路 (CNN) 適用於 **圖像**、**視訊** 等結構化數據。核心概念:卷積層、池化層、批正規化。 python class SimpleCNN(nn.Module): def __init__(self, num_classes=10): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1) self.bn1 = nn.BatchNorm2d(32) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1) self.fc1 = nn.Linear(64 * 8 * 8, 128) self.fc2 = nn.Linear(128, num_classes) def forward(self, x): x = self.pool(F.relu(self.bn1(self.conv1(x)))) x = self.pool(F.relu(self.conv2(x))) x = x.view(x.size(0), -1) x = F.relu(self.fc1(x)) return self.fc2(x) ### 2.3 循環神經網路 (RNN / LSTM / GRU) 用於 **序列資料**,如語音、文本。LSTM 與 GRU 解決長距離依賴問題。 python class SimpleLSTM(nn.Module): def __init__(self, input_dim, hidden_dim, num_layers, output_dim): super().__init__() self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True) self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): h0 = torch.zeros(self.lstm.num_layers, x.size(0), self.lstm.hidden_size).to(x.device) c0 = torch.zeros(self.lstm.num_layers, x.size(0), self.lstm.hidden_size).to(x.device) out, _ = self.lstm(x, (h0, c0)) out = self.fc(out[:, -1, :]) # 取最後時間步 return out ### 2.4 Transformer 採用 **自注意力** 機制,已成為自然語言處理、圖像分割、生成任務的標配。 python from transformers import AutoModelForSeq2SeqLM, AutoTokenizer model_name = "google/flan-t5-large" model = AutoModelForSeq2SeqLM.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) input_text = "翻譯成中文:Hello, world!" inputs = tokenizer(input_text, return_tensors="pt") outputs = model.generate(**inputs) print(tokenizer.decode(outputs[0], skip_special_tokens=True)) --- ## 3. 影像、語音、行為生成 | 任務 | 核心模型 | 典型資料集 | 評估指標 | |------|-----------|-----------|-----------| | 影像分類 | ResNet, EfficientNet | ImageNet, CIFAR‑10 | Top‑1/Top‑5 Accuracy | | 物件偵測 | YOLO, Faster‑RCNN | COCO | mAP | | 影像生成 | StyleGAN, VQ‑VAE | CelebA | FID | | 語音識別 | DeepSpeech, wav2vec 2.0 | LibriSpeech | WER | | 語音合成 | Tacotron2, FastSpeech | LJ Speech | MOS | | 行為生成 | Generative Adversarial Imitation Learning (GAIL) | MuJoCo | Task Success Rate | ### 3.1 影像生成範例:StyleGAN2 python import dnnlib, legacy path = 'https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/stylegan2-ada.pkl' with dnnlib.util.open_url(path) as f: G = legacy.load_network_pkl(f)['G'] # Generator z = torch.randn(1, G.z_dim).cuda() img = G(z, truncation=0.7, noise_mode='const') ### 3.2 語音生成範例:FastSpeech2 python from speechbrain.pretrained import Tacotron2, SpeakerRecognition text = "人機融合的未來就在眼前" S = Tacotron2.from_hparams(source='speechbrain/tts-tacotron2-ljspeech', savedir='pretrained_models/tts-tacotron2') wav = S.encode_text(text) S.save_wav(wav, 'output.wav') --- ## 4. 實務部署:Docker Compose 範例 先前給出的 `docker-compose.yml` 範例展示如何同時運行 **Transformer、DALL‑E、Whisper**。在實務開發中,我們可以將上述模型封裝為 micro‑services,配合 **Kubernetes** 或 **TensorRT** 進行加速。 yaml # docker-compose.yml services: transformer: image: huggingface/transformers:latest ports: - "8000:8000" environment: - MODEL=google/flan-t5-large vision: image: openai/dall-e:latest ports: - "8001:8001" audio: image: openai/whisper:latest ports: - "8002:8002" - **API Gateway**:使用 **NGINX** 或 **Envoy** 將多個端點統一入口。 - **模型快取**:利用 Redis 或 memcached 缓存頻繁請求。 - **監控**:Prometheus + Grafana 監控 GPU 使用率、延遲與錯誤率。 --- ## 5. 進階話題:自動機器學習 (AutoML) 與元學習 | 方向 | 目的 | 典型技術 | |------|------|-----------| | AutoML | 自動搜尋最佳模型與超參數 | Google AutoML, AutoKeras | | 元學習 (Meta‑Learning) | 快速適應新任務 | MAML, Reptile | | 連續學習 (Continual Learning) | 防止遺忘 | EWC, LwF | > **實務建議**:在資料量極少的情境下,先進行 **知識蒸餾**,將大型模型的知識萃取到小模型,既保持效能,又減少資源消耗。 --- ## 6. 小結 - **神經網路基礎**:了解前饋、卷積、循環、Transformer 等架構,並能選擇對應任務。 - **實務範例**:提供完整程式碼,從模型定義到部署的全流程。 - **部署方案**:利用 Docker Compose 搭建多模型服務,並說明擴容與監控要點。 - **進階技術**:AutoML、元學習等未來研究方向,為高效模型開發提供參考。 > **提醒**:在實際開發中,請持續關注資料品質、模型偏見與可解釋性,以確保技術落地後能產生正向社會影響。 --- > **練習題** > 1. 設計一個簡易的圖像分類模型,使用 CIFAR‑10 資料集並計算 Top‑1 Accuracy。 > 2. 將上面模型封裝為 FastAPI,部署在本地 Docker,並測試 POST 請求。 > 3. 嘗試將上述模型應用於小語音辨識任務(如 Speech Commands),並比較 WER。