2025年3月8日 星期六

用泰勒展開式逼近一個 sin 函數

用 python3 的 autograd 模組來驗證:

from autograd import elementwise_grad as grad
import autograd.numpy as audo_np
import matplotlib.pyplot as plt

_n = lambda n   : n * _n(n - 1) if n > 0 else 1  # n! 階層 n
_x = lambda a, n: a * _x(a, n - 1) if n > 0 else 1 # aⁿ, a 指數 n
d_ = lambda n, f: d_(n - 1, grad(f)) if n > 1 else grad(f) # dⁿf(x)/dx, n 階微分函數
f_ = lambda g, a, n: d_(n, g)(0.0) * _x(a, n) / _n(n) + f_(g, a, n - 1) if n > 0 else g(0.0) # f(x) = n 項泰勒展開式: Σ fⁿ(0) * xⁿ / n! 逼近 g(x)
x = audo_np.linspace(-10, 10, 500)
y = f_(audo_np.sin, x, 20)
plt.plot(x , y, x, audo_np.sin(x))  
plt.show()


2025年3月7日 星期五

使用 python3 的 autograd package 產生 n-階微分方程式並繪圖

1. 先安裝 python3 的 python3-venv 虛擬環境, 並安裝到目錄
    sudo apt install python3-venv
    cd ~
    python3 -m venv venv
2. 進入 python3 虛擬環境, 安裝 autograd
    cd ~
    source venv/bin/activate
    pip install autograd
3. 編輯以下測試檔:   xed ~/test_grad.py
from autograd import elementwise_grad as egrad
import autograd.numpy as audo_np
import matplotlib.pyplot as plt
tanh = lambda t: (1.0 - audo_np.exp((-2 * t))) / (1.0 + audo_np.exp(-(2 * t)))
derivative_ = lambda n, f: derivative_(n - 1, derivative_(1, f)) if n > 1 else egrad(f) # dⁿf(x)/dx
#
x = audo_np.linspace(-7, 7, 500)
y0 = tanh(x)
y1 = derivative_(1, tanh)(x)
y2 = derivative_(2, tanh)(x)
y3 = derivative_(3, tanh)(x)
y4 = derivative_(4, tanh)(x)
#
plt.plot(x, y0, x, y1,  x, y2, x, y3, x, y4)
plt.show()

4. 啟用虛擬環境, 執行看看:
    cd ~
    source venv/bin/activate
    python3 test_grad.py

p.s.如果不想安裝 autograd, 可以上官網把整個目錄下載回來:  https://github.com/HIPS/autograd

2025年3月4日 星期二

學習類神經網路

 參考影片 

1. https://www.youtube.com/watch?v=ErnWZxJovaM&list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI

2. https://www.youtube.com/watch?v=BHgssEwMxsY

類神經網路(Neural Network)通常有一個輸入層及一層輸出層, 中間有一個以上的隱藏層,當隱藏層大於 1 時稱為 deep neural network (DNN).層與層之間透過神經元(neuron)互相連接,輸入層神經元收到輸入資料後透過權重將資料往內層擴散傳播,隱藏層的神經元將資料收集加總再串接 activation function 把資料映射後透過權重把資料繼續往內層擴散, 終端輸出層則是加總前一隱藏層的擴散資料再串接 activation function 後輸出數值. 最後透過 backpropagation 演算法訓練出模型內的參數值. 但利用損失函數導出偏微分函數是一件很複雜的事, 還有一種方式是透過 auto gradient computational graph 算出偏微函數值, 讓訓練程序變得簡潔, 可以參考 micrograd 網站 https://github.com/karpathy/micrograd ,  或是 teenygrad 的網站 https://github.com/tinygrad/teenygrad/activity 以及 tinygrad  網站 https://github.com/tinygrad/tinygrad , 內部有完整實現出 autograd 方式. 其中 micrograd 原始碼引擎不到 100 行簡單扼要, teenygrad 不到 1000 行, 還另外實現出 Tesor 及 Optimizer 運算法, 而 tinygrad 則可以利用 GPU 來加速運算. 讓 python 不用安裝 pytorch 也能寫出簡單的類神經網路運算法

用泰勒展開式逼近一個 sin 函數

用 python3 的 autograd 模組來驗證: from autograd import elementwise_grad as grad import autograd.numpy as audo_np import matplotlib.pyplot as plt _...