torch.sparse.sum¶
- torch.sparse.sum(input, dim=None, dtype=None)[source][source]¶
返回给定稀疏张量每行的和。
返回稀疏张量
input
在给定维度dim
上的求和。如果dim
是一个维度列表,则对所有这些维度进行降维。当对所有sparse_dim
进行求和时,此方法返回一个密集张量而不是稀疏张量。所有求和的
dim
都会被压缩(见torch.squeeze()
),结果输出张量的维度比input
少dim
。在反向传播过程中,只有
nnz
位置的input
的梯度会反向传播。注意,input
的梯度是合并的。- 参数:
输入(张量)- 输入稀疏张量
dim(int 或 int 的元组)- 要降维的维度或维度列表。默认:对所有维度进行降维。
dtype(
torch.dtype
,可选)- 返回 Tensor 期望的数据类型。默认:input
的数据类型。
- 返回类型:
示例:
>>> nnz = 3 >>> dims = [5, 5, 2, 3] >>> I = torch.cat([torch.randint(0, dims[0], size=(nnz,)), torch.randint(0, dims[1], size=(nnz,))], 0).reshape(2, nnz) >>> V = torch.randn(nnz, dims[2], dims[3]) >>> size = torch.Size(dims) >>> S = torch.sparse_coo_tensor(I, V, size) >>> S tensor(indices=tensor([[2, 0, 3], [2, 4, 1]]), values=tensor([[[-0.6438, -1.6467, 1.4004], [ 0.3411, 0.0918, -0.2312]], [[ 0.5348, 0.0634, -2.0494], [-0.7125, -1.0646, 2.1844]], [[ 0.1276, 0.1874, -0.6334], [-1.9682, -0.5340, 0.7483]]]), size=(5, 5, 2, 3), nnz=3, layout=torch.sparse_coo) # when sum over only part of sparse_dims, return a sparse tensor >>> torch.sparse.sum(S, [1, 3]) tensor(indices=tensor([[0, 2, 3]]), values=tensor([[-1.4512, 0.4073], [-0.8901, 0.2017], [-0.3183, -1.7539]]), size=(5, 2), nnz=3, layout=torch.sparse_coo) # when sum over all sparse dim, return a dense tensor # with summed dims squeezed >>> torch.sparse.sum(S, [0, 1, 3]) tensor([-2.6596, -1.1450])