pytorch删除Tensor中指定位置的元素

list中删除一个元素:

l1 = ['a','b','c']
del l1[1] # 或者l1.remove('b')
print(l1)
> ['a', 'c']

array中删除元素

arr1 = np.array(['a','b','c'])
arr2 = np.delete(arr1,1) # 删除arr1中索引为1的元素
print(arr2)
> ['a' 'c']

tensor中删除元素,pytorch中貌似没有直接删除元素的方法,那么我们就简单写一个,经过测试发现这个方法居然跟np.delete速度差不多,还以为自己写的会很慢呢

def del_tensor_ele(arr,index):
    arr1 = arr[0:index]
    arr2 = arr[index+1:]
    return torch.cat((arr1,arr2),dim=0)
tensor1 = torch.Tensor([1,2,3,4,5,6])
tensor2 = del_tensor_ele(tensor1,1) # 删除tensor1中索引为1的元素
print(tensor2)
> tensor([1., 3., 4., 5., 6.])

也可以同时删除tensor中的多行元素:

def del_tensor_ele_n(arr, index, n):
    """
    arr: 输入tensor
    index: 需要删除位置的索引
    n: 从index开始,需要删除的行数
    """
    arr1 = arr[0:index]
    arr2 = arr[index+n:]
    return torch.cat((arr1,arr2),dim=0)

arr1 = torch.rand(7,6)
 # 从第1行开始删除4行(索引从0开始哦),剩余第0、5、6行
arr2 = del_tensor_ele_n(arr1,1,4)
print(arr1)
print(arr2)
>>> arr1:
tensor([[0.0473, 0.5389, 0.8256, 0.8314, 0.5320, 0.6926],
        [0.1302, 0.9447, 0.7577, 0.0921, 0.9979, 0.0900],
        [0.8216, 0.4201, 0.6074, 0.3906, 0.3945, 0.1757],
        [0.0885, 0.4012, 0.2769, 0.0840, 0.9057, 0.4395],
        [0.7319, 0.6979, 0.7728, 0.5062, 0.4723, 0.7334],
        [0.0475, 0.9364, 0.4075, 0.7096, 0.1819, 0.7119],
        [0.6423, 0.7226, 0.7131, 0.9694, 0.6918, 0.3276]])
>>> arr2:
tensor([[0.0473, 0.5389, 0.8256, 0.8314, 0.5320, 0.6926],
        [0.0475, 0.9364, 0.4075, 0.7096, 0.1819, 0.7119],
        [0.6423, 0.7226, 0.7131, 0.9694, 0.6918, 0.3276]])

你可能感兴趣的:(学习,python,pytorch,Tensor)