pytorch中的view函數和max函數


一、view函數

代碼:

a=torch.randn(3,4,5,7)
b = a.view(1,-1)
print(b.size())

輸出:

torch.Size([1, 420])

解釋:

其中參數-1表示剩下的值的個數一起構成一個維度。

如上例中,第一個參數1將第一個維度的大小設定成1,后一個-1就是說第二個維度的大小=元素總數目/第一個維度的大小,此例中為3*4*5*7/1=420.

 

代碼:

a=torch.randn(3,4,5,7)
d = a.view(a.size(0),a.size(1),-1)
e=a.view(4,-1,5)

輸出:

d:torch.Size([3, 4, 35])
e:torch.Size([4, 21, 5])

 

二、max函數

1.torch.max()簡單來說是返回一個tensor中的最大值。

2.這個函數的參數中還有一個dim參數,使用方法為re = torch.max(Tensor,dim),返回的re為一個二維向量,其中re[0]為最大值的Tensor,re[1]為最大值對應的index的Tensor。

代碼:

#1.torch.max()簡單來說是返回一個tensor中的最大值。
si = torch.randn(4, 5)
print(si)
print(torch.max(si))
#2.這個函數的參數中還有一個dim參數,使用方法為re = torch.max(Tensor,dim),返回的re為一個二維向量,其中re[0]為最大值的Tensor,re[1]為最大值對應的index的Tensor。
print(torch.max(si,0)[0])#取列中的最大值
print(torch.max(si,0)[1])#取列中的最大值索引

print(torch.max(si,1)[0])#取行中的最大值
print(torch.max(si,1)[1])#取行中的最大值索引

輸出:

tensor([[ 1.4299, 0.7956, -1.6310, 0.4027, -0.4100],
[-0.3948, -1.1118, -2.5281, 0.1844, 0.3637],
[ 0.5374, -0.5555, -0.4043, 0.3505, 0.4292],
[ 0.5980, 0.6220, -1.9076, -1.6443, 1.0266]])
tensor(1.4299)
tensor([ 1.4299, 0.7956, -0.4043, 0.4027, 1.0266])
tensor([0, 0, 2, 0, 3])
tensor([1.4299, 0.3637, 0.5374, 1.0266])


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM