-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetting_started.py
More file actions
94 lines (63 loc) · 2.12 KB
/
getting_started.py
File metadata and controls
94 lines (63 loc) · 2.12 KB
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
90
91
92
93
94
import torch
print("The first tutorial in \"Deep Learning with PyTorch: A 60 Minute Blitz\"")
print("\n")
print("Initialise matrix with arbitrary starting values")
x = torch.empty(5, 3)
print(x)
print("Initialise matrix with random values in [0,1]")
x = torch.rand(5, 3)
print(x)
print("Initialise matrix with zeros, and enforce type long")
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
print("Construct tensor directly from data (also convert existing arrays to tensors")
x=torch.tensor([5.5,3])
print(x)
print("Construct new tensor with properties of given tensor")
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
x = x.new_ones(5, 3, dtype=torch.float)
print(x)
print("Get the size of x")
print(x.size())
print("Addition Syntax")
y = torch.rand(5, 3)
print(x + y)
print(torch.add(x, y))
print("Outputting addiiton result into an existing tensor")
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
print("In-place addition")
y.add_(x)
print(y)
print("You can usee all numpy slicing operations")
print(x[:, 1])
print("Resizing is possible using 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())
print("Getting a single-element tensor as a number")
x = torch.randn(1)
print(x)
print(x.item())
print("Convert tensorflow tensor to numpy array")
a=torch.ones(1,5)
b=a.numpy()
print(a)
print(b)
print("Editing the underlying tensor will also edit any numpy conversion attached to it")
a.add_(a)
print(a)
print(b)
print("Tensors have an assigned device that handles operations on them. We can change it using the .to method")
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!