自動微分

Vibe Prompt

「從零實作一個簡單的自動微分引擎,支援 +, -, *, sin, cos,並計算 f(x,y)=sin(x)*cos(y) 的梯度。」

import math

class Var:
    def __init__(self, val, children=()):
        self.val = val
        self.grad = 0
        self._backward = lambda: None
        self._prev = set(children)
    
    def __add__(self, other):
        other = other if isinstance(other, Var) else Var(other)
        out = Var(self.val + other.val, (self, other))
        def _backward():
            self.grad += out.grad
            other.grad += out.grad
        out._backward = _backward
        return out
    
    def __mul__(self, other):
        other = other if isinstance(other, Var) else Var(other)
        out = Var(self.val * other.val, (self, other))
        def _backward():
            self.grad += other.val * out.grad
            other.grad += self.val * out.grad
        out._backward = _backward
        return out
    
    def __neg__(self):
        return self * Var(-1)
    
    def __sub__(self, other):
        return self + (-other)
    
    def sin(self):
        out = Var(math.sin(self.val), (self,))
        def _backward():
            self.grad += math.cos(self.val) * out.grad
        out._backward = _backward
        return out
    
    def cos(self):
        out = Var(math.cos(self.val), (self,))
        def _backward():
            self.grad += -math.sin(self.val) * out.grad
        out._backward = _backward
        return out
    
    def backward(self):
        topo = []
        visited = set()
        def build(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build(child)
                topo.append(v)
        build(self)
        self.grad = 1
        for v in reversed(topo):
            v._backward()

# 測試
x = Var(0.5)
y = Var(1.2)
f = (x.sin() * y.cos())
f.backward()
print(f"f = sin({x.val}) * cos({y.val}) = {f.val:.4f}")
print(f"df/dx = {x.grad:.4f} (理論: cos(x)*cos(y) = {math.cos(0.5)*math.cos(1.2):.4f})")
print(f"df/dy = {y.grad:.4f} (理論: -sin(x)*sin(y) = {-math.sin(0.5)*math.sin(1.2):.4f})")

本章總結

  • 理解核心概念與原理
  • 掌握實作方法與技巧
  • 熟悉常見問題與解決方案
  • 能夠應用於實際專案

延伸閱讀

  • 官方文件與 API 參考
  • GitHub 開源專案範例
  • 相關技術書籍與課程
  • 社群討論與技術部落格

實作範例

基礎範例

# 本節提供一個完整的實作範例
# 讓你能夠將所學應用到實際專案中

步驟說明

  1. 初始化:設定開發環境與必要工具
  2. 資料準備:收集與整理所需資料
  3. 核心實作:實作主要功能與邏輯
  4. 測試驗證:確保功能正確運作
  5. 最佳化:調整效能與使用者體驗

常見錯誤

| 錯誤類型 | 可能原因 | 解決方法 | |---------|---------|---------| | 編譯錯誤 | 語法問題 | 檢查程式碼語法 | | 執行錯誤 | 環境問題 | 確認相依套件已安裝 | | 邏輯錯誤 | 演算法問題 | 逐步除錯與測試 | | 效能問題 | 效率問題 | 使用效能分析工具 |

程式碼範例

# 範例程式碼
import sys

def main():
    # 主程式邏輯
    print("Hello, World!")

if __name__ == "__main__":
    main()

相關資源

  • 官方文件
  • API 參考手冊
  • 開源專案範例
  • 技術社群討論

完全なチュートリアルをロック解除

このチャプターは有料コンテンツです。プロジェクトに参加して、10以上の神レベルのPromptや実際のソースコード例を含む、5000字以上の深い分析をロック解除してください!