PyTorch 1.1 : Getting Started : PyTorch とは何か?

PyTorch 1.1 : Getting Started : PyTorch とは何か? (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 06/21/2019 (1.1.0)

* 本ページは、PyTorch 1.1 Tutorials の What is PyTorch? を翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

PyTorch とは何か?

それは2つのセットの読者を対象とする Python ベースの科学計算パッケージです :

  • GPU のパワーを使用するための NumPy の置き換えです。
  • 最大限の柔軟性とスピードを提供する深層学習研究プラットフォームです。

 

GETTING STARTED

Tensor

テンソルは NumPy の ndarray に類似していますが、テンソルは GPU 上で計算を加速するために使用できることが付加されます。

from __future__ import print_function
import torch

非初期化の 5×3 行列をコンストラクトします :

x = torch.empty(5, 3)
print(x)
tensor([[-2.6047e-34,  4.5689e-41, -4.4695e-06],
        [ 3.0967e-41,  0.0000e+00,  1.4013e-45],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00]])

ランダムに初期化された行列をコンストラクトします :

x = torch.rand(5, 3)
print(x)
tensor([[0.1607, 0.0298, 0.7555],
        [0.8887, 0.1625, 0.6643],
        [0.7328, 0.5419, 0.6686],
        [0.0793, 0.1133, 0.5956],
        [0.3149, 0.9995, 0.6372]])

ゼロで満たされた dtype long の行列をコンストラクトします :

x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

データから直接 tensor をコンストラクトします :

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

あるいは既存の tensor を基に tensor を作成します。新しい値がユーザにより提供されないのであればこれらのメソッドは入力 tensor のプロパティを再利用します、e.g. dtype。

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
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[ 1.5847,  0.5173, -1.1023],
        [-0.8838,  0.9363,  1.7052],
        [ 0.0128, -0.1290,  2.3332],
        [ 1.5871, -0.1958,  0.6752],
        [-0.0966,  0.6595,  0.3823]])

そのサイズを得ます :

print(x.size())
torch.Size([5, 3])

[NOTE]

torch.Size は実際にはタプルですので、それは総てのタプル演算をサポートします。

 

演算

演算のために複数のシンタックスがあります。次の例では、加算演算を見ます。

加算: シンタクス 1

y = torch.rand(5, 3)
print(x + y)
tensor([[ 2.1828,  1.4681, -0.7141],
        [-0.4905,  1.9230,  2.6847],
        [ 0.9272,  0.3145,  2.7955],
        [ 2.0585,  0.4070,  0.8178],
        [-0.0586,  1.3638,  1.2249]])

加算: シンタクス 2

print(torch.add(x, y))
tensor([[ 2.1828,  1.4681, -0.7141],
        [-0.4905,  1.9230,  2.6847],
        [ 0.9272,  0.3145,  2.7955],
        [ 2.0585,  0.4070,  0.8178],
        [-0.0586,  1.3638,  1.2249]])

加算: 出力テンソルを引数として提供します :

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 2.1828,  1.4681, -0.7141],
        [-0.4905,  1.9230,  2.6847],
        [ 0.9272,  0.3145,  2.7955],
        [ 2.0585,  0.4070,  0.8178],
        [-0.0586,  1.3638,  1.2249]])

加算: in-place

# adds x to y
y.add_(x)
print(y)
tensor([[ 2.1828,  1.4681, -0.7141],
        [-0.4905,  1.9230,  2.6847],
        [ 0.9272,  0.3145,  2.7955],
        [ 2.0585,  0.4070,  0.8178],
        [-0.0586,  1.3638,  1.2249]])

[NOTE]

tensor を in-place で変化させる任意の演算は _ で post-fix されます。例えば : x.copy_(y), x.t_(), は x を変更します。

 
標準的な NumPy-ライクなインデキシングもあらゆるものと一緒に使用できます!

print(x[:, 1])
tensor([ 0.5173,  0.9363, -0.1290, -0.1958,  0.6595])

リサイズ: tensor をリサイズ/reshape することを望む場合、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())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

1 成分 tensor を持つ場合、Python 数として値を得るために .item() が使用できます :

x = torch.randn(1)
print(x)
print(x.item())
tensor([0.4566])
0.45661526918411255

[Read later]:

transposing, インデキシング, スライシング, 数学演算, 線形代数, ランダム数等を含む 100+ Tensor 演算は ここ で記述されています。

 

NumPy ブリッジ

Torch Tensor を NumPy 配列に変換することそしてその逆も簡単なことです。

Torch Tensor と NumPy 配列は (Torch Tensor が CPU 上にある場合) それらの基礎的なメモリ位置を共有するでしょう、そして一方の変更は他方を変更します。

 

Torch Tensor を NumPy 配列に変換する

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

numpy 配列が値についてどのように変更されたかを見ます。

a.add_(1)
print(a)
print(b)
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

 

NumPy 配列を Torch Tensor に変換する

np 配列の変更がどのように Torch Tensor を自動的に変更したかを見ます。

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

CharTensor を除く CPU 上の総ての Tensor は Numpy への変換とその逆をサポートします。

 

CUDA Tensor

テンソルは .to メソッドを使用してどのようなデバイス上にも移動できます。

# 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!
tensor([1.4566], device='cuda:0')
tensor([1.4566], dtype=torch.float64)
 

以上