有关tensor numpy 索引

###将tensor 转为numpy

targets_to_np = targets.detach().cpu().numpy()
x = torch.tensor([1,2,3,2,5,6,5,2])
x#tensor([1, 2, 3, 2, 5, 6, 5, 2])
x1 = x.detach().cpu().numpy()
x1 #array([1, 2, 3, 2, 5, 6, 5, 2])

###将numpy 转为 tensor

targets_index_totensor =torch.tensor(targets_np_index,dtype=torch.int64)
x1 #array([1, 2, 3, 2, 5, 6, 5, 2])
x2 = torch.tensor(x1,dtype=torch.int64)
x2#tensor([1, 2, 3, 2, 5, 6, 5, 2])

###搜索一个数组中值为2 的索引

targets_np_index = np.where(targets_to_np==2)
x3 = numpy.where(x1==2)
x3#(array([1, 3, 7]),)

根据索引去找出tensor中对应的值

preds = torch.take(preds,targets_index_totensor)
x4 = torch.tensor(x3,dtype=torch.int64)
x4#tensor([[1, 3, 7]])
x5 = torch.take(x,x4)
x5#tensor([[2, 2, 2]])

你可能感兴趣的:(实习ing,python,深度学习,numpy,索引)