首頁 免費資源 免費優惠 本文最後更新時間:2025-08-10 2025-08-10
蛤?你還不知道PyTorch?這AI神器讓你輕鬆變身魔法師! 想玩AI卻覺得難如登天?別怕!PyTorch讓你從魯蛇變身AI魔法師,輕鬆駕馭深度學習!
這篇文要帶你用最接地氣的方式,認識這個超好用的免費AI工具,保證讓你看了就想試試看!準備好被PyTorch圈粉了嗎?Let’s go!
欸!到底PyTorch是蝦米碗糕?
簡單來說,PyTorch就像是個超強大的積木組,裡面有各式各樣的AI零件,你可以用它來組裝出各種酷炫的模型,例如:辨識貓咪狗狗、讓電腦生成畫作、甚至讓機器人自己走路!而且它還是免費的!是不是超划算?
但別被 “深度學習” 嚇到,其實PyTorch用起來一點都不難!只要你有點程式基礎 (像是Python),加上一點點耐心,保證你也能做出讓朋友驚豔的AI作品!
為什麼PyTorch這麼夯?
PyTorch之所以這麼受歡迎,不是沒有原因的!它有幾個超棒的優點:
彈性到爆: PyTorch就像一塊黏土,想怎麼捏就怎麼捏!你可以自由地調整模型架構,不用被框架綁死。Debug超方便: 程式碼哪裡出錯?PyTorch的Debug工具讓你一目瞭然,輕鬆找到Bug,不用再對著螢幕崩潰!社群超給力: 遇到問題不用怕!PyTorch社群超熱情,各種疑難雜症都有人幫你解答,讓你不再孤軍奮戰!超多資源: 從官方文件到線上課程,PyTorch的學習資源多到爆炸,不怕學不會,只怕你沒時間學!我個人最喜歡PyTorch的彈性,有時候突發奇想想要修改模型,用其他的框架可能要改一大堆東西,但PyTorch幾乎可以無痛修改,這點真的超讚!
好啦!廢話不多說,開始動手玩PyTorch!
要開始玩PyTorch,第一步當然是把它裝起來!超簡單,只要打開你的終端機 (Terminal),然後輸入這行指令:
1 pip install torch torchvision torchaudio
按下Enter,然後就等它跑完就好啦! (記得要先裝好Python和pip喔!)
裝好之後,就可以開始寫你的第一個PyTorch程式了!
Hello, PyTorch!
我們來寫一個最簡單的PyTorch程式,讓它印出 “Hello, PyTorch!”:
1 2 3 import torchprint ("Hello, PyTorch!" )
把這段程式碼存成一個叫做 hello_pytorch.py
的檔案,然後在終端機輸入:
如果一切順利,你就會看到螢幕上印出 “Hello, PyTorch!” 啦!恭喜你,邁出了成為AI魔法師的第一步!
Tensor是什麼?聽起來很厲害!
在PyTorch的世界裡,最基本也是最重要的東西就是 Tensor 。你可以把它想像成一個多維的陣列,裡面裝滿了數字。不管是圖片、聲音、文字,在PyTorch裡面都是用Tensor來表示的。
舉個例子,一張灰階圖片可以看成是一個二維的Tensor,每個數字代表像素的灰度值;一段聲音可以看成是一個一維的Tensor,每個數字代表聲音的振幅。
建立Tensor
PyTorch提供了很多方法來建立Tensor,例如:
torch.tensor()
: 從Python的List或NumPy的Array建立Tensor。
1 2 3 4 5 6 7 8 9 10 11 12 import torch從List 建立Tensor data = [1 , 2 , 3 , 4 , 5 ] tensor = torch.tensor(data) print (tensor) Output: tensor([1 , 2 , 3 , 4 , 5 ])從NumPy Array建立Tensor import numpy as npnumpy_array = np.array([6 , 7 , 8 , 9 , 10 ]) tensor = torch.tensor(numpy_array) print (tensor) Output: tensor([ 6 , 7 , 8 , 9 , 10 ])
torch.zeros()
: 建立一個全部都是0的Tensor。
1 2 3 4 5 6 7 8 import torch建立一個2x3的Tensor,裡面全部都是0 tensor = torch.zeros((2 , 3 )) print (tensor)Output: tensor([[0. , 0. , 0. ], [0. , 0. , 0. ]])
torch.ones()
: 建立一個全部都是1的Tensor。
1 2 3 4 5 6 7 8 9 import torch建立一個3x2的Tensor,裡面全部都是1 tensor = torch.ones((3 , 2 )) print (tensor)Output: tensor([[1. , 1. ], [1. , 1. ], [1. , 1. ]])
torch.rand()
: 建立一個數值介於0到1之間的隨機Tensor。
1 2 3 4 5 6 7 8 9 10 import torch建立一個4x4的Tensor,裡面都是0 到1 之間的隨機數字 tensor = torch.rand((4 , 4 )) print (tensor)Output: tensor([[0.7576 , 0.2793 , 0.8947 , 0.0451 ], [0.0187 , 0.9860 , 0.7394 , 0.3232 ], [0.3017 , 0.3157 , 0.8049 , 0.1035 ], [0.3464 , 0.0797 , 0.4031 , 0.1832 ]])
Tensor的操作
Tensor可以進行各種數學運算,像是加、減、乘、除、矩陣乘法等等。這些操作都是經過優化的,可以快速地執行,讓你不用擔心效能問題。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import torch建立兩個Tensor tensor1 = torch.tensor([1 , 2 , 3 ]) tensor2 = torch.tensor([4 , 5 , 6 ]) 加法 tensor_sum = tensor1 + tensor2 print (tensor_sum) Output: tensor([5 , 7 , 9 ])乘法 tensor_product = tensor1 * tensor2 print (tensor_product) Output: tensor([ 4 , 10 , 18 ])矩陣乘法 (需要reshape成二維Tensor) tensor1 = tensor1.reshape(1 , 3 ) tensor2 = tensor2.reshape(3 , 1 ) tensor_matmul = torch.matmul(tensor1, tensor2) print (tensor_matmul) Output: tensor([[32 ]])
Tensor的dtype
Tensor裡面儲存的數字可以是不同的類型,例如整數 (int)、浮點數 (float) 等等。你可以用 dtype
屬性來查看Tensor的類型。
1 2 3 4 5 6 7 8 9 import torch建立一個整數Tensor int_tensor = torch.tensor([1 , 2 , 3 ], dtype=torch.int32) print (int_tensor.dtype) Output: torch.int32建立一個浮點數Tensor float_tensor = torch.tensor([1.0 , 2.0 , 3.0 ], dtype=torch.float32) print (float_tensor.dtype) Output: torch.float32
選擇適當的 dtype
可以節省記憶體空間,並且提高運算效能。
搞懂自動微分 (Autograd)
自動微分是PyTorch的核心功能之一,它可以自動計算模型的梯度 (Gradient)。梯度可以用來調整模型的參數,讓模型學習到更好的結果。
你可能會覺得 “梯度” 聽起來很可怕,但其實它只是一個數學概念,用來描述一個函數在某個點的變化率。
PyTorch的自動微分機制是透過追蹤Tensor的運算過程來實現的。當你對一個Tensor進行運算時,PyTorch會記錄下這個運算,並且建立一個運算圖 (Computation Graph)。這個運算圖可以用來計算梯度。
1 2 3 4 5 6 7 8 9 10 11 12 13 import torch建立一個Tensor,並且設定 requires_grad=True x = torch.tensor(2.0 , requires_grad=True ) 定義一個函數 y = x**2 + 2 *x + 1 計算梯度 y.backward() 印出x的梯度 print (x.grad) Output: tensor(6. )
在這個例子中,我們首先建立了一個Tensor x
,並且設定 requires_grad=True
。這個設定告訴PyTorch,我們要追蹤這個Tensor的運算過程,並且計算它的梯度。
然後,我們定義了一個函數 y = x**2 + 2*x + 1
。
接著,我們呼叫 y.backward()
來計算梯度。這個函數會自動追蹤運算圖,並且計算出 x
的梯度。
我們印出 x.grad
,可以看到它的值是 6。這表示當 x
的值增加一點點時,y
的值會增加 6 倍。
建立你第一個神經網路 (Neural Network)
現在,我們來建立一個簡單的神經網路,用來分類手寫數字。
首先,我們要載入 MNIST 資料集。MNIST 資料集包含 60,000 張訓練圖片和 10,000 張測試圖片,每張圖片都是 28x28 像素的灰階圖片,代表 0 到 9 的手寫數字。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import torchimport torchvisionimport torchvision.transforms as transforms定義資料轉換 transform = transforms.Compose([ transforms.ToTensor(), 將圖片轉換成 Tensor transforms.Normalize((0.5 ,), (0.5 ,)) 將像素值標準化到 -1 到 1 之間 ]) 載入 MNIST 資料集 trainset = torchvision.datasets.MNIST(root='./data' , train=True , download=True , transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4 , shuffle=True ) testset = torchvision.datasets.MNIST(root='./data' , train=False , download=True , transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=4 , shuffle=False )
這段程式碼會將 MNIST 資料集下載到 ./data
資料夾,並且將圖片轉換成 Tensor,然後將像素值標準化到 -1 到 1 之間。
接下來,我們要定義神經網路的架構。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import torch.nn as nnimport torch.nn.functional as F定義神經網路 class Net (nn.Module): def __init__ (self ): super ().__init__() self .conv1 = nn.Conv2d(1 , 6 , 5 ) 卷積層 self .pool = nn.MaxPool2d(2 , 2 ) 池化層 self .conv2 = nn.Conv2d(6 , 16 , 5 ) 卷積層 self .fc1 = nn.Linear(16 * 4 * 4 , 120 ) 全連接層 self .fc2 = nn.Linear(120 , 84 ) 全連接層 self .fc3 = nn.Linear(84 , 10 ) 全連接層 def forward (self, x ): x = self .pool(F.relu(self .conv1(x))) 卷積 -> ReLU -> 池化 x = self .pool(F.relu(self .conv2(x))) 卷積 -> ReLU -> 池化 x = torch.flatten(x, 1 ) 將多維 Tensor 展平成一維 x = F.relu(self .fc1(x)) 全連接 -> ReLU x = F.relu(self .fc2(x)) 全連接 -> ReLU x = self .fc3(x) 全連接 return x net = Net()
這個神經網路包含兩個卷積層、兩個池化層和三個全連接層。卷積層用來提取圖片的特徵,池化層用來降低圖片的維度,全連接層用來進行分類。
接下來,我們要定義損失函數 (Loss Function) 和優化器 (Optimizer)。
1 2 3 4 5 6 7 import torch.optim as optim定義損失函數 criterion = nn.CrossEntropyLoss() 定義優化器 optimizer = optim.SGD(net.parameters(), lr=0.001 , momentum=0.9 )
損失函數用來衡量模型的預測結果和真實結果之間的差距,優化器用來調整模型的參數,讓損失函數的值越來越小。
我們要訓練模型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 訓練模型 for epoch in range (2 ): 訓練 2 個 Epoch running_loss = 0.0 for i, data in enumerate (trainloader, 0 ): 取得輸入資料和標籤 inputs, labels = data 將梯度歸零 optimizer.zero_grad() 前向傳播 outputs = net(inputs) 計算損失 loss = criterion(outputs, labels) 反向傳播 loss.backward() 更新參數 optimizer.step() 印出訓練資訊 running_loss += loss.item() if i % 2000 == 1999 : 每 2000 個 Batch 印出一次 print ('[%d, %5d] loss: %.3f' % (epoch + 1 , i + 1 , running_loss / 2000 )) running_loss = 0.0 print ('Finished Training' )
這個迴圈會將訓練資料分成一個一個的 Batch,然後將每個 Batch 輸入到神經網路中,計算損失,並且更新模型的參數。
訓練完成後,我們可以測試模型的準確度。
1 2 3 4 5 6 7 8 9 10 11 12 13 測試模型 correct = 0 total = 0 with torch.no_grad(): 測試時不需要計算梯度 for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max (outputs.data, 1 ) total += labels.size(0 ) correct += (predicted == labels).sum ().item() print ('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total))
這段程式碼會將測試資料輸入到訓練好的神經網路中,並且計算模型的預測結果和真實結果之間的差距,然後計算模型的準確度。
這個範例只是一個簡單的入門,你可以嘗試修改神經網路的架構、調整訓練參數,並且使用不同的資料集來訓練模型,探索更多PyTorch的奧秘!
實用小技巧
善用GPU: 如果你有NVIDIA的GPU,一定要讓PyTorch使用GPU來加速運算。只要將Tensor和模型都移動到GPU上就可以了。
1 2 3 4 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) net.to(device) inputs, labels = inputs.to(device), labels.to(device) outputs = net(inputs)
使用DataParallel: 如果你有多個GPU,可以使用torch.nn.DataParallel
來讓模型在多個GPU上並行運算。
學習PyTorch官方文件: PyTorch官方文件是學習PyTorch最好的資源,裡面有詳細的API說明和範例程式碼。
加入PyTorch社群: PyTorch社群非常活躍,你可以在社群中和其他人交流學習心得,並且尋求幫助。
(欸,等等,沒有啦!)
PyTorch真的是一個超棒的AI工具,它簡單易用、彈性高、社群給力,絕對值得你花時間學習。希望這篇文章能讓你對PyTorch產生興趣,並且開始你的AI魔法師之旅!
別忘了,學習AI最重要的就是動手實作!趕快打開你的電腦,開始寫程式吧!祝你玩得開心! (揮手)
加入最愛 複製分享
→ 請點這裡繼續看更多內容
→ 請點這裡繼續看更多內容
重新整理 複製內容
→ 請點這裡繼續看更多內容
安裝App
→ 請點這裡繼續看更多內容
→ 最後更新時間 2025-08-10 要更新請點這裡