torch.sum¶
- torch.sum(input, *, dtype=None) Tensor¶
返回
inputtensor 中所有元素的和。- 引數
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上返回inputtensor 每行的和。如果dim是一個維度列表,則對所有維度進行求和。如果
keepdim為True,則輸出 tensor 的大小與input相同,但dim維度的大小為 1。否則,dim將被壓縮(參見torch.squeeze()),導致輸出 tensor 減少 1 個(或len(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.])