张量

数组与张量

Pytorch将Numpy数组的语法金属吸收,作为自己处理张量的基本语法,且运算速度从使用CPU的数组进步到使用GPU的张量

Numpy和Pytorch的基础语法几乎一致,具体表现为

  • np对应 torch
  • 数组 array对应张量 tensor
  • Numpy的n维数组对应Pytorch的n阶张量,数组与张量之间可以互相转换
  • 数组 arr转为张量 ts;ts = torch.tensor(arr)
  • 张量 ts转为数组 arr;arr = np.array(ts)

从数组到张量

Pytorch修正的Numpy函数或方法

位置 Numpy的函数 Pytorch的函数 用法区别
1.1 数据类型 .astype() .type() 无
2.4 随机数组 np.random.random() troch.rand() 无
2.4 随机数组 np.random.randint() torch.randint() 不接纳一维张量
2.4 随机数组 np.random.normal() torch.normal() 不接受一维张量
2.4 随机数组 np.random.randn() torch.randn() 无
3.4 数组切片 .copy() .clone() 无
4.4 数组拼接 np.concatenate() torch.cat() 无
4.5 数组分裂 np.split() torch.split() 参数含义优化
6.1 矩阵乘积 np.dot() torch.matmul() 无
6.1 矩阵乘积 np.dot(v,v) torch.dot() 无
6.1 矩阵乘积 np.dot(m,v) torch.mv 无
6.1 矩阵乘积 np.dot(m,m) torch.mm() 无
6.2 数学函数 np.exp() torch.exp() 必须传入张量
6.2 数学函数 np.log() torch.log() 必须传入张量
6.3 聚合函数 np.mean() torch.mean() 必须传入浮点型张量
6.3 聚合函数 np.std() torch.std() 必须传入浮点型张量

用GPU储存张量

默认使用CPU存储张量,可将其搬至CPU

1
2
3
4
5
6
7
import torch
# 默认张量存储在CPU上
ts1 = torch.tandn(3,4)
ts1
# 移动到GPU上
ts2 = ts1.to('cuda:0') # 第一块GPU为cuda0
ts2

以上操作可以把数据集搬到GPU上,但是神经网络模型也要搬到GPU上

1
2
3
4
5
# 搭建神经网络的类
class DNN(torch.nn.Module):
略
# 根据神经网络的类创建一个网络
model = DNN().to('cuda:0')

想要查看显卡是否在运作时,在cmd中输入nvidia-smi