PyTorch中的张量
目标
通过本篇文章的学习,你将学习到PyTorch张量模块中第一部分内容,包含以下内容:
- 张量的数据类型——查看张量的数据类型、重新设置张量的默认数据类型及其转换、获取张量的默认数据类型
- 张量的生成——
torch.tensor()
生成、torch.Tensor()
生成、张量和NumPy数据互相转换、随机数生成张量、其他生成张量的函数等
1. 什么是张量
在数学中,一个单独的数可以称为标量,一列或者一行数组可以称为向量,一个二维数组称为矩阵,矩阵中的每一个元素都可以被行和列的索引唯一确定,但如果一个数组的维度超过2,那么我们可以称该数组为张量(Tensor)。
Tips:
- 在PyTorch中,张量属于一种数据结构,它可以是一个标量、一个向量、一个矩阵,甚至是更高维度的数组,因此PyTorch中的张量(Tensor)和Numpy中的数组(ndarray)非常相似,在使用时也会经常将PyTorch中的张量和Numpy中的数组相互转化。
- 在深度网络中,基于PyTorch的相关计算和优化都是在Tensor的基础上完成的。
2. 张量的数据类型
2.1 张量的数据类型
在torch中CPU和GPU张量分别有8种数据类型,如下表1所示。
Data type | dtype | CPU Tensor | GPU Tensor |
---|---|---|---|
32-bit floating point | torch.float32 or torch.float | torch.FloatTensor | torch.cuda.FloatTensor |
64-bit floating point | torch.float64 or torch.double | torch.DoubleTensor | torch.cuda.DoubleTensor |
16-bit floating point | torch.float16 or torch.half | torch.HalfTensor | torch.cuda.HalfTensor |
8-bit integer (unsigned) | torch.uint8 | torch.ByteTensor | torch.cuda.ByteTensor |
8-bit integer (signed) | torch.int8 | torch.CharTensor | torch.cuda.CharTensor |
16-bit integer (signed) | torch.int16 or torch.short | torch.ShortTensor | torch.cuda.ShortTensor |
32-bit integer (signed) | torch.int32 or torch.int | torch.IntTensor | torch.cuda.IntTensor |
64-bit integer (signed) | torch.int64 or torch.long | torch.LongTensor | torch.cuda.LongTensor |
注意: 在torch中默认的数据类型是32位浮点型(torch.FloatTensor)。
2.2 张量的数据类型查看及转换
可以通过torch.set_default_tensor_type()
函数设置默认的数据类型,但是该函数只支持设置浮点型数据类型,下面使用程序演示如何查看和设置张量的数据类型。
2.2.1 查看张量的数据类型
# 导入所需要的库
import torch
print(torch.tensor([1.2, 2.2]).dtype)
>>>torch.float32
torch.tensor()
函数生成一个张量,使用.dtype
方法查看张量的数据类型,结果为32位浮点型。
2.2.2 重新设置张量的默认数据类型及其转换
# 将张量的默认数据类型设置为其它类型
# torch.set_default_tensor_type()函数只支持设置浮点型数据类型
torch.set_default_tensor_type(torch.DoubleTensor)
print(torch.tensor([1.2, 2.2]).dtype)
>>>torch.float64
# 将张量的默认数据类型转化为其他数据类型
a = torch.tensor([1.2, 2.2])
print("a.dtype:", a.dtype)
print("a.long()方法:", a.long().dtype)
print("a.int()方法:", a.int().dtype)
print("a.float()方法:", a.float().dtype)
>>>a.dtype: torch.float64
>>>a.long(): torch.int64
>>>a.int(): torch.int32
>>>a.float(): torch.float32
Tips: 由于已经重新设置过张量的默认数据类型为
64-bit floating point
,所以生成张量a
的数据类型a.dtype
为float64
。
2.2.3 获取张量的默认数据类型
# 恢复torch默认的数据类型
torch.set_default_tensor_type(torch.FloatTensor)
print(torch.tensor([1.2, 2.2]).dtype)
>>>torch.float32
# 使用torch.get_default_dtype()获取默认的数据类型
print(torch.get_default_dtype())
>>>torch.float32
从张量的.dtype
方法输出结果为torch.float32
可知,已经将默认的数据类型恢复为32位浮点型。
Tips:
torch.set_default_tensor_type()
与torch.get_default_dtype()
是有区别的,请不要记混淆了。
3. 张量的生成
3.1 torch.tensor()函数生成张量
(1)Python列表或序列可以通过torch.tensor()
函数构造张量
A = torch.tensor([[1.0, 1.0], [2.0, 2.0]])
print(A)
>>>tensor([[1., 1.],
[2., 2.]])
(2)查看张量的维度.shape
、大小.size()
和元素数量.numel()
# 获取张量的维度
print("A的维度为:", A.shape)
# 获取张量的形状大小
print("A的形状大小为:", A.size())
# 计算张量中包含元素的数量
print("A的元素数量为:", A.numel())
>>>A的维度为: torch.Size([2, 2])
>>>A的形状大小为: torch.Size([2, 2]