如何在PyTorch中查詢元素級餘數?
當張量除以另一個張量時,可以使用 **torch.remainder()** 方法計算元素級的餘數。我們也可以使用 **torch.fmod()** 來查詢餘數。
這兩種方法的區別在於,在 **torch.remainder()** 中,如果結果的符號與除數的符號不同,則將除數新增到結果中;而在 **torch.fmod()** 中,則不會新增。
語法
torch.remainder(input, other) torch.fmod(input, other)
引數
**輸入 (Input)** – 它是PyTorch張量或標量,即 **被除數**。
**其他 (Other)** – 它也是PyTorch張量或標量,即 **除數**。
輸出
它返回一個包含元素級餘數值的張量。
步驟
匯入torch庫。
定義張量,即被除數和除數。
計算 **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("Tensor 1:", tensor1)
print("Divisor:", 5)
# compute the element-wise remainder tensor/scalar
rem = torch.remainder(tensor1, 5)
print("Remainder:", rem)輸出
Tensor 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("Tensor 1:", tensor1)
print("Divisor:", 5)
# compute the element-wise remainder of tensor/scalar
rem = torch.fmod(tensor1, 5)
print("Remainder:", rem)輸出
Tensor 1: tensor([ 10, -22, 31, -47]) Divisor: 5 Remainder: tensor([ 0, -2, 1, -2])
注意上面兩個示例輸出的區別。在這兩個示例中,我們使用了相同的輸入,但使用了不同的方法來計算餘數。在示例1中,我們使用 **torch.remainder()**,而在示例2中,我們使用 **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("Tensor 1:", tensor1)
print("Tensor 2:", tensor2)
# compute the element-wise remainder of tensor1/tensor2
rem = torch.remainder(tensor1, tensor2)
print("Remainder:", rem)輸出
Tensor 1: tensor([10, 22, 31, 47]) Tensor 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("Tensor 1:", tensor1)
print("Tensor 2:", tensor2)
# compute the element-wise remainder of tensor1/tensor2
rem = torch.remainder(tensor1, tensor2)
print("Remainder:", rem)輸出
Tensor 1: tensor([10., 22., 31., 47.]) Tensor 2: tensor([0, 3, 0, 5]) Remainder: tensor([nan, 1., nan, 2.])
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP