关于深度学习的基础的Python知识(PyTorch)
一、概念:张量
1、张量的定义:
张量是矩阵的扩展与延伸,可以认为是高阶的矩阵。1阶张量为向量,2阶张量为矩阵。张量是类似于Numpy的多维数组(ndarray)的概念,可以具有任意多的维度。
(图片来自邱锡鹏老师和飞桨的《神经网络与深度学习:案例与实践》)
2、个人理解:
张量是用向量组成的维度空间的实体,可以很方便地存放各式各样的信息。
二.、使用PyTorch实现张量运算
首先导入torch
:
import torch
1、创建张量
(1)以指定数据创建张量(以三阶张量为例)
# 创建一个三阶张量(指定数据创建张量)
ndim_1_Tensor = torch.tensor([[[1, 9], [6, 3]], [[0, 1], [2, 8]]])
print(ndim_1_Tensor)
运行结果:
(2)指定形状创建张量
# 指定形状创建
size = ndim_1_Tensor.size()
zero_Tensor = torch.zeros(size) # 全零张量
print(zero_Tensor)
one_Tensor = torch.ones(size) # 全一张量
print(one_Tensor)
full_Tensor = torch.full(size, 10) #指定数据
print(full_Tensor)
运行结果:
2、张量的属性
(1)张量的形状属性
张量具有如下形状属性:
Tensor.ndim
:张量的维度,例如向量的维度为1,矩阵的维度为2。Tensor.shape
: 张量每个维度上元素的数量。Tensor.shape[n]
:张量第n维的大小。第n维也称为轴(axis)。Tensor.numel()
:张量中全部元素的个数。(paddle
中为Tensor.size
)
(图片来自邱锡鹏老师和飞桨的《神经网络与深度学习:案例与实践》)
创建如图张量:
ndim_4_Tensor = torch.ones([2, 3, 4, 5]) # 创建一个每个维度的宽度分别为2,3,4,5的4维张量
打印出此向量的shape
、ndim
、shape[n]
、numel()
属性:
# 打印出此向量的`shape`、`ndim`、`shape[n]`、`numel()`属性
print("shape:", ndim_4_Tensor.shape)
print("ndim:", ndim_4_Tensor.ndim)
print("shape[2]:", ndim_4_Tensor.shape[1])
print("numel:", ndim_4_Tensor.numel())
运行结果:
(2)张量形状的改变
在实际使用中,还可以通过使用torch.reshape
接口来改变张量的形状:
ndim_3_Tensor = torch.tensor([[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]],
[[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]],
[[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30]]])
print("shape:", ndim_3_Tensor.shape)
# 改变数据形状
reshape_Tensor = torch.reshape(ndim_3_Tensor, [2, 5, 3])
print("After reshape:", reshape_Tensor)
运行结果:
可以看到,通过此接口改变张量的形状后,张量内部的数据顺序是不变的。
除使用torch.reshape
进行张量形状的改变外,还可以通过torch.unsqueeze
将张量中的某一维度中插入尺寸为1的维度:
ones_Tensor = torch.ones([5, 10])
new_Tensor1 = torch.unsqueeze(ones_Tensor, dim=0)
print('new shape: ', new_Tensor1.shape)
运行结果
其他技巧:
将reshape
值设为-1
,使张量变为一维:
new_Tensor1