快捷方式

torch.sum

torch.sum(input, *, dtype=None) Tensor

返回 input tensor 中所有元素的和。

引數

input (Tensor) – 輸入 tensor。

關鍵字引數

dtype (torch.dtype, 可選) – 返回 tensor 期望的資料型別。如果指定,操作執行前輸入 tensor 會被轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:None。

注意

如果您需要特定 tensor 型別的結果,請使用 dtype 引數。否則,結果型別可能會自動提升(例如,從 torch.int32 提升到 torch.int64)。

示例

>>> a = torch.randn(1, 3)
>>> a
tensor([[ 0.1133, -0.9567,  0.2958]])
>>> torch.sum(a)
tensor(-0.5475)
torch.sum(input, dim, keepdim=False, *, dtype=None) Tensor

在給定維度 dim 上返回 input tensor 每行的和。如果 dim 是一個維度列表,則對所有維度進行求和。

如果 keepdimTrue,則輸出 tensor 的大小與 input 相同,但 dim 維度的大小為 1。否則,dim 將被壓縮(參見 torch.squeeze()),導致輸出 tensor 減少 1 個(或 len(dim) 個)維度。

引數
  • input (Tensor) – 輸入 tensor。

  • dim (intinttuple,可選) – 要進行求和運算的維度。如果為 None,則對所有維度進行求和。

  • keepdim (bool) – 輸出 tensor 是否保留 dim 維度。

關鍵字引數

dtype (torch.dtype, 可選) – 返回 tensor 期望的資料型別。如果指定,操作執行前輸入 tensor 會被轉換為 dtype。這對於防止資料型別溢位非常有用。預設值:None。

示例

>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.0569, -0.2475,  0.0737, -0.3429],
        [-0.2993,  0.9138,  0.9337, -1.6864],
        [ 0.1132,  0.7892, -0.1003,  0.5688],
        [ 0.3637, -0.9906, -0.4752, -1.5197]])
>>> torch.sum(a, 1)
tensor([-0.4598, -0.1381,  1.3708, -2.6217])
>>> b = torch.arange(4 * 5 * 6).view(4, 5, 6)
>>> torch.sum(b, (2, 1))
tensor([  435.,  1335.,  2235.,  3135.])

文件

查閱 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並獲取解答

檢視資源