Deep Learning with PyTorch: A 60 Minute Blitz 要点整理

Tensor

创建

  • Construct a 5x3 matrix, uninitialized:
x = torch.Tensor(5, 3)
  • Construct a randomly initialized matrix
x = torch.rand(5, 3)

Operation

实现两个tensor的加法:x+y
1.

x + y

2.

torch.add(x, y)

3.giving an output tensor

result = torch.Tensor(5, 3)
torch.add(x, y, out=result)

4.in-place

y.add_(x)

Numpy Bridge

The torch Tensor and numpy array will share their underlying memory locations, and changing one will change the other.

Converting torch Tensor to numpy Array

a = torch.ones(5)
b = a.numpy()

Converting numpy Array to torch Tensor

a = np.ones(5)
b = torch.from_numpy(a)

CUDA Tensors

Tensors can be moved onto GPU using the .cuda function.

if torch.cuda.is_available():
    x = x.cuda()
    y = y.cuda()
    x + y

autograd.Variable

  • .backward()
  • .data
  • .grad: autograd.Variable
  • .creator: autograd.Function. Each variable has a .creator attribute that references a Function that has created the Variable (except for Variables created by the user - their creator is None).

版权声明:本文为u011636567原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。