2.预备知识

2.1 数据操作

1
2
3
import torch
x = torch.arange(12)
x
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
1
x.shape
torch.Size([12])
1
x.numel()
12
1
2
X=x.reshape(3,4)
X
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
1
X.shape
torch.Size([3, 4])
1
2
Y=x.reshape(-1,4)
Y
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
1
2
Z=x.reshape(3,-1)
Z
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
1
torch.zeros((2,3,4))
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])
1
torch.ones((2,3,4))
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
torch.randn(3,4)
tensor([[ 1.6438, -1.2879,  0.2324,  0.2719],
        [-0.6636,  0.9939, -0.8435, -1.0906],
        [-0.5617,  0.2107, -0.9530,  0.7362]])
1
2
3
x=torch.tensor([1.0,2,4,8])
y=torch.tensor([2,2,2,2])
x+y,x-y,x*y,x/y,x**y
(tensor([ 3.,  4.,  6., 10.]),
 tensor([-1.,  0.,  2.,  6.]),
 tensor([ 2.,  4.,  8., 16.]),
 tensor([0.5000, 1.0000, 2.0000, 4.0000]),
 tensor([ 1.,  4., 16., 64.]))
1
torch.exp(x)
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])
1
2
X=torch.arange(12,dtype=torch.float32).reshape((3,4))
X
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]])
1
2
Y=torch.tensor([[2.0,1,4,3],[1,2,3,4],[4,3,2,1]])
Y
tensor([[2., 1., 4., 3.],
        [1., 2., 3., 4.],
        [4., 3., 2., 1.]])
阅读更多