PyTorch 统计属性-Tensor基本操作

发布于:2024-06-13 ⋅ 阅读:(118) ⋅ 点赞:(0)
  • 最小 min, 最大 max, 均值 mean,累加 sum,累乘 prod …

    >>> a = torch.arange(0,8).view(2,4).float()
    >>> a
    tensor([[0., 1., 2., 3.],
            [4., 5., 6., 7.]])
            
            
    >>> a.min()  	## 最小值:tensor(0.)
    >>> a.max()  	## 最大值:tensor(7.)
    
    >>> a.argmin()	## 最小值对应的 idx: tensor(0)
    >>> a.argmax()	## 最大值对应的 idx: tensor(7)
    
    >>> a.argmin(dim=1)	## 每行 dim=1 最小值对应的 idx: tensor([0, 0])  每行都是最前面的数最小
    >>> a.argmax(dim=1)	## 每行 dim=1 最大值对应的 idx: tensor([3, 3])  每行都是最后面的数最大
    
    >>> a.argmin(dim=1, keepdim=True)  ## 加 keepdim 可以保持原 a 维度
    tensor([[0],
            [0]])
    >>> a.argmax(dim=1, keepdim=True)  ## 加 keepdim 可以保持原 a 维度
    tensor([[3],
            [3]])
    
    >>> a.topk(3, dim=1)  ## k 大的 value 和对应的 idx
    torch.return_types.topk(
    values=tensor([[3., 2., 1.],
            [7., 6., 5.]]),
    indices=tensor([[3, 2, 1],
            [3, 2, 1]]))
    >>> a.topk(3, dim=1, largest=False)   ## k 小的:largest=False
    torch.return_types.topk(
    values=tensor([[0., 1., 2.],
            [4., 5., 6.]]),
    indices=tensor([[0, 1, 2],
            [0, 1, 2]]))
    
    
    >>> a.mean()  	## 平均值:tensor(3.5000)
    >>> a.sum()		## 累加值:tensor(28.)
    >>> a.prod()	## 累乘值:tensor(0.)
    
  • norm 范数,非 normalization 不是一个概念

    >>> a = torch.full([1], 8)  # tensor([1, 1, 1, 1, 1, 1, 1, 1])     
    >>> a.float().norm(1)  		#: tensor(8.)
    >>> a.float().norm(2)  		#: tensor(2.8284)
    
    >>> b = a.view(2,4) 		# tensor([[1, 1, 1, 1], [1, 1, 1, 1]])
    >>> b.float().norm(1)  		#: tensor(8.)	
    >>> a.float().norm(2)  		#: tensor(2.8284)
    
    >>> b.float().norm(1, dim=0)  # 指定 dim:0
    tensor([2., 2., 2., 2.])
    >>> b.float().norm(1, dim=1)  # 指定 dim: 1
    tensor([4., 4.])
    
    • .norm() 时可能出现的 RuntimeError 解决方案:加 .float() -> a.float.norm()
      >>> a.norm()
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "D:\Tutu.Python\lib\site-packages\torch\tensor.py", line 389, in norm
          return torch.norm(self, p, dim, keepdim, dtype=dtype)
        File "D:\Tutu.Python\lib\site-packages\torch\functional.py", line 1290, in norm
          return _VF.frobenius_norm(input, dim=(), keepdim=keepdim)  # type: ignore
      RuntimeError: Can only calculate the mean of floating types. Got Long instead.
      


网站公告

今日签到

点亮在社区的每一天
去签到