From: https://github.com/L1aoXingyu/code-of-learn-deep-learning-with-pytorch
PyTorch 的官方介绍是一个拥有强力GPU加速的张量和动态构建网络的库,其主要构件是张量,所以我们可以把 PyTorch 当做 NumPy 来用,PyTorch 的很多操作好 NumPy 都是类似的,但是因为其能够在 GPU 上运行,所以有着比 NumPy 快很多倍的速度。
1 tensor
创建tensor
import torch
import numpy as np
from torch.autograd import Variable
tensor1 = torch.Tensor(2,3) # 2行3列
tensor2 = torch.rand(2, 3) # [0,1]均匀分布随机初始化二维数组
tensor3 = torch.randn(2, 3) # 标准正态分布 二维数组
numpy --> tensor
numpy_tensor = np.random.randn(2, 4)
pytorch_tensor1 = torch.Tensor(numpy_tensor)
pytorch_tensor2 = torch.from_numpy(numpy_tensor)
tensor --> numpy
numpy_array = pytorch_tensor1.numpy()
tensor 基本属性
print(pytorch_tensor1.shape)
print(pytorch_tensor1.size())
print(pytorch_tensor1.type())
# 维度
print(pytorch_tensor1.dim())
# 元素个数
print(pytorch_tensor1.numel())
tensor 操作
x = torch.ones(2, 3)
转换成整形
x = x.long()
转化成float
x = x.float()
按 行/列 取最大值
x = torch.randn(2, 4)
max_value, max_index = x.max(1) # 行
max_value2, max_index2 = x.max(0) # 列
按 行/列 求和
sum_x_1 = torch.sum(x, 1) # 行
sum_x_2 = torch.sum(x, 0) # 列
维度增删
# 增加
x = torch.rand(2,4) # torch.Size([2, 4])
x.unsqueeze_(0) # torch.Size([1, 2, 4])
x.unsqueeze_(1) # torch.Size([2, 1, 4])
# 减少
x = torch.rand(2,4) # torch.Size([2, 4])
x.unsqueeze_(1) # torch.Size([2, 1, 4])
x.unsqueeze_(-1) # torch.Size([2, 1, 4, 1])
x.squeeze_() # torch.Size([2, 4])
维度交换
# permute
x = torch.rand(1,2,3) # torch.Size([1, 2, 3])
x1 = x.permute(0,2,1) # torch.Size([1, 3, 2])
x2 = x.permute(2,1,0) # torch.Size([1, 3, 2])
# transpose
x.transpose(0, 2).shape # torch.Size([3, 2, 1])
维度reshape
x = torch.rand(4, 6) # torch.Size([4, 6])
x1 = x.reshape(2, 12) # torch.Size([2, 12])
Variable
tensor 是 PyTorch 中的完美组件,但是构建神经网络还远远不够,我们需要能够构建计算图的 tensor,这就是 Variable。Variable 是对 tensor 的封装,操作和 tensor 是一样的,但是每个 Variabel都有三个属性,Variable 中的 tensor本身.data,对应 tensor 的梯度.grad以及这个 Variable 是通过什么方式得到的.grad_fn
定义Variable
x_tensor = torch.rand(10, 5)
y_tensor = torch.rand(10, 5)
x = Variable(x_tensor, requires_grad=True)
y = Variable(y_tensor, requires_grad=True)
z = torch.sum(x + y)
print(z)
# tensor(43.7516, grad_fn=<SumBackward0>)
求x, y 的梯度
z.backward()
print(x.grad)
print(y.grad)
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
练习
尝试构建一个函数 ?=?2 ,然后求 x=2 的导数。
x = Variable(torch.Tensor([2]), requires_grad=True)
y = x**2
y.backward()
print(x.grad)