pytorch入门

参考PyTorch官方教程中文版

特点

支持GPU,灵活,支持动态神经网络,底层代码易于理解,命令式体验。

张量(tensor)学习

具体用法参照官方文档

1
2
3
4
import torch
# 构造一个5x3矩阵,不初始化。
x = torch.empty((5, 3)
print(x)

1
2
3
# 构造一个随机初始化的矩阵
x = torch.rand((5, 3))
print(x)

1
2
3
# 构造一个填充某个值的矩阵
x = torch.full((5, 3), 3.1415)
print(x)

1
2
3
# 构造全为0的矩阵,且数据类型为long
x = torch.zeros((5, 3), dtype = torch.long)
print(x)

1
2
3
4
# 构造单位矩阵
# torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
# Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.
torch.eye(3)

1
2
3
# 使用数据构造一个张量
x = torch.tensor([5.5, 3])
print(x)

1
2
3
4
5
6
7
8
# 用已经存在的tensor构造一个tensor
x = x.new_ones((5, 3), dtype = torch.double)
# new_* methods take in sizes
print(x)

x = torch.randn_like(x, dtype = torch.float)
# size和原x的size相同,但数据类型不同
print(x)

1
2
# 获取维度信息 size()
print(x.size())

1
2
3
# 加法1 +
y = torch.rand(5, 3)
print(x + y)

1
2
3
4
# 加法2 torch.add
# torch.add(input, alpha=1, other, out=None)
# Each element of the tensor other is multiplied by the scalar alpha and added to each element of the tensor input. The resulting tensor is returned.
print(torch.add(x, y))

1
2
3
4
# 提供一个输出tensor作为参数
result = torch.empty((5, 3))
torch.add(x, y, out = result)
print(x + y)

1
2
3
4
5
# add x to y  (in-place)
# 即将x+y的值赋给y
# 任何使张量会发生变化的操作都有一个前缀
y.add_(x)
print(y)

1
2
3
4
5
6
# 改变大小:如果你想改变一个 tensor 的大小或者形状,你可以使用 torch.view:

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())