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.]])
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP