如何在 PyTorch 中找到逐元素余数?
使用该方法计算张量除以其他张量时的元素余数。我们也可以申请求余数。torch.remainder()torch.fmod()
这两种方法的区别在于,在中,当结果的符号与除数的符号不同时,则将除数加到结果中;而在中,则没有添加。torch.remainder()torch.fmod()
语法
torch.remainder(input, other) torch.fmod(input, other)
参数
输入——它是一个PyTorch张量或标量,即股息。
其他–它也是PyTorch张量或标量,除数。
输出结果
它返回元素级余数的张量。
脚步
导入火炬库。
定义张量、被除数和除数。
计算或。它给出了剩余值的张量。torch.remainder(input,other)torch.fmod(input,other)
显示计算的余数张量。
示例1
在下面的Python程序中,我们将看到如何求张量除以标量的余数。
# Python program to find remainder using torch.remainder() # import the library import torch # define a tensor tensor1 = torch.tensor([10,-22,31,-47]) # print the created tensors print("张量1:", tensor1) print("Divisor:", 5) # compute the element-wise remainder tensor/scalar rem = torch.remainder(tensor1, 5) print("Remainder:", rem)输出结果
张量1: tensor([ 10, -22, 31, -47]) Divisor: 5 Remainder: tensor([0, 3, 1, 3])
示例2
# Python program to find remainder using torch.fmod() # import necessary libraries import torch # define a tensor tensor1 = torch.tensor([10,-22,31,-47]) # print the created tensors print("张量1:", tensor1) print("Divisor:", 5) # compute the element-wise remainder of tensor/scalar rem = torch.fmod(tensor1, 5) print("Remainder:", rem)输出结果
张量1: tensor([ 10, -22, 31, -47]) Divisor: 5 Remainder: tensor([ 0, -2, 1, -2])
请注意上述两个示例的输出之间的差异。在这两个例子中,我们有相同的输入,但我们使用不同的方法来计算余数。在示例1中,我们使用,而在示例2中,我们使用。torch.remainder()torch.fmod()
示例3
# import necessary libraries import torch # define two tensors tensor1 = torch.tensor([10,22,31,47]) tensor2 = torch.tensor([2,3,4,5]) # print the created tensors print("张量1:", tensor1) print("张量2:", tensor2) # compute the element-wise remainder of tensor1/tensor2 rem = torch.remainder(tensor1, tensor2) print("Remainder:", rem)输出结果
张量1: tensor([10, 22, 31, 47]) 张量2: tensor([2, 3, 4, 5]) Remainder: tensor([0, 1, 3, 2])
示例4
# import necessary libraries import torch # define two tensors tensor1 = torch.tensor([10.,22.,31.,47.]) tensor2 = torch.tensor([0,3,0,5]) # print the created tensors print("张量1:", tensor1) print("张量2:", tensor2) # compute the element-wise remainder of tensor1/tensor2 rem = torch.remainder(tensor1, tensor2) print("Remainder:", rem)输出结果
张量1: tensor([10., 22., 31., 47.]) 张量2: tensor([0, 3, 0, 5]) Remainder: tensor([nan, 1., nan, 2.])