@TOC
一、张量(Tensor)的基本创建及其类型
1.张量(Tensor)函数创建方法
张量创建函数:torch.tensor()
# 通过列表创建张量
t = torch.tensor([1, 2])
# 通过元组创建张量
torch.tensor((1, 2))
import numpy as np
a = np.array((1, 2))
# 通过数组创建张量
t1 = torch.tensor(a)
# 创建int16整型张量
torch.tensor([1.1, 2.7], dtype = torch.int16)
2.张量的类型
t.dtype # torch.int64
t1.dtype # torch.int32
张量则默认创建int64(长整型)类型,整数型的数组默认创建int32(整型)类型。
torch.tensor(np.array([1.1, 2.2])).dtype # torch.float64
torch.tensor([1.11, 2.2]).dtype # torch.float32
创建浮点型数组时,张量默认是float32(单精度浮点型),而Array则是默认float64(双精度浮点型)。
3.张量类型的转化
张量类型的隐式转化
和NumPy中array相同,当张量各元素属于不同类型时,系统会自动进行隐式转化。
# 浮点型和整数型的隐式转化
torch.tensor([1.1, 2]).dtype
# 布尔型和数值型的隐式转化
torch.tensor([True, 2.0])
张量类型的转化方法
可以使用.float()、.int()等方法对张量类型进行转化
# 通过列表创建张量
t = torch.tensor([1, 2])
# 转化为默认浮点型(32位)
t.float()
当在torch函数中使用dtype参数时候,需要输入torch.float表示精度;
在使用方法进行类型转化时,方法名称则是double。(虽然torch.float和double都表示双精度浮点型。)
二、张量的维度与形变
t1 = torch.tensor([1, 2])
# 使用ndim属性查看张量的维度
t1.ndim # 1
# 使用shape查看形状
t1.shape # torch.Size([2])
# 和size函数相同
t1.size() #torch.Size([2])
# 返回拥有几个(N-1)维元素
len(t1) # 2
# 返回总共拥有几个元素
t1.numel() # 2
零维张量
t = torch.tensor(1)
t.ndim # 0
t.shape # torch.Size([])
t.numel() # 1
张量的形变
flatten拉平:将任意维度张量转化为一维张量
t2 = torch.tensor([[1, 2], [3, 4]])
t2.flatten() # tensor([1, 2, 3, 4])
注:如果将零维张量使用flatten,则会将其转化为一维张量。
reshape方法:任意变形
t1 = torch.tensor([1, 2])
# 转化为两行、一列的向量
t1.reshape(2, 1)
t1.reshape(2, 1).ndim # 2
张量维度变换
通过reshape方法,能够灵活调整张量的形状。而在实际操作张量进行计算时,往往需要另外进行降维和升维的操作,当我们需要除去不必要的维度时,可以使用squeeze函数,而需要手动升维时,则可采用unsqueeze函数。
squeeze函数:删除不必要的维度
简单理解,squeeze就相当于剔除了shape返回结果中的1
t = torch.zeros(1, 1, 3, 1)
t.shape
torch.squeeze(t)
torch.squeeze(t).shape # torch.Size([3])
unsqeeze函数:手动升维
t = torch.zeros(1, 2, 1, 2)
torch.unsqueeze(t, dim = 0) # 在第1个维度索引上升高1个维度
torch.unsqueeze(t, dim = 2).shape # 在第3个维度索引上升高1个维度
torch.unsqueeze(t, dim = 4).shape # 在第5个维度索引上升高1个维度
三、张量(Tensor)和其他相关类型之间的转化方法
张量、数组和列表是较为相似的三种类型对象,在实际操作过程中,经常会涉及三种对象的相互转化。torch.tensor函数可以直接将数组或者列表转化为张量,而我们也可以将张量转化为数组或者列表。
.numpy方法:张量转化为数组
t1 = torch.arange(1,11) # tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
t1.numpy() # array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=int64)
# 当然,也可以通过np.array函数直接转化为array
np.array(t1) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=int64)
.tolist方法:张量转化为列表
t1 = torch.arange(1,11) # tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
t1.tolist() # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.item()方法:转化为数值
n = torch.tensor(10) # tensor(10)
n.item() # 10