What is PyTorch?

What is PyTorch?

It’s a Python based scientific computing package targeted at two sets of audiences:

  • A replacement for NumPy to use the power of GPUs
  • a deep learning research platform that provides maximum flexibility and speed

Getting Started

Tensors

Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.

from __future__ import print_function
import torch

Construct a 5x3 matrix, uninitialized:

x = torch.empty(5, 3)
print(x)

Out:

tensor([[-5.0254e+18,  4.5609e-41, -5.0254e+18],
        [ 4.5609e-41,  1.6395e-43,  1.3873e-43],
        [ 1.4574e-43,  4.4842e-44,  1.4293e-43],
        [ 1.4714e-43,  1.5134e-43,  1.4153e-43],
        [ 4.4842e-44,  1.5554e-43,  1.5975e-43]])

Construct a randomly initialized matrix:

x = torch.rand(5, 3)
print(x)

Out:

tensor([[0.3380, 0.3845, 0.3217],
        [0.8337, 0.9050, 0.2650],
        [0.2979, 0.7141, 0.9069],
        [0.1449, 0.1132, 0.1375],
        [0.4675, 0.3947, 0.1426]])

Construct a matrix filled zeros and of dtype long:

x = torch.zeros(5, 3, dtype=torch.long)
print(x)

Out:

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

Construct a tensor directly from data:

x = torch.tensor([5.5, 3])
print(x)

Out:

tensor([5.5000, 3.0000])

or create a tensor based on an existing tensor. These methods will reuse properties of the input tensor, e.g. dtype, unless new values are provided by user

x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print(x)

x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x)                                      # result has the same size

Out:

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[-0.2080,  1.5288, -1.8337],
        [ 1.3006,  0.9401, -2.4675],
        [ 0.6897, -0.4666,  2.5578],
        [ 1.1115,  0.1749, -0.0959],
        [ 0.7542, -0.2380,  0.0408]])

Get its size:

print(x.size())

Out:

torch.Size([5, 3])

Note

torch.Size is in fact a tuple, so it supports all tuple operations.

Operations

There are multiple syntaxes for operations. In the following example, we will take a look at the addition operation.

Addition: syntax 1

y = torch.rand(5, 3)
print(x + y)

Out:

tensor([[ 0.7890,  1.9319, -1.2865],
        [ 1.3956,  1.4262, -2.3513],
        [ 0.9005,  0.4398,  3.3741],
        [ 1.4076,  0.3860, -0.0404],
        [ 0.8079,  0.0838,  0.1361]])

Addition: syntax 2

print(torch.add(x, y))

Out:

tensor([[ 0.7890,  1.9319, -1.2865],
        [ 1.3956,  1.4262, -2.3513],
        [ 0.9005,  0.4398,  3.3741],
        [ 1.4076,  0.3860, -0.0404],
        [ 0.8079,  0.0838,  0.1361]])

Addition: providing an output tensor as argument

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

Out:

tensor([[ 0.7890,  1.9319, -1.2865],
        [ 1.3956,  1.4262, -2.3513],
        [ 0.9005,  0.4398,  3.3741],
        [ 1.4076,  0.3860, -0.0404],
        [ 0.8079,  0.0838,  0.1361]])

Addition: in-place

# adds x to y
y.add_(x)
print(y)

Out:

tensor([[ 0.7890,  1.9319, -1.2865],
        [ 1.3956,  1.4262, -2.3513],
        [ 0.9005,  0.4398,  3.3741],
        [ 1.4076,  0.3860, -0.0404],
        [ 0.8079,  0.0838,  0.1361]])

Note

Any operation that mutates a tensor in-place is post-fixed with an _. For example: x.copy_(y)x.t_(), will change x.

You can use standard NumPy-like indexing with all bells and whistles!

print(x[:, 1])

Out:

tensor([ 1.5288,  0.9401, -0.4666,  0.1749, -0.2380])

Resizing: If you want to resize/reshape tensor, you can use 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())

Out:

torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

If you have a one element tensor, use .item() to get the value as a Python number

x = torch.randn(1)
print(x)
print(x.item())

Out:

tensor([0.5191])
0.5191271305084229

Read later:

100+ Tensor operations, including transposing, indexing, slicing, mathematical operations, linear algebra, random numbers, etc., are described here.

NumPy Bridge

Converting a Torch Tensor to a NumPy array and vice versa is a breeze.

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

Converting a Torch Tensor to a NumPy Array

a = torch.ones(5)
print(a)

Out:

tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)

Out:

[1. 1. 1. 1. 1.]

See how the numpy array changed in value.

a.add_(1)
print(a)
print(b)

Out:

tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

Converting NumPy Array to Torch Tensor

See how changing the np array changed the Torch Tensor automatically

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

Out:

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

All the Tensors on the CPU except a CharTensor support converting to NumPy and back.

CUDA Tensors

Tensors can be moved onto any device 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!

Out:

tensor([1.5191], device='cuda:0')
tensor([1.5191], dtype=torch.float64)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值