torch索引使用方式示例
已知两个tensor,[x1,y1,z1],[x2,y2,z2],求对应位置的最大值,即比较x1和x2,y1和y2,z1和z2,最后得出tensor
import torch # 创建两个包含三个元素的张量 tensor1 = torch.tensor([x1, y1, z1]) tensor2 = torch.tensor([x2, y2, z2]) # 比较两个张量中对应位置的最大值 max_tensor = torch.max(tensor1, tensor2) print(max_tensor)
有个troch.tensor([x1,y1,x2,y2])怎么转为torch.tensor([y1,x1,y2,x2])
import torch # 创建包含四个元素的原始张量 original_tensor = torch.tensor([x1, y1, x2, y2]) # 进行转换 transformed_tensor = original_tensor[[1, 0, 3, 2]] print(transformed_tensor)
-
已知b = torch.Tensor([[1],[2]]),请问b[1]和b[[1]]的区别
在 PyTorch 中,b[1]
和 b[[1]]
之间有一个微妙的区别,这涉及到张量的索引和切片操作。让我解释一下两者之间的区别:
-
b[1]:这是使用整数索引来获取张量
b
中的元素。由于b
是一个形状为 (2, 1) 的张量,使用整数索引会选择第二个元素,即2
。这会返回一个包含标量值2
的张量。 -
b[[1]]:这是使用列表或张量索引来获取张量
b
中的元素。由于使用了双层方括号,所以实际上是在索引一个张量,即形状为 (1, 1) 的张量,其中包含的值是2
。这会返回一个形状为 (1, 1) 的张量。
以下是示例代码,说明两者之间的区别:
import torch
b = torch.tensor([[1], [2]])
# 使用整数索引
b_indexed = b[1]
print("b[1]:", b_indexed) # 输出: tensor([2])
# 使用列表索引
b_list_indexed = b[[1]]
print("b[[1]]:", b_list_indexed) # 输出: tensor([[2]])
总之,b[1]
返回一个包含标量值 2
的张量,而 b[[1]]
返回一个形状为 (1, 1) 的张量,其中包含值 2
。
其他索引汇总
>>> torch.cat([torch.tensor(1).unsqueeze(0),torch.tensor(2).unsqueeze(0)]) tensor([1, 2]) >>> torch.tensor([0,1,3]).unsqueeze(0) tensor([[0, 1, 3]]) >>> torch.tensor([0,1,3]).unsqueeze(1) tensor([[0], [1], [3]]) >>> a = torch.tensor(1) >>> a.numel() 1 >>> a = torch.tensor([0,1,3]) >>> torch.index_select(a,0,torch.tensor(1)) tensor([1]) >>> torch.index_select(a,0,torch.tensor([1,2])) tensor([1, 3]) >>> a =torch.tensor(1).unsqueeze(0) >>> a tensor([1]) >>> d tensor([0., 1.]) >>> a = torch.tensor(1) >>> d[a] tensor(1.) >>> a tensor(1) >>> a.tolist() 1 >>> type(a.tolist()) <class 'int'> >>> tensor = torch.tensor([[1], [2], [3], [4]]) >>> flattened_tensor = tensor.view(-1) >>> print("平铺后的张量:", flattened_tensor) 平铺后的张量: tensor([1, 2, 3, 4]) >>> torch.cat((torch.tensor([]), torch.tensor([])),dim=0) tensor([]) >>> a = (1,2) >>> c,d = a >>> c,d (1, 2) >>> c 1 >>> d 2 >>> type(c) <class 'int'> >>> c tensor([[1.], [2.]]) >>> c[1] tensor([2.]) >>> c[[1]] tensor([[2.]]) >>> torch.argmax(c) tensor(1) >>> d = torch.argmax(c) >>> d.squeeze(0) tensor(1) >>> d.unsqueeze(0) tensor([1]) >>> boxes = torch.tensor([[100, 100, 200, 200], [120, 120, 220, 220], [150, 150, 250, 250]]) >>> boxes[:,3]-boxes[:,1] tensor([100, 100, 100]) >>> (boxes[:,3]-boxes[:,1]) * (boxes[:,3]-boxes[:,1]) tensor([10000, 10000, 10000]) >>> areas = (boxes[:,3]-boxes[:,1]) * (boxes[:,3]-boxes[:,1]) >>> max_index = torch.argmax(areas) >>> max_index tensor(0) >>> boxes[max_index] tensor([100, 100, 200, 200]) >>> torch.nonzero(boxes[max_index] != 300) tensor([[0], [1], [2], [3]]) >>> torch.nonzero(boxes[max_index] != 300).squeeze() tensor([0, 1, 2, 3]) >>> torch.nonzero(boxes[max_index] != 300).squeeze(0) tensor([[0], [1], [2], [3]]) >>> torch.nonzero(boxes[max_index] != 300).squeeze(1) tensor([0, 1, 2, 3])
本文来自博客园,作者:海_纳百川,转载请注明原文链接:https://www.cnblogs.com/chentiao/p/17661020.html,如有侵权联系删除