由于numpy比较基础和通用,但是GPU上跑实验必须使用tensor,故还是直接用torch里面的函数更加直接快速,其两者直接的对比整理如下:
import numpy as np import torch
| 用途 | numpy | torch |
|---|---|---|
| 随机整数 | np.random.randint(0,2,(4,3)) | torch.empty(4,3).random_(0,2) |
| [0,1)均匀分布 | np.random.rand(3,4) | torch.rand(3,4) |
| 任意均匀分布 | np.random.uniform(-1,1,(3,4)) | torch.empty(3,4).uniform_(-1,1) |
| 标准正态分布 | np.random.randn(3,4) | torch.randn(3, 4) |
| 任意正态分布( μ , σ 2 mu,sigma^2 μ,σ2) | σ sigma σ*np.random.randn(3,4)+ μ mu μ | σ sigma σ*torch.randn(3, 4)+ μ mu μ |
| 全0矩阵 | np.zeros((3,4)) | torch.zeros(3,4) |
| 全1矩阵 | np.ones((3,4)) | torch.ones(3,4) |
| 单位矩阵 | np.identity(3) | torch.eye(3) |
| 向量点积 | np.dot(a,b) | torch.dot(a,b) |
| 转置 | a.T | a.T |
| 矩阵相乘 | np.matmul(a,b) | torch.matmul(a,b) |
| 布尔值有真 | np.any(a) | torch.any(a) |
| 布尔值皆真 | np.all(a) | torch.all(a) |



