學習pytorch中的一些筆記(2)

學習pytorch中的一些筆記(2)

一、torch.expand(*sizes)

torch.expand()用來擴展某張量某維度的值,先看代碼示例:

import torch
x = torch.tensor([[1, 2, 3]])
print(x.size())
y = x.expand(2,3)
print(y)
print(y.size())

輸出:
torch.Size([1, 3])
tensor([[1, 2, 3],
        [1, 2, 3]])
torch.Size([2, 3])

官網文檔如下:
torch.expand()
通過官方文檔,我覺得需要注意的一點是,expand()只能對維度爲1的那個維度進行擴張,如果不是1,則無法進行擴展。示例如下:

import torch
x = torch.tensor([[1, 2, 3]])
print(x.size())
y = x.expand(2,4)
print(y)
print(y.size())

輸出:
torch.Size([1, 3])
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-27-ac6657df382d> in <module>
      1 x = torch.tensor([[1, 2, 3]])
      2 print(x.size())
----> 3 y = x.expand(2,4)
      4 print(y)
      5 print(y.size())

RuntimeError: The expanded size of the tensor (4) must match the existing size (3) at non-singleton dimension 1.  
Target sizes: [2, 4].  Tensor sizes: [1, 3]

二、torch.Tensor.item( )和torch.Tensor.tolist( )

torch.Tensor.item( )在獲取一維張量中的數字的時候使用,且只能使用在一維張量,返回一個數字。
item( )
torch.Tensor.tolist( )在取tensor中數據的時候使用,一維張量的時候等同於torch.Tensor.item( )返回一個數字,多維張量的時候使用會返回一個list(嵌套的列表)。

在這裏插入圖片描述

三、torch.squeeze( )和torch.unsqueeze( )

torch.suqeeze( ) 是將一個張量中維度爲1的維度刪除然後返回,第二個參數可以不指定。
torch.squeeze( )
需要注意的是,squeeze只能對於維度爲1的維度進行刪除
第二個參數如果指定的話,就只對指定的維度進行操作,如果指定維度不是1,就不進行任何操作,如果指定維度是1,就刪除此維度。

torch.unsuqeeze( ):是返回一個在指定維度增加了一個維度爲1的維度的張量,第二個參數必須指定。
torch.unsqueeze( )

import torch
x = torch.zeros(2, 1, 2, 1, 2)
print(x.size())
y = torch.squeeze(x)
print(y.size())
z = torch.squeeze(x,1)
print(z.size())

輸出:
torch.Size([2, 1, 2, 1, 2])
torch.Size([2, 2, 2])
torch.Size([2, 2, 1, 2])


import torch
x = torch.zeros(2, 2, 2)
print(x.size())
y = torch.unsqueeze(x,1)
print(y.size())
z = torch.unsqueeze(x,3)
print(z.size())

輸出:
torch.Size([2, 2, 2])
torch.Size([2, 1, 2, 2])
torch.Size([2, 2, 2, 1])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章