記錄常用語法以備忘,記得不是很規範,主要方便自己遺忘時查閱…
本文從以下三個方面記錄pytorch的常用語法,並會隨着將來的使用不斷更新:
- 張量操作
- 數據預處理
- 網絡構建
1 張量操作
1.1 張量創建
x = torch.empty(5, 3 , dtype = torch.uint8)
x = torch.ones(5, 3 , dtype = torch.float64)
x = torch.rand(5, 3 , dtype = torch.float32, requires_grad=True)
x = torch.view(3,-1) # reshape x to (3,5)
x = torch.randn(5, 3 , dtype = torch.long)
x_copy = x.new_ones(5, 3 ,dtype = torch.double)
x_same_size = torch.randn_like(x, dtype = torch.float)
torch.arange(start, end, step=1, dtype=torch.int32)
torch.full(size, fill_value)
torch.normal(mean, std, out=None) #正態分佈
1.2類型轉換
b = a.long() # torch.int64
c = a.half() # torch.float16
d = a.int() # torch.int32
e = a.double() # torch.float64
f = a.float() # torch.float32
g = a.char() # torch.int8
h = a.byte() # torch.uint8
j = a.short() # torch.int16
c = a.type_as(c) # 轉化 a 的數據格式與 c 相同
1.3 張量信息查詢
print(x.size()) # print(x.shape)
print(x.dtype) #tensor.uint8 tensor.float64 ....
print(type(x))
print(x[0][2].item())
print(x[0][2])
1.3 張量操作
-
b = a.numpy() #numpy torch數據轉換
-
a = torch.form_numpy(b)
-
GPU設備中的運算
if torch.cuda.is_available():
device = torch.device("cuda")
y = torch.ones_like(x,device= device) #直接從 GPU 創建張量
x = x.to(device) #將 CPU 中變量移動到 GPU 中
z = y + x
- 求導相關
x = torch.rand(5, 5, requires_grad=True)
y = torch.rand(5, 5, requires_grad=True)
z=torch.sum(x+y)
z.backward(torch.ones_like(z))
print(z.grad_fn)
print(x.grad, y.grad)
with torch.no_grad():
............
2 數據預處理
3 構建網絡
3.1 優化器
3.2 網絡層
- 卷積層
self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, groups=1, bias=True)
x = self.conv1(x)
- BatchNormal層
self.bn1 = torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1,
affine=True, track_running_stats=True)
- 池化層
- ReLU層