【问题标题】:tensor equality and boolean as return value张量相等和布尔值作为返回值
【发布时间】:2019-11-15 15:27:57
【问题描述】:

所以,我在 SO 上关注了这个 answer

我试图将两个张量等同起来

torch.equal(x_valid[0], x_valid[:1]) 返回Falsetorch.all(torch.eq(x_valid[0], x_valid[:1])) 返回tensor(1, dtype=torch.uint8)

我知道两个张量都与x_valid 的第一个值相同,那么为什么torch.equal 返回False

除了x_valid[0] 返回([0, 0, ...,0])x_valid[:1] 返回([[0, 0, ...,0]])这一事实之外

但是它们的类型仍然是tensor。所以我真的不明白为什么第一个查询的输出是False

【问题讨论】:

    标签: pytorch tensor


    【解决方案1】:

    torch.equal(tensor1, tensor2) 如果两个张量具有相同的大小和元素,则返回 True,否则返回 False。检查here

    例子:

    y = torch.tensor([[0, 0, 0]])
    print(y[0], y[0].shape)
    print(y[:1], y[:1].shape)
    print(torch.equal(y[0], y[:1]))
    print(torch.equal(y[0], y[:1][0])) # (torch.Size([3]), torch.Size([3]))
    

    输出:

    tensor([0, 0, 0]) torch.Size([3])
    tensor([[0, 0, 0]]) torch.Size([1, 3])
    False
    True
    

    torch.eq(input, other, out=None) 计算元素相等性。这里需要注意的是,第二个参数可以是数字或张量,其形状为broadcastable,第一个参数。

    【讨论】:

    • 但是我的 tensor1、tensor2 在大小和元素上有何不同。是因为包含张量列表的元组和包含张量的其他实际元组吗?
    • @AbhimanyuAryan, y[:1] 有一个额外的维度。看到自己使用y[:1].size()
    猜你喜欢
    • 1970-01-01
    • 2015-04-07
    • 2014-12-13
    • 1970-01-01
    • 2018-01-24
    • 2012-08-26
    • 1970-01-01
    • 2012-12-06
    • 2013-08-18
    相关资源
    最近更新 更多