pytorch學習紀錄
作者為淡江資工學生,寫這一份文章純為練習文筆表達及邏輯釐清,順便記錄學習軌跡,如有問題歡迎告知(本人邏輯欠佳,但需要一個練習且受公評的地方,還請多多見諒。)
pytorch學習紀錄
作者為淡江資工學生,寫這一份文章純為練習文筆表達及邏輯釐清,順便記錄學習軌跡,如有問題歡迎告知(本人邏輯欠佳,但需要一個練習且受公評的地方,還請多多見諒。)
今天要解說的是Pytorch,而了解Pytorch的第一個問題,就是甚麼是Pytorch?
1.甚麼是pytorch?
根據網路,pytorch是一個開源的python機器學習庫,底層由c++實踐,是一個隸屬於linux基金會的bsd授權自由軟體,首次釋出於2016年10月,至現在時間2023/12/26最新版本為2.1.2,適用於cuda11.8及12.1,最主要的特色是自動微分即類似陣列適用於nvdia gpu的張量。
2.如何學習?
官方就有官方課程,可google翻譯,接下來將以官方課程為主軸進行介紹。
官方教程:https://pytorch.org/tutorials/
3.第一站learn the basic
第一步:導入函示庫
import torch
from torch import nn
from torch.utils.data import DataLoader #utils是"實用程式"意思
from torchvision import datasets
from torchvision.transforms import ToTensor
pytorch有兩個處理資料的關鍵字,分別是dataloader及dataset,dataset中處存樣本(sample)及標籤(label),dataloader將基於dataset製作可迭代物件。其中 dataset包括許多常見實用訓練資料像coco(物件追蹤)及minist(手寫辨識)(想要的功能都可以在https://pytorch.org/vision/stable/datasets.html找到,都有提供導入程式碼及相關細節)。

每個 TorchVision類型dataset都包含兩個參數:transform 和 target_transform,分別用於修改樣本(sample)和標籤(label)。
接下來將以Minist為範例解說
第二步:download from dataset
# Download training data from open datasets.
training_data = datasets.FashionMNIST(
root="data",
train=True, #training train
download=True,
transform=ToTensor(),#轉為張量
)
# Download test data from open datasets.
test_data = datasets.FashionMNIST(
root="data",
train=False, #test not train
download=True,
transform=ToTensor(),#轉為張量
)
補充(可略過):將dataset可視化
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}#dictionary
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()#torch.randint(low=0, high, size,
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
第二步:建立databuilder
batch_size = 64 #訓練批次
# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
for X, y in test_dataloader:
print(f"Shape of X [N, C, H, W]: {X.shape}")
print(f"Shape of y: {y.shape} {y.dtype}")
break
未完
메타데이터
- post_id
- 0904d1d5bee1
- slug
- pytorch學習紀錄-0904d1d5bee1
- url
- https://medium.com/@410411655/pytorch%E5%AD%B8%E7%BF%92%E7%B4%80%E9%8C%84-0904d1d5bee1
- canonical_url
- https://medium.com/@410411655/pytorch%E5%AD%B8%E7%BF%92%E7%B4%80%E9%8C%84-0904d1d5bee1
- author_url
- https://medium.com/@410411655
- status
- ok
- fetched_at
- 2026-07-24 16:59:40