1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import torch
print(dir(torch.distributions))
print('1.张量的创建')
t = torch.ones(4) print('t:', t)
x = torch.arange(12) print('x:', x) print('x shape:', x.shape)
y = x.reshape(3, 4) print('y:', y) print('y.numel():', y.numel())
z = torch.zeros(2, 3, 4) print('z:', z)
w = torch.randn(2, 3, 4) print('w:', w)
q = torch.tensor([[1, 2, 3], [4, 3, 2], [7, 4, 3]]) print('q:', q)
print('2.张量的运算') x = torch.tensor([1.0, 2, 4, 8]) y = torch.tensor([2, 2, 2, 2]) print(x + y) print(x - y) print(x * y) print(x / y) print(x ** y) print(torch.exp(x))
X = torch.arange(12, dtype=torch.float32).reshape(3, 4) Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) print('cat操作 dim=0', torch.cat((X, Y), dim=0)) print('cat操作 dim=1', torch.cat((X, Y), dim=1))
print('X == Y', X == Y) print('X < Y', X < Y) print('张量所有元素的和:', X.sum())
print('3.广播机制') a = torch.arange(3).reshape(3, 1) b = torch.arange(2).reshape(1, 2) print('a:', a) print('b:', b) print('a + b:', a + b)
print('4.索引和切片') X = torch.arange(12, dtype=torch.float32).reshape(3, 4) print('X:', X) print('X[-1]:', X[-1]) print('X[1:3]:', X[1:3])
X[1, 2] = 9 print('X:', X)
X[0:2, :] = 12 print('X:', X)
print('5.节约内存') before = id(Y) Y = Y + X print(id(Y) == before)
before = id(X) X += Y print(id(X) == before)
before = id(X) X[:] = X + Y print(id(X) == before)
print('6.转换为其他 Python对象') Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) A = Y.numpy() print(type(A)) print(A) B = torch.tensor(A) print(type(B)) print(B)
a = torch.tensor([3.5]) print(a, a.item(), float(a), int(a))
|