Python – PyTorch ceil() 和 floor() 方法


一个数的上舍入值是大于或等于该数的最小整数。要找到 Torch 张量元素的上舍入值,我们使用 **torch.ceil()** 函数。此函数以 Torch 张量作为输入参数,并返回一个 Torch 张量,其中包含输入张量每个元素的 **上舍入** 值。此函数仅支持实数值输入。它支持任何维度的 Torch 张量。

一个数的下舍入值是小于或等于该数的最大整数。要找到 Torch 张量元素的下舍入值,我们使用 **torch.floor()** 函数。此函数以 **Torch** 张量作为输入参数,并返回一个 Torch 张量,其中包含输入张量每个元素的下舍入值。此函数仅支持实数值输入,并且可以支持任何维度的 Torch 张量。

语法

torch.ceil(input)
torch.floor(input)

参数

  • **input** - 它是输入张量。

输出

它返回一个包含输入张量元素的上舍入或下舍入值的张量。

步骤

您可以使用以下步骤查找包含输入张量元素的上舍入或下舍入值的张量

  • 导入所需的库。在以下所有示例中,所需的 Python 库为 **torch**。请确保您已安装它。

import torch
  • 创建一个 Torch 张量并打印该张量。

T = torch.tensor([1, 2.3, .2, 0, 4.01, 4.5, 4.99])
print("Tensor:
", T)
  • 计算 **torch.ceil(input)** 或 **torch.floor(input)** 以查找包含输入元素的上舍入或下舍入值的张量,并打印计算出的值

print("Tensor with ceil values:
",torch.ceil(T)) print("Tensor with floor values:
",torch.floor(T))

示例 1

在以下 Python 代码中,我们计算 Torch 张量元素的上舍入和下舍入值。我们已将张量的所有元素都设为正数。

# Import the required library
import torch

# define a torch tensor
T = torch.tensor([1, 2.3, .2, 0, 4.01, 4.5, 4.99])
print("Tensor:
", T) print("Tensor with ceil values:
",torch.ceil(T)) print("Tensor with floor values:
",torch.floor(T))

输出

Tensor:
   tensor([1.0000, 2.3000, 0.2000, 0.0000, 4.0100, 4.5000, 4.9900])
Tensor with ceil values:
   tensor([1., 3., 1., 0., 5., 5., 5.])
Tensor with floor values:
   tensor([1., 2., 0., 0., 4., 4., 4.])

示例 2

以下 Python 程序演示了如何查找张量元素的上舍入和下舍入值。有些元素是负数。请注意负数的上舍入和下舍入值是如何计算的。

# Import the required library
import torch
T = torch.tensor([-1, -2.3, .2, 0, -4.01, 4.5, -4.99])
print("Tensor:
", T) print("Tensor with ceil values:
",torch.ceil(T)) print("Tensor with floor values:
",torch.floor(T))

输出

Tensor:
   tensor([-1.0000, -2.3000, 0.2000, 0.0000, -4.0100, 4.5000, -4.9900])
Tensor with ceil values:
   tensor([-1., -2., 1., 0., -4., 5., -4.])
Tensor with floor values:
   tensor([-1., -3., 0., 0., -5., 4., -5.])

示例 3

在以下 Python 代码中,输入是一个二维张量。它计算张量每个元素的上舍入和下舍入值

# Import the required library
import torch
T = torch.randn(4,3)
print("Tensor:
", T) print("Tensor with ceil values:
",torch.ceil(T)) print("Tensor with floor values:
",torch.floor(T))

输出

Tensor:
   tensor([[-0.4304, -0.5405, -0.7153],
      [ 0.8230, -0.0368, -0.0357],
      [-1.3842, 0.2168, -0.0332],
      [ 0.3007, 0.2878, 0.1758]])
Tensor with ceil values:
   tensor([[-0., -0., -0.],
      [ 1., -0., -0.],
      [-1., 1., -0.],
      [ 1., 1., 1.]])
Tensor with floor values:
   tensor([[-1., -1., -1.],
      [ 0., -1., -1.],
      [-2., 0., -1.],
      [ 0., 0., 0.]])

更新于: 2022年1月20日

794 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.