如何在 PyTorch 中獲取張量的資料型別?
PyTorch 張量是同質的,即張量中的所有元素都具有相同的資料型別。我們可以透過使用張量的“.dtype” 屬性來訪問其資料型別。它將返回張量的資料型別。
步驟
匯入必需的程式碼庫。在所有以下 Python 示例中,所需的 Python 程式碼庫都為torch。確保你已安裝過它。
建立一個張量並進行列印。
計算T.dtype。此處 T 為我們需要獲取其資料型別的張量。
列印該張量的資料型別。
示例 1
以下 Python 程式展示瞭如何獲取張量的資料型別。
# Import the library
import torch
# Create a tensor of random numbers of size 3x4
T = torch.randn(3,4)
print("Original Tensor T:\n", T)
# Get the data type of above tensor
data_type = T.dtype
# Print the data type of the tensor
print("Data type of tensor T:\n", data_type)輸出
Original Tensor T: tensor([[ 2.1768, -0.1328, 0.8155, -0.7967], [ 0.1194, 1.0465, 0.0779, 0.9103], [-0.1809, 1.8085, 0.8393, -0.2463]]) Data type of tensor T: torch.float32
示例 2
# Python program to get data type of a tensor
# Import the library
import torch
# Create a tensor of random numbers of size 3x4
T = torch.Tensor([1,2,3,4])
print("Original Tensor T:\n", T)
# Get the data type of above tensor
data_type = T.dtype
# Print the data type of the tensor
print("Data type of tensor T:\n", data_type)輸出
Original Tensor T: tensor([1., 2., 3., 4.]) Data type of tensor T: torch.float32
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP