簡體   English   中英

張量的 Torch 和子集

[英]Torch sum subsets of tensor

如果張量的形狀是 [20, 5] 那么我需要一次取 10 個並對它們求和,所以結果是 [2,5]。

例如:
shape[20,5] -> shape[2, 5](一次求和 10)
shape[100, 20] -> shape[10,20](一次求和 10)

有沒有更快/最佳的方法來做到這一點?

例如:
[[1, 1], [1, 2], [3, 4], [1,2]]我想要[[2, 3], [4, 6]]取 2 行的總和。

我不知道有任何現成的解決方案。

如果平均值就足夠了,您可以使用nn.AvgPool1d https://pytorch.org/docs/stable/generated/torch.nn.AvgPool1d.html#avgpool1d

import torch, torch.nn as nn

x = torch.rand(batch_size, channels, lenght)
pool = nn.AvgPool1D(kernel_size=10, stride=10)

avg = pool(x)

使用此解決方案,只需確保您對正確的維度進行平均。

編輯我剛剛意識到你可以通過用avg = pool(x) * kernel_size修改最后一行來獲得總和!

您也可以編寫自己的 function 來為您求和:

import torch

def SumWindow(x, window_size, dim):
    input_split = torch.split(x, window_size, dim)
    input_sum = [v.sum(dim=dim), for v in input_split] # may be expensive if there are too many tensors
    out = torch.cat(inptu_sum, dim=dim)
    return dim

目前還不完全清楚,但我不能對此發表評論,所以。

對於第一種情況,您有:

t1 = torch.tensor([[1., 1.], [1., 2.], [3., 4.], [1.,2.]])
t1.shape #=> torch.Size([4, 2])
t1
tensor([[1., 1.],
        [1., 2.],
        [3., 4.],
        [1., 2.]])

要獲得所需的 output,您應該重塑:

tr1 = t1.reshape([2, 2, 2])
res1 = torch.sum(tr1, axis = 1)
res1.shape #=> torch.Size([2, 2])
res1
tensor([[2., 3.],
        [4., 6.]])

對於第二種情況,讓我們采用所有元素 ( torch.ones ) 的張量。

t2 = torch.ones((20, 5))
t2.shape #=> torch.Size([20, 5])
t2
tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])

因此,重塑以獲得所需的(?)結果:

tr2 = tensor.reshape((10, 2, 5))
res2 = torch.sum(tr2, axis = 0)
res2.shape #=> torch.Size([2, 5])
res2
tensor([[10., 10., 10., 10., 10.],
        [10., 10., 10., 10., 10.]])

這是你想要的?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM