【问题标题】:How to remove an element from the torch tensor list?如何从火炬张量列表中删除元素?
【发布时间】:2022-11-04 00:33:48
【问题描述】:

我有如下所示的火炬张量列表

tensor([[[-1.8510e-01,  1.3181e-01,  3.2903e-01,  ...,  1.9867e-01,
           5.1037e-03,  6.4071e-03],
         [-4.6331e-01,  2.0216e-01,  2.7916e-01,  ...,  2.6695e-01,
          -1.3543e-02,  5.3604e-02],
         [-3.8719e-01,  2.9603e-01,  2.5516e-01,  ...,  1.7509e-01,
           8.9148e-02,  3.7516e-02],

这个火炬张量的形状是[500, 197, 768]

有 500 张 197*768 尺寸的图像。我需要删除一些图像的实例。假设我删除 5 张图片,那么形状将是 [495, 197, 768] 谁能告诉我如何使用索引删除它?

【问题讨论】:

    标签: python-3.x pytorch


    【解决方案1】:

    这取决于您要沿该维度删除项目的位置。

    要删除第一个/最后一个 n 元素(使用普通 Python 索引):

    new_data = data[n:] # Remove first n elements
    new_data = data[:-n] # Remove last n elements
    

    要删除张量内的n 项目,您需要指定起始索引ss+n 不应大于沿该维度的长度):

    new_data = torch.cat((data[:s], data[s+n:]), dim=0) # Remove n elements starting at s
    

    要使用索引列表删除,您可以执行以下操作:

    indices = [6, 7, 9, 100, 204] # Arbitrary list of indices that should be removed
    indices_to_keep = [i for i in range(data.shape[0]) if i not in indices] # List of indices that should be kept
    new_data = data[torch.LongTensor(indices_to_keep)]
    

    【讨论】:

      猜你喜欢
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2021-09-22
      • 2021-12-11
      • 1970-01-01
      • 2022-10-23
      • 2017-02-23
      相关资源
      最近更新 更多