首页 文章资讯内容详情

PyTorch – 如何计算张量的逐元素逻辑异或?

2026-06-02 1 花语

torch.logical_xor()计算给定的两个输入张量的逐元素逻辑异或。在张量中,具有零值的元素被视为False,非零元素被视为True。它以两个张量作为输入参数,并在计算逻辑异或后返回一个带有值的张量。

语法

torch.logical_xor(tensor1, tensor2)

其中tensor1tensor2是两个输入张量。

脚步

要计算给定输入张量的逐元素逻辑异或,可以按照以下步骤操作-

导入火炬库。确保您已经安装了它。

创建两个张量,tensor1tensor2,并打印张量。

计算torch.logical_xor(tesnor1,tesnor2)并将值分配给变量。

执行逐元素逻辑异或运算后打印最终结果。

示例1

# import torch library import torch # define two Boolean tensors tensor1 = torch.tensor([True, True, True, False, False]) tensor2 = torch.tensor([True, False, False, True, True]) # display the defined tensors print("Tensor 1:\n", tensor1) print("Tensor 2:\n", tensor2) # compute XOR of tensor1 and tensor2 and display tensor_xor = torch.logical_xor(tensor1, tensor2) print("XOR result:\n", tensor_xor)输出结果Tensor 1: tensor([ True, True, True, False, False]) Tensor 2: tensor([ True, False, False, True, True]) XOR result: tensor([False, True, True, True, True])

示例2

# import torch library import torch # define two tensors tensor1 = torch.tensor([True, True, True, False, False]) tensor2 = torch.tensor([1, 0, 123, 23, -12]) # display the defined tensors print("Tensor 1:\n", tensor1) print("Tensor 2:\n", tensor2) # compute XOR of tensor1 and tensor2 and display tensor_xor = torch.logical_xor(tensor1, tensor2) print("XOR result:\n", tensor_xor)输出结果Tensor 1: tensor([ True, True, True, False, False]) Tensor 2: tensor([ 1, 0, 123, 23, -12]) XOR result: tensor([False, True, False, True, True])

示例3

# import torch library import torch # define two tensors tensor1 = torch.tensor([12, 3, 11, 21, -12]) tensor2 = torch.tensor([1, 0, 123, 0, -2]) # display the defined tensors print("Tensor 1:\n", tensor1) print("Tensor 2:\n", tensor2) # compute XOR of tensor1 and tensor2 and display tensor_xor = torch.logical_xor(tensor1, tensor2) print("XOR result:\n", tensor_xor)输出结果Tensor 1: tensor([ 12, 3, 11, 21, -12]) Tensor 2: tensor([ 1, 0, 123, 0, -2]) XOR result: tensor([False, True, False, True, False])