a np.array([2,3.3]) # 创建一个一行两列的数组 # output [2. 3.3] b torch.from_numpy(a) # 转化为 tensor # output tensor([2.0000, 3.3000], dtype torch.float64) c b.numpy() # 将 tensor 转化为数组 # output [2. 3.3]tensor 的维度查看 tensor.shape tensor.size()
a torch.Tensor([[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]) print(a.shape) # output torch.Size([4, 4]) print(a.size()) # output torch.Size([4, 4])tensor 的数据随机生成 torch.rand() and torch.randn()
a torch.rand(size (2,3)) # 包含了从区间[0, 1)的均匀分布中抽取的一组随机数 b torch.randn(size (2,3)) # 包含了从标准正态分布 均值为0 方差为1 中抽取的一组随机数 # size 为这个 tensor 的维度tensor 的维度变换 tensor.reshape() and tensor.view()
a torch.randn(size (4,1,28,28)) a.shape # output torch.Size([4, 1, 28, 28]) b a.view(4,28*28) b.shape # output torch.Size([4, 784]) c a.reshape(4,784) c.shape # output torch.Size([4, 784]) 如果要将一个 tensor 打平 打平成一维的 d a.reshape(-1) d.shape # output torch.Size([3136]) e a.view(-1) e.sh ape # output torch.Size([3136])tensor 添加维度 及 减少维度 tensor.unsqueeze() and tensor.squeeze()
a torch.rand(szie (4,1,28,28)) print(a.unsqueeze(0).shape) print(a.unsqueeze(1).shape) print(a.unsqueeze(2).shape) print(a.unsqueeze(3).shape) print(a.unsqueeze(4).shape) # output torch.Size([1, 4, 1, 28, 28]) # 在 0 维度添加一个维度 torch.Size([4, 1, 1, 28, 28]) # 在 1 维度添加一个维度 torch.Size([4, 1, 1, 28, 28]) # 在 2 维度添加一个维度 torch.Size([4, 1, 28, 1, 28]) # 在 3 维度添加一个维度 torch.Size([4, 1, 28, 28, 1]) # 在 4 维度添加一个维度 a torch.rand(size (1,32,1,1)) print(a.squeeze().shape) # 如果 squeeze 中什么参数不填 就默认将所有维度为 1 的 进行去除 # output torch.Size([32]) print(a.squeeze(2).shape) # output torch.Size([1, 32, 1])tensor 的维度扩增 tensor.expand() and tensor.repeat()
# expand 不会分配新的内存 只是在存在的张量上创建一个新的视图 一个大小等于1的维度扩展到更大的尺寸 # tensor.expand() 仅仅针对于维度为 1 的进行变化 参数中的 -1 代表这个维度不发生变化 a torch.rand(size (2,3,1)) b a.expand(32,-1,-1,5) b.shape # output torch.Size([32, 2, 3, 5]) # 沿着特定的维度重复这个张量 这个函数重新分配内存 # tensor.repeat() 里面的参数是每个维度扩增的倍数 这个参数的维度和 a 的维度一致 a torch.rand(size (1,32,1,1)) b a.repeat(4,32,1,1) print(b.shape) # output torch.Size([4, 1024, 1, 1])2 维的 tensor 矩阵 的转置 tensor.t()
# tensor.t() 是对矩阵进行转置 即行变列 列变行 a torch.Tensor([[1,2,3,4],[5,6,7,8]]) print(a) # output tensor([[1., 2., 3., 4.], [5., 6., 7., 8.]]) print(a.t()) # output tensor([[1., 5.], [2., 6.], [3., 7.], [4., 8.]])tensor 交换维度 (tensor.transpose())
注意 一次只能交换两个维度 交换多个维度会报错 如果交换多个维度 请使用 tensor.permute()
a torch.rand(size (2,3,4)) print(a.shape) # output torch.Size([2, 3, 4]) print(a.transpose(0,1).shape) # output torch.Size([3, 2, 4]) print(a.permute(2,1,0).shape) # output torch.Size([4, 3, 2])



