登录
首页 >  文章 >  python教程

PyTorch 中的余数

时间:2025-01-17 11:37:07 135浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个文章开发实战,手把手教大家学习《PyTorch 中的余数》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

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:\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
  • 不能同时使用标量作为 inputother 参数。
  • 结果张量的符号与 other 参数的符号相同。

PyTorch 中的余数

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>