支持PyTorch的einops張量操作神器用法示例詳解
今天做visual transformer研究的時候,發(fā)現(xiàn)了einops這么個神兵利器,決定大肆安利一波。
先看鏈接:https://github.com/arogozhnikov/einops
安裝:
pip install einops
基礎用法
einops的強項是把張量的維度操作具象化,讓開發(fā)者“想出即寫出”。舉個例子:
from einops import rearrange # rearrange elements according to the pattern output_tensor = rearrange(input_tensor, 'h w c -> c h w')
用'h w c -> c h w'就完成了維度調換,這個功能與pytorch中的permute相似。但是,einops的rearrange玩法可以更高級:
from einops import rearrange import torch a = torch.randn(3, 9, 9) # [3, 9, 9] output = rearrange(a, 'c (r p) w -> c r p w', p=3) print(output.shape) # [3, 3, 3, 9]
這就是高級用法了,把中間維度看作r×p,然后給出p的數(shù)值,這樣系統(tǒng)會自動把中間那個維度拆解成3×3。這樣就完成了[3, 9, 9] -> [3, 3, 3, 9]的維度轉換。
這個功能就不是pytorch的內置功能可比的。
除此之外,還有reduce和repeat,也是很好用。
from einops import repeat import torch a = torch.randn(9, 9) # [9, 9] output_tensor = repeat(a, 'h w -> c h w', c=3) # [3, 9, 9]
指定c,就可以指定復制的層數(shù)了。
再看reduce:
from einops import reduce import torch a = torch.randn(9, 9) # [9, 9] output_tensor = reduce(a, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2)
這里的'mean'指定池化方式。 相信你看得懂,不懂可留言提問~
高級用法
einops也可以嵌套在pytorch的layer里,請看:
# example given for pytorch, but code in other frameworks is almost identical
from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU
from einops.layers.torch import Rearrange
model = Sequential(
Conv2d(3, 6, kernel_size=5),
MaxPool2d(kernel_size=2),
Conv2d(6, 16, kernel_size=5),
MaxPool2d(kernel_size=2),
# flattening
Rearrange('b c h w -> b (c h w)'),
Linear(16*5*5, 120),
ReLU(),
Linear(120, 10),
)
這里的Rearrange是nn.module的子類,直接可以當作網(wǎng)絡層放到模型里~
一個字,絕。
以上就是支持PyTorch的einops張量操作神器用法示例詳解的詳細內容,更多關于einops張量操作用法的資料請關注腳本之家其它相關文章!
相關文章
python實現(xiàn)封裝得到virustotal掃描結果
這篇文章主要介紹了python實現(xiàn)封裝得到virustotal掃描結果的方法,是比較實用的技巧,可將掃描結果寫入數(shù)據(jù)庫,需要的朋友可以參考下2014-10-10
Jupyter Notebook讀取csv文件出現(xiàn)的問題及解決
這篇文章主要介紹了Jupyter Notebook讀取csv文件出現(xiàn)的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
python通過ElementTree操作XML獲取結點讀取屬性美化XML
本文講解如何通過ElementTree解析XML,獲取兒子結點、插入兒子結點、操作屬性、美化XML2013-12-12

