溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)如何使用

發(fā)布時(shí)間:2023-03-09 11:15:19 來源:億速云 閱讀:95 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)如何使用”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)如何使用”文章能幫助大家解決問題。

tensor.squeeze() 和 tensor.unsqueeze() 是 PyTorch 中用于改變 tensor 形狀的兩個(gè)函數(shù),它們的作用如下:

  • tensor.squeeze(dim=None, *, out=None) : 壓縮 tensor 中尺寸為 1 的維度,并返回新的 tensor。可以指定要壓縮的維度(默認(rèn)為所有尺寸為 1 的維度均壓縮)。

  • tensor.unsqueeze(dim, *, out=None) : 在指定的位置插入一個(gè)新維度,并返回新的 tensor。dim 參數(shù)表示新插入的維度在哪個(gè)位置(從 0 開始),可以是負(fù)數(shù),表示倒數(shù)第幾個(gè)維度。

  • squeeze 是壓縮維度,unsqueeze是增加維度.

下面給出例子來說明它們的使用。

tensor.squeeze()

import torch
 
# 創(chuàng)建一個(gè)形狀為 (1, 3, 1, 2) 的 tensor
x = torch.randn(1, 3, 1, 2)
print(x.shape)  # torch.Size([1, 3, 1, 2])
 
# 壓縮尺寸為 1 的維度
y = x.squeeze()
print(y.shape)  # torch.Size([3, 2])
 
# 指定要壓縮的維度
y = x.squeeze(dim=0)
print(y.shape)  # torch.Size([3, 1, 2])

在上面的例子中,我們創(chuàng)建了一個(gè)形狀為 (1, 3, 1, 2) 的 tensor,然后使用 squeeze() 函數(shù)壓縮了尺寸為 1 的維度。在第二個(gè) squeeze() 調(diào)用中,我們指定了要壓縮的維度為 0,也就是第一個(gè)維度,因此第一個(gè)維度的大小被壓縮為 1,變成了形狀為 (3, 1, 2) 的 tensor。

tensor.unsqueeze()

import torch
 
# 創(chuàng)建一個(gè)形狀為 (3, 2) 的 tensor
x = torch.randn(3, 2)
print(x.shape)  # torch.Size([3, 2])
 
# 在維度 0 上插入新維度
y = x.unsqueeze(dim=0)
print(y.shape)  # torch.Size([1, 3, 2])
 
# 在維度 1 上插入新維度
y = x.unsqueeze(dim=1)
print(y.shape)  # torch.Size([3, 1, 2])
 
# 在倒數(shù)第二個(gè)維度上插入新維度
y = x.unsqueeze(dim=-2)
print(y.shape)  # torch.Size([3, 1, 2])

在上面的例子中,我們創(chuàng)建了一個(gè)形狀為 (3, 2) 的 tensor,然后使用 unsqueeze() 函數(shù)在不同的位置插入了新維度。在第一個(gè) unsqueeze() 調(diào)用中,我們?cè)诰S度 0 上插入了新維度,因此新的 tensor 形狀為 (1, 3, 2)。在第二個(gè)和第三個(gè) unsqueeze() 調(diào)用中,我們分別在維度 1 和倒數(shù)第二個(gè)維度上插入了新維度,分別得到了形狀為 (3, 1, 2) 和 (3, 2, 1) 的 tensor。

關(guān)于“tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)如何使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI