PyTorch张量检索张量,返回索引值

一、问题描述

        假设有三个张量a、b和c,其中张量a的shape为(8, 2),张量b的shape为(8, 5),张量c的shape为(1, 2)。张量a和张量b是对应的关系,并且张量a和张量b每行元素都唯一、不会重复。而我需要通过检索的方式来获得张量c在张量a中的索引(索引值大于等于0),如果没有那么就返回一个异常值(-1)。例如

a = [ [1,2],

        [2,3],

        [3,4],

        [3,8],

        [4,5],

        [4,1],

        [5,6],

        [5,5] ]

b = [ [0, 0, 0, 0, 0],

        [0, 0, 0, 0, 1],

        [0, 0, 0, 1, 0],

        [0, 0, 0, 1, 1],

        [0, 0, 1, 0, 0],

        [0, 0, 1, 0, 1],

        [0, 0, 1, 1, 0],

        [0, 0, 1, 1, 1] ]

c = [ [4,1] ]

        我想要得到张量c在张量a中的索引值5,进而得到张量b中的[0, 0, 1, 0, 1]

二、解决方法

        代码(主要是采取遍历的思想,因为实在是找不到太好的api)

import torch

# input_: a 2d tensor
# query_: a 2d tensor
# function: get the index of query_ in input_
def index_tensor_by_tensor(input_, query_):
    # default index of result
    idx = -1
    # index range of tensor2d_a
    n_a = input_.shape[0]
    # traverse tensor2d_a
    for i in range(n_a):
        if input_[i][0] == query_[0][0] and input_[i][1] == query_[0][1]:
            # find the query tensor
            idx = i
            break
    return idx

# main function
if __name__ == '__main__':
    # input
    a = torch.tensor([[1, 2],
                      [2, 3],
                      [3, 4],
                      [3, 8],
                      [4, 5],
                      [4, 1],
                      [5, 6],
                      [5, 5]])
    b = torch.tensor([[0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 1],
                      [0, 0, 0, 1, 0],
                      [0, 0, 0, 1, 1],
                      [0, 0, 1, 0, 0],
                      [0, 0, 1, 0, 1],
                      [0, 0, 1, 1, 0],
                      [0, 0, 1, 1, 1]])
    c_1 = torch.tensor([[4, 1]])    # it is exist in a
    c_2 = torch.tensor([[7, 1]])    # it is not exist in a

    # query
    res_i_1 = index_tensor_by_tensor(a, c_1)
    res_i_2 = index_tensor_by_tensor(a, c_2)

    # output
    if res_i_1 != -1:
        print(res_i_1, b.select(0, res_i_1))
    else:
        print(res_i_1, None)
    if res_i_2 != -1:
        print(res_i_2, b.select(0, res_i_2))
    else:
        print(res_i_2, None)

        效果

5 tensor([0, 0, 1, 0, 1])
-1 None

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
我们可以使用下面的代码来实现图文检索:import torch import torchvision# 加载数据集 transform = torchvision.transforms.Compose([ torchvision.transforms.Resize(224), torchvision.transforms.ToTensor() ])dataset = torchvision.datasets.ImageNet(root='./data/', split='train', transform=transform)# 定义网络 class ImageNet(torch.nn.Module): def __init__(self): super(ImageNet, self).__init__() self.conv1 = torch.nn.Conv2d(3, 16, 3, padding=1) self.conv2 = torch.nn.Conv2d(16, 32, 3, padding=1) self.fc1 = torch.nn.Linear(32 * 7 * 7, 256) self.fc2 = torch.nn.Linear(256, 10) def forward(self, x): x = torch.nn.functional.relu(self.conv1(x)) x = torch.nn.functional.max_pool2d(x, 2, 2) x = torch.nn.functional.relu(self.conv2(x)) x = torch.nn.functional.max_pool2d(x, 2, 2) x = x.view(-1, 32 * 7 * 7) x = torch.nn.functional.relu(self.fc1(x)) x = self.fc2(x) return x# 初始化模型 model = ImageNet()# 定义损失函数和优化器 criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)# 训练模型 for epoch in range(2): running_loss = 0.0 for i, data in enumerate(dataset): # 获取输入 inputs, labels = data # 梯度清零 optimizer.zero_grad() # forward + backward outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # 打印log running_loss += loss.item() if i % 2000 == 1999: print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training')

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞机火车巴雷特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值