numpy和tensor增加、刪除一個(gè)維度

numpy

1.增加維度

import numpy as np
a = np.ones((3,4))
print(a.shape)

輸出a的形狀:(3,4)

現(xiàn)在變量a為二維數(shù)組,在圖形計(jì)算中有時(shí)需要將圖像處理成(length, width, channel)的形式,我們需要將a處理成三維,第三維的形狀為1,方式如下:

b = np.expand_dims(a, 2)
print(b.shape)

輸出的形狀為:(3,4,1)

2.壓縮維度

如果我們想要將b再變回二維,需要用到如下方法:

c = np.squeeze(b)
print(c.shape)

輸出的形狀為:(3,4)
我們也可以指定要壓縮的維度

c = np.squeeze(b, axis=2)
print(c.shape)

輸出為:(3,4)

Tensor

1.增加維度

import torch
a = torch.ones((3,4))
print(a.shape)

輸出的形狀為:torch.Size([3,4])
現(xiàn)在,我們要讓它增加一個(gè)維度,變成[1,3,4]

b = torch.unsqueeze(a, 0)
print(b.shape)

輸出結(jié)果為:torch.Size([1,3,4])
現(xiàn)在我們要把它再壓縮到三維:

c = torch.squeeze(b, 0)
print(c.shape)

輸出結(jié)果為:torch.Size([3,4]) 。[1]


  1. Numpy , Tensor , Variable 增刪一個(gè)值為1的維度
    ?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容