PyTorch:高效比较张量并构建Other列表
PyTorch:高效比较张量并构建Other列表
你想判断 tensor_list[i] 是否与 label_list 中的任何张量相同,并将不同的张量添加到 other_list 中吗?以下是一些可以优化代码的方法:
**原始代码:**pythontarget_similarity = F.cosine_similarity(output, tensor_list[i].unsqueeze(0), dim=1)label_list = [torch.tensor([1, 0, 0, 0]), torch.tensor([0, 1, 0, 0]), torch.tensor([0, 0, 1, 0]), torch.tensor([1, 1, 1, 1])]
other_list = []for label_tensor in label_list: if not torch.all(torch.eq(tensor_list[i], label_tensor)): other_list.append(label_tensor)
打印不是标签的其他张量print(other_list)
**优化后的代码:**pythonimport torchimport torch.nn.functional as F
假设 tensor_list 和 output 已经定义tensor_list = [torch.tensor([1, 0, 0, 0]), torch.tensor([0, 1, 0, 0]), torch.tensor([0, 0, 0, 1]), torch.tensor([1, 1, 1, 1])]output = torch.randn(4)
label_list = [torch.tensor([1, 0, 0, 0]), torch.tensor([0, 1, 0, 0]), torch.tensor([0, 0, 1, 0]), torch.tensor([1, 1, 1, 1])]
使用列表推导式简化代码i = 0 # 假设你想检查 tensor_list 中的第一个张量other_list = [label_tensor for label_tensor in label_list if not torch.all(torch.eq(tensor_list[i], label_tensor))]
打印不是标签的其他张量print(other_list)
代码解释:
-
计算
target_similarity: 这行代码使用F.cosine_similarity计算output和tensor_list[i]之间的余弦相似度。这部分代码与你的目标无关,可以删除。 -
定义
label_list: 这行代码定义了一个包含四个张量的列表。 -
高效构建
other_list: 使用列表推导式,我们可以简洁地迭代label_list并仅保留与tensor_list[i]不相等的张量。 -
打印结果: 最后,打印
other_list,其中包含与tensor_list[i]不匹配的所有张量。
优势:
- 代码简洁性: 使用列表推导式使代码更易读和理解。- 效率: 列表推导式通常比传统的
for循环更高效。
希望这个优化后的代码能够帮助你!
原文地址: https://www.cveoy.top/t/topic/Mqk 著作权归作者所有。请勿转载和采集!