无标题
张量
数组与张量
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 | import torch |
以上操作可以把数据集搬到GPU上,但是神经网络模型也要搬到GPU上
1 | # 搭建神经网络的类 |
想要查看显卡是否在运作时,在cmd中输入nvidia-smi
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Ciallo~(∠・ω< )⌒☆!





