tensor.squeeze() 和 tensor.unsqueeze() 是 PyTorch 中用于改變 tensor 形狀的兩個(gè)函數(shù),它們的作用如下:
- tensor.squeeze(dim=None, *, out=None) : 壓縮 tensor 中尺寸為 1 的維度,并返回新的 tensor??梢灾付ㄒ獕嚎s的維度(默認(rèn)為所有尺寸為 1 的維度均壓縮)。
- tensor.unsqueeze(dim, *, out=None) : 在指定的位置插入一個(gè)新維度,并返回新的 tensor。dim 參數(shù)表示新插入的維度在哪個(gè)位置(從 0 開始),可以是負(fù)數(shù),表示倒數(shù)第幾個(gè)維度。
- squeeze 是壓縮維度,unsqueeze是增加維度.
下面給出例子來說明它們的使用。文章源自四五設(shè)計(jì)網(wǎng)-http://m.wasochina.com/49496.html
tensor.squeeze()
importtorch?# 創(chuàng)建一個(gè)形狀為 (1, 3, 1, 2) 的 tensorx=torch.randn(1,3,1,2)(x.shape)?# torch.Size([1, 3, 1, 2])?# 壓縮尺寸為 1 的維度y=x.squeeze()(y.shape)?# torch.Size([3, 2])?# 指定要壓縮的維度y=x.squeeze(dim=0)(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。文章源自四五設(shè)計(jì)網(wǎng)-http://m.wasochina.com/49496.html
tensor.unsqueeze()
importtorch?# 創(chuàng)建一個(gè)形狀為 (3, 2) 的 tensorx=torch.randn(3,2)(x.shape)?# torch.Size([3, 2])?# 在維度 0 上插入新維度y=x.unsqueeze(dim=0)(y.shape)?# torch.Size([1, 3, 2])?# 在維度 1 上插入新維度y=x.unsqueeze(dim=1)(y.shape)?# torch.Size([3, 1, 2])?# 在倒數(shù)第二個(gè)維度上插入新維度y=x.unsqueeze(dim=-2)(y.shape)?# torch.Size([3, 1, 2])
在上面的例子中,我們創(chuàng)建了一個(gè)形狀為 (3, 2) 的 tensor,然后使用 unsqueeze() 函數(shù)在不同的位置插入了新維度。在第一個(gè) unsqueeze() 調(diào)用中,我們在維度 0 上插入了新維度,因此新的 tensor 形狀為 (1, 3, 2)。在第二個(gè)和第三個(gè) unsqueeze() 調(diào)用中,我們分別在維度 1 和倒數(shù)第二個(gè)維度上插入了新維度,分別得到了形狀為 (3, 1, 2) 和 (3, 2, 1) 的 tensor。文章源自四五設(shè)計(jì)網(wǎng)-http://m.wasochina.com/49496.html
到此這篇關(guān)于tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解的文章就介紹到這了文章源自四五設(shè)計(jì)網(wǎng)-http://m.wasochina.com/49496.html 文章源自四五設(shè)計(jì)網(wǎng)-http://m.wasochina.com/49496.html



評(píng)論