【问题标题】:concatenating two tensors in pytorch(with a twist)在pytorch中连接两个张量(有一个扭曲)
【发布时间】:2020-09-09 09:45:15
【问题描述】:

我有一个大小为torch.Size([8, 768]) 的词嵌入(张量类型)存储在变量embeddings 中,看起来像这样:-

 tensor([[-0.0687, -0.1327,  0.0112,  ...,  0.0715, -0.0297, -0.0477],
        [ 0.0115, -0.0029,  0.0323,  ...,  0.0277, -0.0297, -0.0599],
        [ 0.0760,  0.0788,  0.1640,  ...,  0.0574, -0.0805,  0.0066],
        ...,
        [-0.0110, -0.1773,  0.1143,  ...,  0.1397,  0.3021,  0.1670],
        [-0.1379, -0.0294, -0.0026,  ..., -0.0966, -0.0726,  0.1160],
        [ 0.0466, -0.0113,  0.0283,  ..., -0.0735,  0.0496,  0.0963]],
       grad_fn=<IndexBackward>)

现在,我希望取一些嵌入的平均值并将平均值放回张量中。 例如,(我会用list而不是tensor来解释)

a = [1,2,3,4,5]
output = [1.5, 3, 4, 5]

所以,我在这里取了 1 和 2 的平均值,然后通过将元素移到列表中的左侧将其放入 list output。我也想对张量做同样的事情。

我将索引存储在变量i 中,我需要从中取平均值,j 变量用于停止索引。现在,让我们看一下代码:-

if i != len(embeddings):
  sum = 0
  count = 0
  #Calculating sum 
  for x in range(i-1, j):
    sum += text_index[x]
    count += 1

  avg = sum/count

  #Inserting the average in place of the other embeddings
  embeddings = embeddings[:i-1] + [avg] + embeddings[j:]
else :
  pass

现在,我在这一行遇到错误embeddings = embeddings[:i-1] + [avg] + embeddings[j:] 错误是:-

TypeError: unsupported operand type(s) for +: 'Tensor' and 'list'

现在,我知道如果embeddings 是一个列表但它是一个张量,上面的代码会运行良好。我该怎么做?

注意:

*1。 *embeddings.shape : torch.Size([8, 768])
2. avg 是浮点型**

【问题讨论】:

    标签: python pytorch tensor


    【解决方案1】:

    要连接多个张量,您可以使用torch.cat,其中张量列表在指定维度上连接。这要求所有张量具有相同数量的维度,并且除了它们连接的维度之外的所有维度都需要具有相同的大小。

    您的embeddings 的大小为 [8, 768],因此左侧部分和右侧部分的大小为 [num_left, 768][ num_right, 768]。并且avg 的大小为 [768](它是张量,而不是单个 float),因为您将多个嵌入平均为一个。为了将它们与其他两个部分连接起来,它需要具有大小 [1, 768],以便它可以在第一个维度上连接以创建大小为 [num_left + 1 + num_right, 768]。可以使用torch.unsqueeze 添加单数第一个维度。

    embeddings = torch.cat([embeddings[:i-1], avg.unsqueeze(0), embeddings[j:]], dim=0)
    

    for 循环也可以通过对张量进行切片并用torch.mean 取平均值来替换。

    # keepdim=True keeps the dimension that the average is taken on
    # So the output has size [1, 768] instead of [768]
    avg = torch.mean(embeddings[i-1:j], dim=0, keepdim=True)
    
    embeddings = torch.cat([embeddings[:i-1], avg, embeddings[j:]], dim=0)
    

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2020-08-27
      • 2022-01-12
      • 2021-11-20
      • 2019-08-24
      • 2021-06-18
      • 1970-01-01
      • 2019-07-10
      • 2021-10-30
      相关资源
      最近更新 更多