PyTorch – 如何計算張量的逐元素邏輯異或?
**torch.logical_xor()** 計算給定的兩個輸入張量的逐元素邏輯異或。在張量中,值為零的元素被視為 False,非零元素被視為 True。它接受兩個張量作為輸入引數,並返回計算邏輯異或後的值組成的張量。
語法
torch.logical_xor(tensor1, tensor2)
其中 **tensor1** 和 **tensor2** 是兩個輸入張量。
步驟
要計算給定輸入張量的逐元素邏輯異或,可以按照以下步驟操作:
匯入 **torch** 庫。確保你已經安裝了它。
建立兩個張量,**tensor1** 和 **tensor2**,並列印這些張量。
計算 **torch.logical_xor(tensor1, tensor2)** 並將值賦給一個變數。
執行逐元素邏輯異或運算後,列印最終結果。
示例 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:
", tensor1) print("Tensor 2:
", tensor2) # compute XOR of tensor1 and tensor2 and display tensor_xor = torch.logical_xor(tensor1, tensor2) print("XOR result:
", 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:
", tensor1) print("Tensor 2:
", tensor2) # compute XOR of tensor1 and tensor2 and display tensor_xor = torch.logical_xor(tensor1, tensor2) print("XOR result:
", 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:
", tensor1) print("Tensor 2:
", tensor2) # compute XOR of tensor1 and tensor2 and display tensor_xor = torch.logical_xor(tensor1, tensor2) print("XOR result:
", 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])
廣告