Python 相对于第一维连接

Python 相对于第一维连接,python,deep-learning,pytorch,Python,Deep Learning,Pytorch,在下面的代码中,torch.cat真正做什么。我知道它连接了样本中包含的批次,但为什么我们必须这样做,以及连接的真正含义是什么 # memory is just a list of events def sample(self, batch_size): samples = zip(*random.sample(self.memory, batch_size)) return map(lambda x: Variable(torch.cat(x,0))) torch.cat

在下面的代码中,torch.cat真正做什么。我知道它连接了样本中包含的批次,但为什么我们必须这样做,以及连接的真正含义是什么

 # memory is just a list of events
 def sample(self, batch_size):
    samples = zip(*random.sample(self.memory, batch_size))
    return map(lambda x: Variable(torch.cat(x,0)))
torch.cat按照名称所示沿着指定维度连接

文档中的示例将告诉您需要了解的一切:

x = torch.randn(2, 3) # shape (2, 3)
catted = torch.cat((x, x, x), dim=0) # shape (6, 3), e.g. 3 x stacked on each other
请记住,连接的张量需要具有相同的维数,但要连接的张量除外

在上面的示例中,它没有做任何事情,甚至不可行,因为它缺少第二个参数输入来应用map,请参见

假设您将改为执行此映射:

map(lambda x: Variable(torch.cat(x,0)), samples)
它将创建一个新的形状张量[lensamples,x_dim_1,x_dim_2,…],前提是所有样本都具有相同的维度(0除外)

不过,这是一个非常复杂的示例,绝对不应该像torch.autograd.Variable被弃用那样进行,请看,这应该足够了:

# assuming random.sample returns either `list` or `tuple`
def sample(self, batch_size):
   return torch.cat(random.sample(self.memory, batch_size), dim=0)