在pytorch中怎么使用 \
1、1.1 PyTorch 张量
PyTorch 的关键数据结构是张量,即多维数组。其功能与 NumPy 的 ndarray 对象类似,如下我们可以使用 torch.Tensor() 创建张量。
# Generate a 2-D pytorch tensor (i.e., a matrix)pytorch_tensor = torch.Tensor(10, 20)print("type: ", type(pytorch_tensor), " and size: ", pytorch_tensor.shape )
如果你需要一个兼容 NumPy 的表征,或者你想从现有的 NumPy 对象中创建一个 PyTorch 张量,那么就很简单了。
# Convert the pytorch tensor to a numpy array:numpy_tensor = pytorch_tensor.numpy()print("type: ", type(numpy_tensor), " and size: ", numpy_tensor.shape) # Convert the numpy array to Pytorch Tensor:print("type: ", type(torch.Tensor(numpy_tensor)), " and size: ", torch.Tensor(numpy_tensor).shape)

2、1.2 PyTorch vs. NumPy
PyTorch 并不是 NumPy 的简单替代品,但它实现了很多 NumPy 功能。其中有一个不便之处是其命名规则,有时候它和 NumPy 的命名方法相当不同。我们来举几个例子说明其中的区别:

3、1 张量创建
t = torch.rand(2, 4, 3, 5)
a = np.random.rand(2, 4, 3, 5)
2 张量分割
a = t.numpy()pytorch_slice = t[0, 1:3, :, 4]numpy_slice = a[0, 1:3, :, 4]print ('Tensor[0, 1:3, :, 4]:\\n', pytorch_slice)print ('NdArray[0, 1:3, :, 4]:\\n', numpy_slice)-------------------------------------------------------------------------Tensor[0, 1:3, :, 4]: 0.2032 0.1594 0.3114 0.9073 0.6497 0.2826[torch.FloatTensor of size 2x3] NdArray[0, 1:3, :, 4]: [[ 0.20322084 0.15935552 0.31143939] [ 0.90726137 0.64966112 0.28259504]]

4、3 张量
Maskingt = t - 0.5pytorch_masked = t[t > 0]numpy_masked = a[a > 0]


5、4 张量重塑
pytorch_reshape = t.view([6, 5, 4])numpy_reshape = a.reshape([6, 5, 4])

6、.3 PyTorch 变量
PyTorch 张量的简单封装帮助建立计算图Autograd(自动微分库)的必要部分将关于这些变量的梯度保存在 .grad 中

