我想重寫nn.Linear的作業。問題是,輸入大小為(N,*,in_feature),權重大小為(out_feature, in_feature)。如果我想用python把結果變成(N,*,out_feature),我應該怎樣寫代碼?
input @ weight.T
是不對的,很遺憾。
uj5u.com熱心網友回復:
為了應用@,大小需要匹配,即__matmul__:輸入x的形狀是(N, *, in_feature),而權重張量w的形狀是(out_feature, in_feature)。
x = torch.rand(2, 4, 4, 10)
w = torch.rand(5, 10)
對w進行轉置將得到一個(in_feature, out_feature)的形狀。在x和w.T之間應用__matmul__將減少到一個(N, *, out_feature)的形狀:
>>> z = [email protected]
>>> z.shape
torch.Size([2, 4, 4, 5] )
或者等同于使用torch.matmul:
>>> z = torch.matmul(x, w.T)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316888.html
標籤:
上一篇:為什么我無法使用#apisauce從我的api獲得回應?
下一篇:如何解釋一個多引數的函式?
