回顾
在之前,我已经撰写过 numpy 的教程,pytorch 可以认为是 numpy 在 GPU 上可以加速实现的版本。这里对一些基本的 pytorch 操作进行了总结,方便后续看代码。原教程请查看:W3Cschool
1 定义
pytorch 的核心基础是张量,类似 ndnarray。
import torch
# 初始化一个张量
a = torch.empty(5, 3)
print(a)
'''
tensor([[1.8990e+28, 2.9602e+29, 7.1447e+31],
[2.2266e-15, 1.7753e+28, 3.0579e+32],
[1.8469e+25, 1.6458e+19, 3.4063e-15],
[7.3988e+31, 4.4849e+21, 2.7370e+20],
[6.4640e-04, 1.8461e+20, 9.0941e-04]])
'''
# 随机初始化矩阵
a = torch.rand(4, 3)
print(a)
'''
tensor([[0.8109, 0.5578, 0.1464],
[0.5521, 0.1801, 0.7965],
[0.6199, 0.5824, 0.8495],
[0.8143, 0.8501, 0.9338]])
'''
# 初始化一个全为 long 0的矩阵
a = torch.zeros(2, 3, dtype=torch.long)
print(a)
'''
tensor([[0, 0, 0],
[0, 0, 0]])
'''
# 直接构造一个张量
a = torch.tensor([5, 3])
print("输出结果:", a) # 输出结果: tensor([5, 3])
# 张量的形状
print(a.size()) # torch.Size([2])
2 运算
import torch
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
# 对应项加法
print(a + b)
print(torch.add(a, b))
'''
tensor([[ 6, 8],
[10, 12]])
'''
# 自加
print("自加前 a:\n", a)
a.add_(b)
print("自加后 a:\n", a)
'''
自加前 a:
tensor([[1, 2],
[3, 4]])
自加后 a:
tensor([[ 6, 8],
[10, 12]])
'''
# 索引
print(a[:, 1]) # tensor([ 8, 12])
# 改变形状
c = b.view(4)
print(c) # tensor([5, 6, 7, 8])
c = b.view(4, -1)
print(c)
'''
tensor([[5],
[6],
[7],
[8]])
'''