pytorch数学操作

作者 : admin 本文共2140个字,预计阅读时间需要6分钟 发布时间: 2024-06-5 共2人阅读

文章目录

    • 1.torch.bitwise_not()
    • 2.torch.bitwise_and()
    • 3.torch.ceil()
    • 3.torch.clamp()
    • 4.torch.torch.floor()

1.torch.bitwise_not()

在 PyTorch 中,torch.bitwise_not() 是一个函数,用于执行逐元素的位非(bitwise NOT)操作。

torch.bitwise_not(input, out=None)
"""
input:输入张量。
out:可选参数,输出张量。
"""
import torch

x = torch.tensor([5, 2, 7], dtype=torch.uint8)

y = torch.bitwise_not(x)

print(y)
tensor([250, 253, 248], dtype=torch.uint8)

当我们使用 torch.bitwise_not() 函数时,它会对输入张量中的每个元素执行位非(bitwise NOT)操作。位非操作是对二进制表示的每一位进行取反的操作,即将 0 变为 1,将 1 变为 0。

例如,如果我们有一个输入张量 x 包含了整数值 [5, 2, 7],这些值的二进制表示分别是 [101, 010, 111]。使用 torch.bitwise_not() 函数对 x 进行位非操作,得到的结果张量 y 的元素将是对应位置上的二进制取反结果。

在示例中,输出张量 y 包含了 [250, 253, 248],这些值的二进制表示分别是 [11111010, 11111101, 11111000]。可以观察到,每个元素的二进制表示中的每一位都被取反。

需要注意的是,输入张量的数据类型对位非操作有影响。在示例中,我们使用了无符号8位整数 (torch.uint8) 的输入张量 x。位非操作会在每个元素的二进制表示中逐位取反,并且结果张量 y 的数据类型仍然是无符号8位整数 (torch.uint8)。

2.torch.bitwise_and()

在 PyTorch 中,torch.bitwise_and() 是一个函数,用于执行逐元素的位与(bitwise AND)操作。

torch.bitwise_and(input, other, out=None)
"""
input:第一个输入张量。
other:第二个输入张量。
out:可选参数,输出张量。
"""
import torch

x = torch.tensor([5, 3, 7], dtype=torch.uint8)
y = torch.tensor([3, 6, 5], dtype=torch.uint8)

z = torch.bitwise_and(x, y)

print(z)
tensor([1, 2, 5], dtype=torch.uint8)

在这个示例中,我们使用 torch.bitwise_and() 函数对张量 x 和 y 中的元素执行位与操作。输入张量 x 和 y 包含了无符号8位整数。torch.bitwise_and() 函数将 x 和 y 对应位置上的元素进行位与操作,得到了结果张量 z。

需要注意的是,位与操作将每个元素的二进制表示的对应位进行逻辑与操作,只有当对应位都为 1 时,结果位才为 1,否则为 0。输出张量 z 的数据类型与输入张量 x 和 y 相同。

3.torch.ceil()

在 PyTorch 中,torch.ceil() 函数用于执行逐元素的向上取整操作。它返回一个新的张量,其中的元素是输入张量中对应元素的向上取整结果。

torch.ceil(input, out=None)
"""
input:输入张量。
out:可选参数,输出张量。
"""
import torch

x = torch.tensor([1.2, 2.7, 3.5, 4.9])

y = torch.ceil(x)

print(y)
tensor([2., 3., 4., 5.])

3.torch.clamp()

在 PyTorch 中,torch.clamp() 函数用于对张量进行截断操作,将张量中的元素限制在指定范围内。它返回一个新的张量,其中的元素被限制在给定的范围内。

torch.clamp(input, min, max, out=None)
"""
input:输入张量。
min:指定的最小值,小于该值的元素会被替换为该值。
max:指定的最大值,大于该值的元素会被替换为该值。
out:可选参数,输出张量。
"""
返回值是一个新的张量,其元素被截断在 [min, max] 的范围内。
import torch

x = torch.tensor([1.2, -0.5, 3.7, 2.8])

y = torch.clamp(x, min=0, max=2)

print(y)
tensor([1.2000, 0.0000, 2.0000, 2.0000])

4.torch.torch.floor()

在 PyTorch 中,torch.floor() 函数用于执行逐元素的向下取整操作。它返回一个新的张量,其中的元素是输入张量中对应元素的向下取整结果。

torch.floor(input, out=None)
"""
input:输入张量。
out:可选参数,输出张量。
"""
import torch

x = torch.tensor([1.2, 2.7, 3.5, 4.9])

y = torch.floor(x)

print(y)
tensor([1., 2., 3., 4.])
本站无任何商业行为
个人在线分享 » pytorch数学操作
E-->