快捷鍵

torch.sum

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

傳回 input tensor 中所有元素的總和。

參數

input (Tensor) – 輸入 tensor。

關鍵字參數

dtype (torch.dtype, optional) – 返回 tensor 的期望資料類型。如果指定,輸入 tensor 會在執行運算之前轉換為 dtype。這對於防止資料類型溢位很有用。預設值:None。

注意

如果您需要特定 tensor 類型的結果,請使用 dtype 參數。否則,結果類型可能會自動提升 (例如,從 torch.int32torch.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

傳回給定維度 diminput 張量的每一列總和。如果 dim 是維度的列表,則對所有維度進行歸約。

如果 keepdimTrue,則輸出張量的大小與 input 相同,但在維度 dim 中大小為 1 的情況除外。 否則,dim 會被壓縮 (請參閱 torch.squeeze()),從而使輸出張量減少 1 個(或 len(dim) 個)維度。

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

  • dim (intintstuple, optional) – 要歸約的維度。 如果 None,則會歸約所有維度。

  • keepdim (bool) – 輸出張量是否保留 dim

關鍵字參數

dtype (torch.dtype, optional) – 返回 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 的完整開發人員文件

查看文件

教學課程

取得針對初學者和進階開發人員的深入教學課程

查看教學課程

資源

尋找開發資源並獲得您問題的解答

查看資源