1、torch的属性
假设y是tensor类型张量
方法 | 作用 | 示例 |
---|
is_tensor | 张量是tensor类型返回True | torch.is_tensor(y) |
numel | 返回输入张量元素的总数 | y.numel() |
shape | 返回输入张量的形状 | y.size() |
size | 返回输入张量的形状 | y.shape |
dtype | 返回输入张量元素的类型 | y.dtype |
2、创建torch的操作(⭐为最常用)
方法 | 作用 | 示例 |
---|
⭐tensor | 用输入数据创建张量(同np的array方法) | torch.tensor([[1,2],[3,4]]) |
as_tensor | 将数据转变为张量 | torch.as_tensor(x) |
from_numpy | 从numpy.ndarray类型创建张量 | torch.from_numpy(x) |
⭐zeros | 返回全0张量,形状为参数 | torch.zeros(3,4) |
zeros_like | 返回和输入形状一样的全0张量 | torch.zeros_like(x.shape) |
⭐ones | 返回全1张量,形状为参数 | torch.ones(3,4) |
ones_like | 返回和输入形状一样的全1张量 | torch.ones_like(x.shape) |
⭐arange | 生成数值为范围内数的张量 | torch.arange(12).reshape(3,4) |
range | 类似arange | torch.range(0,12,2) |
linspace | 生成一维张量,从strat到end均分为step份 | torch.linspace(0,12,10) |
eye | 生成主对角线都是1的张量矩阵 | torch.eye(4,4) |
3、torch的变换操作
方法 | 作用 | 示例 |
---|
cat | 在规定维度上连接两个张量 | torch.cat((x,y),dim=0) |
reshape | 重塑张量形状 | x.reshape(3,4) |
T | 转置 | x.T |
take | 将张量展平,取出对应索引的张量组成新的张量 | torch.take(y,torch.tensor([0,1])) |
item | 将张量转换为标量(类似asscalar) | x.item() |
4、torch的随机数生成
方法 | 作用 | 示例 |
---|
normal | 正态分布 | torch.normal(mean=0,std=1,size=(3,4)) |
randn | 标准正态分布 | torch.randn(size=(3,4)) |
randint | 随机整数 | torch.randint(0,12,size=(3,4)) |
rand | 0-1上均匀分布 | torch.rand(size=(3,4)) |
5、torch的数学操作
方法 | 作用 | 示例 |
---|
abs | 各元素绝对值 | torch.tensor([[1,2],[3,4]]) |
exp | 各元素指数 | torch.as_tensor(x) |
log | 各元素log2 | torch.from_numpy(x) |
log10 | 各元素log10 | 单元格 |
6、torch的梯度操作
张量是否保留梯度信息由torch.no_grad(), torch.enable_grad(), and torch.set_grad_enabled()
等决定.
1、在梯度计算前要有保存梯度的地方
x.attach_grad()
x.requires_grad_(True)
2、计算y
with autograd.record():
y = net(x)
y.backward()
y = net(x)
梯度信息此时已保留在x.grad
中
7、torch的取值操作
通过指定axis=0,可以让其在维度0上进行相应操作
方法 | 作用 |
---|
argmax | Returns the indices of the maximum value of all elements in the input tensor. |
argmin | Returns the indices of the minimum value(s) of the flattened tensor or along a dimension |
max | Returns the maximum value of all elements in the input tensor. |
mean | Returns the mean value of all elements in the input tensor. |
norm | Returns the matrix norm or vector norm of a given tensor. |
sum | Returns the sum of all elements in the input tensor. |