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])