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) # 使用关键字参数指定 inputresult2 = tensor1.remainder(other=tensor2) # 使用方法调用print(f"Result 1:n{result1}n")print(f"Result 2:n{result2}n")result3 = torch.remainder(9, other=tensor2) # 标量与张量运算print(f"Result 3:n{result3}n")result4 = torch.remainder(input=tensor1, other=4) # 张量与标量运算print(f"Result 4:n{result4}n")# 负数整数张量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:n{result5}n")result6 = torch.remainder(-9, other=tensor2)print(f"Result 6:n{result6}n")result7 = torch.remainder(input=tensor1, other=4)print(f"Result 7:n{result7}n")# 浮点数张量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:n{result8}n")result9 = torch.remainder(9.75, other=tensor2)print(f"Result 9:n{result9}n")result10 = torch.remainder(input=tensor1, other=4.26)print(f"Result 10:n{result10}n")
重要说明:
other 参数不能为 0,否则会引发 ZeroDivisionError。不能同时使用标量作为 input 和 other 参数。结果张量的符号与 other 参数的符号相同。

以上就是PyTorch 中的余数的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1355247.html
微信扫一扫
支付宝扫一扫