pytorch基礎一:張量

簡單記錄以便查閱

張量

一、創建張量

x = torch.empty(5,3)                       # 創建未初始化矩陣張量
x = torch.rand(5,3)                        # 創建初始化隨機矩陣張量
x = torch.zeros(5,3,dtype=torch.long)      # 創建0填充矩陣張量
x = torch.tensor([5.5,3])                  # 使用現有數據初始化張量
x = x.new_ones(5,3, dtype=torch.double)    # 使用new_*來創建對象
x = 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)          # 正態分佈

二、張量尺寸

x.size()
x.shape

三、張量維度

x = torch.squeeze(x)         # 去掉大小爲1的維度
x = torch.unsqueeze(x,3)     # 在第三維增加1個維度
x = torch.transpose(x, 1, 2) # 交換維度1和維度2
x = torch.permute(1,2,3,0)   # 交換多個維度/維度重組

四、張量操作

x + y   /  torch.add(x, y)   /  y.add_(x)   # 四則運算
x[:, 1]                                     # 切片操作
x = x.view(-1, 8)                           # 改變維度(-1維度自動推斷)
x = x.reshape(8,-1)                         # 改變維度
x.item()                                    # 取張量的數值(前提:張量只有一個元素)
torch.cat((x,y), dim=0)                     # 張量拼接(在原有的某一維度上進行連接)
torch.stack((x,y), dim=0)                   # 張量拼接(創建一個新的維度,將原有維度在這個維度上進行順序排列)[詳細](https://blog.csdn.net/TH_NUM/article/details/83088915)
torch.chunk(a, chunk_num, dim=0)            # 張量拆分(在指定維度上將a變成chunk_num個大小相等的chunk,返回一個tuple。如果最後一個不夠chunk_num,就返回剩下的)
torch.split(a, chunk_size, dim=0)           # 張量拆分(同上)

五、張量類型轉換

1.Torch Tensor與NumPy數組共享底層內存地址
b = a.numpy()             # tensor 轉 numpy
b = torch.from_numpy(a)   # numpy 轉 tensor

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 相同

六、CUDA 張量

# is_available 函數判斷是否有cuda可以使用
# ``torch.device``將張量移動到指定的設備中
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA 設備對象
    y = torch.ones_like(x, device=device)  # 直接從GPU創建張量
    x = x.to(device)                       # 或者直接使用``.to("cuda")``將張量移動到cuda中
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` 也會對變量的類型做更改
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章