【问题标题】:Python: drop index from tensorPython:从张量中删除索引
【发布时间】:2021-08-28 06:39:56
【问题描述】:

我有两个张量。

tensor_A对应一批8张图片,20类物体,每张图片为256 x 256

tensor_B对应len 20全1或0的8个数组,对应对象类是否存在

tensor_A.shape = ([8, 20, 256, 256])

tensor_B.shape = ([8, 20])

从 tensor_A,我想删除对应于 tensor_B 中 1 的索引

例如如果 tensor_B[0] = [1,0,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0, 0]

我想做 tensor_A[0, 0, :, :].drop 然后 tensor_A[0, 2, :, :].drop 等等,但都是一步完成

到目前为止,我已经使用以下方法确定了对应于 1 的索引:

for i in range(8):
    (tensor_B[i, :] == 0).nonzero())
# code for dropping here

不知道如何继续

【问题讨论】:

    标签: tensor torch indices drop


    【解决方案1】:

    你想要的东西行不通,因为:

    # A -> tensor of shape (8, 20, 256, 256)
    # B -> tensor of shape (8, 20)
    
    # If B[0] = [1,0,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0]
    dropped_A_0 = A[0, B[0] == 0, :, :]
    # dropped_A_0 -> tensor of shape (1, 13, 256, 256)
    
    # If B[1] = [1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]
    dropped_A_1 = A[1, B[1] == 0, :, :]
    # dropped_A_1 -> tensor of shape (1, 16, 256, 256)
    

    你看到问题了吗?当您从 A 的行中“删除”值时,它们不再是相同的形状,因此不能作为单个张量一起存在。您可以拥有的是 A 的行列表,其中包含已删除的值:

    dropped_A = []
    for i in range(len(A)):
        dropped_A.append(A[i, B[i] == 0, :, :])
    

    您可以做的另一件事是将 A 中不需要的值设置为 0。

    A[B == 1] = 0
    

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 2022-07-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多