PyTorch中關(guān)于tensor.repeat()的使用
關(guān)于tensor.repeat()的使用
考慮到很多人在學(xué)習(xí)這個函數(shù),我想在這里提 一個建議:
強烈推薦 使用 einops 模塊中的 repeat() 函數(shù) 替代 tensor.repeat()!
它可以擺脫 tensor.repeat() 參數(shù)的神秘主義。
einops 模塊文檔地址:https://nbviewer.jupyter.org/github/arogozhnikov/einops/blob/master/docs/1-einops-basics.ipynb
學(xué)習(xí) tensor.repeat() 這個函數(shù)的功能的時候,最好還是要觀察所得到的 結(jié)果的維度。
不多說,看代碼:
>>> import torch >>> >>> # 定義一個 33x55 張量 >>> a = torch.randn(33, 55) >>> a.size() torch.Size([33, 55]) >>> >>> # 下面開始嘗試 repeat 函數(shù)在不同參數(shù)情況下的效果 >>> a.repeat(1,1).size() # 原始值:torch.Size([33, 55]) torch.Size([33, 55]) >>> >>> a.repeat(2,1).size() # 原始值:torch.Size([33, 55]) torch.Size([66, 55]) >>> >>> a.repeat(1,2).size() # 原始值:torch.Size([33, 55]) torch.Size([33, 110]) >>> >>> a.repeat(1,1,1).size() # 原始值:torch.Size([33, 55]) torch.Size([1, 33, 55]) >>> >>> a.repeat(2,1,1).size() # 原始值:torch.Size([33, 55]) torch.Size([2, 33, 55]) >>> >>> a.repeat(1,2,1).size() # 原始值:torch.Size([33, 55]) torch.Size([1, 66, 55]) >>> >>> a.repeat(1,1,2).size() # 原始值:torch.Size([33, 55]) torch.Size([1, 33, 110]) >>> >>> a.repeat(1,1,1,1).size() # 原始值:torch.Size([33, 55]) torch.Size([1, 1, 33, 55]) >>> >>> # ------------------ 割割 ------------------ >>> # repeat()的參數(shù)的個數(shù),不能少于被操作的張量的維度的個數(shù), >>> # 下面是一些錯誤示例 >>> a.repeat(2).size() # 1D < 2D, error Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor >>> >>> # 定義一個3維的張量,然后展示前面提到的那個錯誤 >>> b = torch.randn(5,6,7) >>> b.size() # 3D torch.Size([5, 6, 7]) >>> >>> b.repeat(2).size() # 1D < 3D, error Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor >>> >>> b.repeat(2,1).size() # 2D < 3D, error Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor >>> >>> b.repeat(2,1,1).size() # 3D = 3D, okay torch.Size([10, 6, 7]) >>>
Tensor.repeat()的簡單用法
相當(dāng)于手動實現(xiàn)廣播機制,即沿著給定的維度對tensor進行重復(fù):
比如說對下面x的第1個通道復(fù)制三次,其余通道保持不變:
import torch x = torch.randn(1, 3, 224, 224) y = x.repeat(3, 1, 1, 1) print(x.shape) print(y.shape)
結(jié)果為:
torch.Size([1, 3, 224, 224])
torch.Size([3, 3, 224, 224])
這個在復(fù)制batch的時候用的比較多,上面的情況就相當(dāng)于batch為1的3×224×224特征圖復(fù)制成了batch為3
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python機器學(xué)習(xí)實戰(zhàn)之最近鄰kNN分類器
這篇文章主要介紹了python機器學(xué)習(xí)實戰(zhàn)之最近鄰kNN分類器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
python實現(xiàn)跨excel的工作表sheet之間的復(fù)制方法
今天小編就為大家分享一篇python實現(xiàn)跨excel的工作表sheet之間的復(fù)制方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Python復(fù)制目錄結(jié)構(gòu)腳本代碼分享
這篇文章主要介紹了Python復(fù)制目錄結(jié)構(gòu)腳本代碼分享,本文分析了需求、講解了匿名函數(shù)lambda等內(nèi)容,并給出了腳本代碼,需要的朋友可以參考下2015-03-03

