pytorch基本操作

1
2
import torch
torch.__version__
'1.5.1'
1
2
3
# 空向量
x = torch.empty(5,3)
x
tensor([[ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  1.1614e-41],
        [ 0.0000e+00,  2.2369e+08,  0.0000e+00],
        [ 0.0000e+00,  2.8699e-42,  2.8699e-42],
        [        nan,         nan, -1.6905e-07]])
1
2
3
# 随机值
x = torch.rand(5,3)
x
tensor([[0.0896, 0.1420, 0.0921],
        [0.5026, 0.8910, 0.7219],
        [0.4368, 0.9443, 0.7994],
        [0.8293, 0.0944, 0.5980],
        [0.4768, 0.9790, 0.5101]])
1
2
3
# 全零
x = torch.zeros(5,3, dtype=torch.long)
x
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
1
x.size()
torch.Size([5, 3])
1
2
y = torch.rand(5,3)
x + y
tensor([[0.2258, 0.2405, 0.4114],
        [0.2318, 0.3827, 0.7611],
        [0.1114, 0.5431, 0.2139],
        [0.3742, 0.6116, 0.5016],
        [0.5376, 0.2027, 0.1309]])
1
2
# 索引
x[:,1]
tensor([0, 0, 0, 0, 0])
1
2
3
x = torch.randn(4,4)
y = x.view(16) # 16维
print(y)
tensor([-1.2441,  0.8297,  1.1797, -0.5350,  1.1497, -0.0510,  0.1188,  0.6360,
        -1.9398, -0.7194, -0.3698, -1.3789, -1.4802, -1.0151, -1.5127, -0.9896])
1
2
3
z = x.view(-1, 8) # -1自动做计算
print(z)
print(z.size())
tensor([[-1.2441,  0.8297,  1.1797, -0.5350,  1.1497, -0.0510,  0.1188,  0.6360],
        [-1.9398, -0.7194, -0.3698, -1.3789, -1.4802, -1.0151, -1.5127, -0.9896]])
torch.Size([2, 8])
1
2
3
# 与numpy协同操作
a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
1
2
b = a.numpy()
b
array([1., 1., 1., 1., 1.], dtype=float32)
1
2
3
4
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
b
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
1


pytorch基本操作
https://zhangfuli.github.io/2020/09/01/pytorch基本操作/
作者
张富利
发布于
2020年9月1日
许可协议