max item sum size squeeze
torch.max()
torch.max(a,0)或torch.max(a,1)
torch.max(a,0)返回行的最大值+最大值的索引
torch.max(a,1)返回列的最大值+最大值的索引

参考博客
x.item()
x.item() →获取x的值 只能是数值,不能是list
x必须是tensor 且只能是数值
x.sum()
x.sum() →计算x的总和
x是tensor
可以x.sum().item()连用,先求和再获取值
x.size(0)
x.size()返回张量tensor的shape
x.size(0)返回shape的第0维度
x.size(-1)返回shape的最后一个维度

import torch
yyy = torch.tensor(111)
print(yyy.size())
# print(yyy.size(0)) # 报错 因为没有shape
# print(yyy.size(-1)) # 报错 因为没有shape
print()
zzz = torch.tensor([1,2,3,4])
print(zzz.size())
print(zzz.size(0))
print(zzz.size(-1))
print()
www = torch.tensor([[1],[2],[3],[4]])
print(www.size())
print(www.size(0))
print(www.size(-1))
print()
xxx = torch.tensor([[1,2,3,4],[5,6,7,8],[1,3,5,6]])
print(xxx.size())
print(xxx.size(0))
print(xxx.size(-1))
# 结论:
# x.size()返回张量tensor的shape
# x.size(0)返回shape的第0维度
# x.size(-1)返回shape的最后一个维度
x.squeeze()
x.squeeze() 或torch.squeeze(x,dim) 压缩tensor,删除所有维度中是1的维度
或删除指定的维度dim中的1(不删除全部1)
同理,torch.unsqueeze(x,dim)扩充指定维度dim,使其维度为1
squeeze删除1的例子

本文详细介绍了PyTorch中的一些基本操作,包括如何使用torch.max()获取张量中的最大值及其索引,如何利用x.item()获取张量的数值,如何通过x.sum()计算张量元素的总和,以及如何运用x.size()来获取张量的形状信息,并介绍了x.squeeze()压缩张量的功能。

1523

被折叠的 条评论
为什么被折叠?



