example:
in[1]: x = torch.rand(4,1,28,28)
in[2]: x.size()
out[2]: torch.size([4, 1, 28, 28])
in[3]: y = x.view(4,28*28)
in[4]: y.size()
out[4]:
torch.size([4, 784])
in[5]: y = x.reshape(4,28*28)
in[6]: y.size()
out[6]:
torch.size([4, 784])
example:
in[1]: x = torch.rand(4,1,28,28)
in[2]: x.size()
out[2]: torch.size([4, 1, 28, 28])
in[3]: y = x.squeeze()
in[4]: y.size()
out[4]: torch.size([4, 28, 28]) #預設去掉所有為元素個數為1的維度
in[5]: y = x.squeeze(1)
in[6]: y.size()
out[6]: torch.size([4, 28, 28])
in[7]: y = x.squeeze(2)
in[8]: y.size()
out[8]: torch.size([4, 1, 28, 28]) #元素個數不為1的維度不能squeeze().
in[9]: y = x.unsqueeze(2)
in[10]: y.size()
out[10]: torch.size([4, 1, 1, 28, 28]) #引數就是插入位置
example:
in[1]: x = torch.randn(2, 3)
in[2]: x.size()
out[2]: torch.size([2, 3])
in[3]: y = x.t() #轉置只針對二維張量
in[4]: y.size()
out[4]: torch.size([3, 2])
example:
in[1]: x = torch.rand(4,1,28,28)
in[2]: x.size()
out[2]: torch.size([4, 1, 28, 28])
in[3]: y = x.transpose(0, 1)
in[4]: y.size()
out[4]: torch.size([1, 4, 28, 28])
in[5]: y = x.permute(3, 2, 1, 0))
in[6]: y.size()
out[6]: torch.size([28, 28, 1, 4])
example:
in[1]: x = torch.rand(4,1,1,1)
in[2]: x.size()
out[2]: torch.size([4, 1, 1, 1])
in[3]: y = x.expand(4,1,28,28)
in[4]: y.size()
out[4]: torch.size([4, 1, 28, 28])
in[5]: y = x.repeat(4,1,28,28)
in[6]: y.size()
out[6]: torch.size([16, 1, 28, 28]) #引數是repeat倍數
此外,在進行維度變換時,要注意資料順序的實際意義!!!
pytorch 張量 張量的生成
張量的生成 import torch import numpy as np 使用tensor.tensor 函式構造張量 a torch.tensor 1.0,1.0 2.2 print a 獲取張量的維度 print 張量的維度 a.shape 獲取張量的形狀大小 print 張量的大小 a.si...
pytorch張量追蹤
torch.tensor 是這個包的核心類。如果設定它的屬性 requires grad 為 true,那麼它將會追蹤對於該張量的所有操作。當完成計算後可以通過呼叫 backward 來自動計算所有的梯度。這個張量的所有梯度將會自動累加到.grad屬性.要阻止乙個張量被跟蹤歷史,可以呼叫 detac...
pytorch 張量重構view
view在pytorch中是用來改變張量的shape的,簡單又好用。pytorch中view的用法通常是直接在張量名後用.view呼叫,然後放入自己想要的shape。如 tensor name.view shape example 1.直接用法 x torch.randn 4,4 x.size to...