WeHelp
PyTorch 是建置、訓練、佈署現代人工智慧、深度學習、神經網路模型的核心開發套件。
  1. 簡介、安裝、快速開始
  2. Tensor 張量
  3. 定義資料集、載入器
  4. 神經網路簡介
  5. PyTorch 定義模型
  6. PyTorch 激勵函式
  7. PyTorch 損失函式
  8. PyTorch 優化器
  9. 二元分類模型範例
Tensor 張量
# PyTorch Tensor 簡介 `Tensor` 是 PyTorch 中最核心的資料結構,可以想成支援 GPU 加速與自動微分功能的多維陣列(Multi-dimensional Array)。 常見用途包括: - 儲存輸入資料、標籤與模型參數 - 進行矩陣運算、向量運算與深度學習計算 - 在 CPU、GPU 或其他裝置上執行運算 - 透過 Autograd 自動計算梯度,訓練神經網路 ```python import torch ``` --- ## 1. 建立 Tensor ### 從 Python List 建立 ```python x = torch.tensor([1, 2, 3]) print(x) # tensor([1, 2, 3]) ``` 建立二維 Tensor: ```python matrix = torch.tensor([ [1, 2], [3, 4] ]) print(matrix.shape) # torch.Size([2, 2]) ``` ### 指定資料型別 ```python x = torch.tensor([1, 2, 3], dtype=torch.float32) print(x.dtype) # torch.float32 ``` 常見資料型別: ```python torch.float32 torch.float64 torch.int32 torch.int64 torch.bool ``` --- ## 2. 建立特殊 Tensor ### 全為 0 或 1 ```python zeros = torch.zeros(2, 3) ones = torch.ones(2, 3) ``` 結果形狀都是 `(2, 3)`。 ### 指定形狀建立隨機 Tensor ```python x = torch.rand(2, 3) # 0 到 1 之間的均勻分布 x = torch.randn(2, 3) # 標準常態分布 ``` ### 建立單位矩陣 ```python identity = torch.eye(3) ``` 結果: ```text tensor([ [1., 0., 0.], [0., 1., 0.], [0., 0., 1.] ]) ``` ### 建立連續數值 ```python x = torch.arange(0, 10, 2) # tensor([0, 2, 4, 6, 8]) y = torch.linspace(0, 1, 5) # tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) ``` --- ## 3. Tensor 的基本屬性 ```python x = torch.randn(2, 3, 4) print(x.shape) # torch.Size([2, 3, 4]) print(x.size()) # 同樣可以取得形狀 print(x.ndim) # 維度數量:3 print(x.dtype) # 資料型別 print(x.device) # 所在裝置,例如 cpu print(x.numel()) # 元素總數:24 ``` --- ## 4. Tensor 的索引與切片 語法和 NumPy、Python List 類似。 ```python x = torch.tensor([ [1, 2, 3], [4, 5, 6] ]) print(x[0]) # 第一列 # tensor([1, 2, 3]) print(x[0, 1]) # 第 1 列、第 2 欄 # tensor(2) print(x[:, 1]) # 所有列的第 2 欄 # tensor([2, 5]) print(x[0, :2]) # 第一列的前兩個元素 # tensor([1, 2]) ``` 也可以使用布林條件: ```python x = torch.tensor([1, 2, 3, 4, 5]) print(x[x > 3]) # tensor([4, 5]) ``` --- ## 5. Tensor 的算術運算 大多數運算會逐元素進行。 ```python a = torch.tensor([1., 2., 3.]) b = torch.tensor([4., 5., 6.]) print(a + b) print(a - b) print(a * b) print(a / b) print(a ** 2) ``` 也可以使用函式形式: ```python torch.add(a, b) torch.sub(a, b) torch.mul(a, b) torch.div(a, b) ``` ### 純量運算 ```python x = torch.tensor([1., 2., 3.]) print(x + 10) # tensor([11., 12., 13.]) print(x * 2) # tensor([2., 4., 6.]) ``` --- ## 6. 矩陣運算 ### 矩陣乘法 ```python a = torch.randn(2, 3) b = torch.randn(3, 4) c = torch.matmul(a, b) # c.shape 為 torch.Size([2, 4]) ``` 也可以使用 `@`: ```python c = a @ b ``` 注意: ```python a * b ``` 代表逐元素乘法,不是矩陣乘法。 ### 轉置 ```python x = torch.randn(2, 3) print(x.T.shape) # torch.Size([3, 2]) ``` 對高維 Tensor,較常使用: ```python y = x.transpose(0, 1) ``` --- ## 7. 改變 Tensor 形狀 ### `reshape` ```python x = torch.arange(6) y = x.reshape(2, 3) print(y) # tensor([ # [0, 1, 2], # [3, 4, 5] # ]) ``` ### `view` ```python y = x.view(2, 3) ``` `view()` 通常要求 Tensor 在記憶體中是 contiguous;一般情況下可使用 `reshape()`,較方便。 ### `squeeze` 與 `unsqueeze` ```python x = torch.randn(1, 3) y = x.squeeze() print(y.shape) # torch.Size([3]) z = y.unsqueeze(0) print(z.shape) # torch.Size([1, 3]) ``` - `squeeze()`:移除大小為 `1` 的維度 - `unsqueeze(dim)`:在指定位置增加大小為 `1` 的維度 ### 改變維度順序 ```python x = torch.randn(2, 3, 4) y = x.permute(2, 0, 1) print(y.shape) # torch.Size([4, 2, 3]) ``` --- ## 8. 串接與分割 Tensor ### `cat` 沿著指定維度串接: ```python a = torch.randn(2, 3) b = torch.randn(2, 3) x = torch.cat([a, b], dim=0) print(x.shape) # torch.Size([4, 3]) ``` 沿著欄方向串接: ```python x = torch.cat([a, b], dim=1) print(x.shape) # torch.Size([2, 6]) ``` ### `stack` 新增一個維度後堆疊: ```python x = torch.stack([a, b], dim=0) print(x.shape) # torch.Size([2, 2, 3]) ``` ### `split` ```python x = torch.arange(6) parts = torch.split(x, 2) # (tensor([0, 1]), tensor([2, 3]), tensor([4, 5])) ``` --- ## 9. 聚合與統計運算 ```python x = torch.tensor([ [1., 2., 3.], [4., 5., 6.] ]) print(torch.sum(x)) # 所有元素總和 print(torch.mean(x)) # 平均值 print(torch.max(x)) # 最大值 print(torch.min(x)) # 最小值 ``` 指定維度: ```python print(torch.sum(x, dim=0)) # tensor([5., 7., 9.]) print(torch.mean(x, dim=1)) # tensor([2., 5.]) ``` 取得最大值及其索引: ```python values, indices = torch.max(x, dim=1) print(values) print(indices) ``` 常見函式還包括: ```python torch.std(x) # 標準差 torch.argmax(x) # 最大值索引 torch.argmin(x) # 最小值索引 ``` --- ## 10. Tensor 與裝置 CPU/GPU 查看 CUDA 是否可用: ```python device = torch.device( "cuda" if torch.cuda.is_available() else "cpu" ) x = torch.randn(2, 3).to(device) print(x.device) ``` 或: ```python if torch.cuda.is_available(): x = x.cuda() ``` 模型與資料必須放在相同裝置上: ```python model = model.to(device) inputs = inputs.to(device) ``` 否則可能出現裝置不一致的錯誤。 --- ## 11. Tensor 與 NumPy 互轉 ### Tensor 轉 NumPy ```python x = torch.tensor([1, 2, 3]) arr = x.numpy() ``` 這通常要求 Tensor 位於 CPU,且沒有參與梯度計算。 若 Tensor 可能需要梯度: ```python arr = x.detach().cpu().numpy() ``` ### NumPy 轉 Tensor ```python import numpy as np arr = np.array([1, 2, 3]) x = torch.from_numpy(arr) ``` `torch.from_numpy()` 通常會與 NumPy 陣列共享記憶體。 --- ## 12. Autograd 與梯度 若要讓 PyTorch 追蹤某個 Tensor 的梯度,可以設定: ```python x = torch.tensor(2.0, requires_grad=True) y = x ** 2 + 3 * x y.backward() print(x.grad) # tensor(7.) ``` 因為: \[ y = x^2 + 3x \] 所以: \[ \frac{dy}{dx} = 2x + 3 = 7 \] 在模型推論時,通常不需要計算梯度: ```python with torch.no_grad(): output = model(input) ``` 也可使用: ```python with torch.inference_mode(): output = model(input) ``` --- ## 13. 常見注意事項 ### Tensor 之間的資料型別通常要相容 ```python x = torch.tensor([1, 2, 3], dtype=torch.float32) ``` 神經網路輸入通常使用浮點數,而分類標籤常見使用 `torch.int64`: ```python inputs = inputs.float() labels = labels.long() ``` ### 避免不必要的原地操作 以下是原地操作: ```python x.add_(1) x *= 2 ``` 這類操作可能影響 Autograd,訓練模型時需小心。 ### `clone()` 與直接指定的差異 ```python x = torch.tensor([1, 2, 3]) y = x z = x.clone() ``` - `y = x`:兩個變數指向相同 Tensor - `z = x.clone()`:複製一份新的 Tensor --- ## 常用語法總覽 ```python import torch # 建立 torch.tensor([1, 2, 3]) torch.zeros(2, 3) torch.ones(2, 3) torch.rand(2, 3) torch.randn(2, 3) torch.arange(10) # 屬性 x.shape x.dtype x.device x.numel() # 索引與形狀 x[0] x[:, 1] x.reshape(...) x.squeeze() x.unsqueeze(0) x.permute(...) # 運算 x + y x * y x @ y torch.matmul(x, y) # 聚合 torch.sum(x) torch.mean(x) torch.max(x, dim=0) # 串接 torch.cat([x, y], dim=0) torch.stack([x, y], dim=0) # 裝置與梯度 x.to("cuda") x.requires_grad_(True) x.backward() x.grad ``` 總體而言,PyTorch Tensor 結合了多維陣列的彈性、GPU 加速能力,以及自動微分功能,是建立與訓練深度學習模型的基礎。
相關學習地圖、教學課程
Python 人工智慧
建議完成「Python 資料工程」教程後,繼續學習以下課程。