一、张量的创建与类型
张量最基本创建方法和Numpy
中创建Array
的格式一致,都是创建函数的格式。
1.1 通过列表创建
t = torch.tensor([1, 2])
print(t)
# tensor([1, 2])
1.2 通过元组创建
t = torch.tensor((1, 2))
print(t)
# tensor([1, 2])
1.3 通过Numpy
创建
import numpy as np
n = np.array([1, 2])
t = torch.tensor(n)
print(t)
# tensor([1, 2])
1.4 张量的类型
i = torch.tensor([1, 2])
f = torch.tensor([1.0, 2.0])
print(type(i), i.dtype, sep = ' , ')
print(type(f), f.dtype, sep = ' , ')
# <class 'torch.Tensor'> , torch.int64
# <class 'torch.Tensor'> , torch.float32
1.5 张量类型的转化方法
t = torch.tensor([1, 2])
f = t.float()
print(f)
print(t)
# tensor([1., 2.])
# tensor([1, 2])
二、张量的维度
# 一维向量
t1 = torch.tensor((1, 2))
# 二维向量
t2 = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 三维向量
t3 = torch.tensor([[[1, 2], [3, 4]],[[5, 6], [7, 8]]])
2.1 ndim
查看张量维度
print(t1.ndim, t2.ndim, t3.ndim, sep = ', ')
# 1, 2, 3
# t1为1维向量
# t2为2维矩阵
# t3为3维张量
2.2 shape&size
查看向量的形状
-
print(t1.shape, t2.shape, t3.shape, sep = ', ')
-
# torch.Size([2]), torch.Size([2, 3]), torch.Size([2, 2, 2])
-
print(t1.size(), t2.size(), t3.size(), sep = ', ')
-
# torch.Size([2]), torch.Size([2, 3]), torch.Size([2, 2, 2])
t1
向量torch.Size([2])
的理解:向量的形状是1行2列。
t2
矩阵torch.Size([2, 3])
的理解:包含两个一维向量,每个一维向量的形状是1行3列。
t3
矩阵torch.Size([2, 2, 2])
的理解:包含两个二维矩阵,每个二维矩阵的形状是2行2列。
2.3 numel
查看张量中的元素个数
print(t1.numel(), t2.numel(), t3.numel(), sep = ', ')
# 2, 6, 8
# t1向量中共有2个元素
# t2矩阵中共有6个元素
# t3张量中共有8个元素
2.4 flatten
将任意维度张量转为一维张量
t2.flatten()
# tensor([1, 2, 3, 4, 5, 6])
t3.flatten()
# tensor([1, 2, 3, 4, 5, 6, 7, 8])
2.5 reshape
任意变形
形变维度的乘积需要等于张量元素的个数。
# 将`t3`变成2×4的矩阵
t3.reshape(2, 4)
#tensor([[1, 2, 3, 4],[5, 6, 7, 8]])
# 将`t3`变成1×4×2的矩阵
t3.reshape(1, 4, 2)
# tensor([[[1, 2], [3, 4], [5, 6], [7, 8]]])
2.6 squeeze
&unsqueeze
-
squeeze
的作用是压缩张量,去掉维数为1位置的维度
# 将t3的维度变为2×1×4
t_214 = t3.reshape(2, 1, 4)
print(t_214)
# tensor([[[1, 2, 3, 4]], [[5, 6, 7, 8]]])
# 使用squeeze将其变成2×4,去掉维度为1位置的维度
t_24 = t_214.squeeze(1)
print(t_24)
# tensor([[1, 2, 3, 4], [5, 6, 7, 8]])