PyTorch 中的余数(余数.PyTorch...)

wufei1232025-01-24python15

pytorch 的 remainder() 函数详解:高效进行模运算

本文将详细介绍 PyTorch 中 remainder() 函数的用法,它可以对张量或标量进行高效的模运算(求余数)。 一杯咖啡☕已备好,请享用!

remainder() 函数能够对两个张量或一个张量和一个标量进行逐元素的模运算,返回结果张量与输入张量形状一致。

函数参数:

  • input (Tensor or scalar): 输入张量或标量 (int 或 float 类型)。如果使用 torch 函数调用,则 input 为必需参数,且标量必须使用 input= 关键字参数指定。
  • other (Tensor or scalar): 另一个输入张量或标量 (int 或 float 类型)。 必需参数。
  • out (Tensor, optional): 输出张量。可选参数,用于指定输出张量的存储位置。

使用示例:

以下代码示例展示了 remainder() 函数在不同输入类型下的使用方法:

import torch

# 整数张量
tensor1 = torch.tensor([9, 7, 6])
tensor2 = torch.tensor([[4, -4, 3], [-2, 5, -5]])

result1 = torch.remainder(input=tensor1, other=tensor2) # 使用关键字参数指定 input
result2 = tensor1.remainder(other=tensor2) # 使用方法调用
print(f"Result 1:
{result1}
")
print(f"Result 2:
{result2}
")

result3 = torch.remainder(9, other=tensor2) # 标量与张量运算
print(f"Result 3:
{result3}
")

result4 = torch.remainder(input=tensor1, other=4) # 张量与标量运算
print(f"Result 4:
{result4}
")


# 负数整数张量
tensor1 = torch.tensor([-9, -7, -6])
tensor2 = torch.tensor([[4, -4, 3], [-2, 5, -5]])

result5 = torch.remainder(input=tensor1, other=tensor2)
print(f"Result 5:
{result5}
")

result6 = torch.remainder(-9, other=tensor2)
print(f"Result 6:
{result6}
")

result7 = torch.remainder(input=tensor1, other=4)
print(f"Result 7:
{result7}
")


# 浮点数张量
tensor1 = torch.tensor([9.75, 7.08, 6.26])
tensor2 = torch.tensor([[4.26, -4.54, 3.37], [-2.16, 5.43, -5.98]])

result8 = torch.remainder(input=tensor1, other=tensor2)
print(f"Result 8:
{result8}
")

result9 = torch.remainder(9.75, other=tensor2)
print(f"Result 9:
{result9}
")

result10 = torch.remainder(input=tensor1, other=4.26)
print(f"Result 10:
{result10}
")

重要说明:

  • other 参数不能为 0,否则会引发 ZeroDivisionError。
  • 不能同时使用标量作为 input 和 other 参数。
  • 结果张量的符号与 other 参数的符号相同。

PyTorch 中的余数

以上就是PyTorch 中的余数的详细内容,更多请关注知识资源分享宝库其它相关文章!

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。