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

PyTorch 1.0 : Getting Started : PyTorch とは何か? (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/07/2018 (1.0.0.dev20181128)

* 本ページは、PyTorch 1.0 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([[ 1.6343e-07,  4.5744e-41, -1.1779e-38],
        [ 3.0897e-41,  4.4842e-44,  0.0000e+00],
        [ 1.1210e-43,  0.0000e+00, -1.0953e-38],
        [ 3.0897e-41,  7.0979e+28,  4.6664e-14],
        [ 1.4312e+13,  1.0304e-11,  2.7450e-06]])

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

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([[-0.2217, -0.9135, -0.6010],
        [-0.3193, -0.3675,  0.1951],
        [ 0.0646, -0.4947,  1.0374],
        [-0.4154, -1.0247, -1.2872],
        [ 0.5228,  0.3420,  0.0219]])

そのサイズを得ます :

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

[NOTE]

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

 

演算

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

加算: シンタクス 1

y = torch.rand(5, 3)
print(x + y)
tensor([[ 0.2349, -0.0427, -0.5053],
        [ 0.6455,  0.1199,  0.4239],
        [ 0.1279,  0.1105,  1.4637],
        [ 0.4259, -0.0763, -0.9671],
        [ 0.6856,  0.5047,  0.4250]])

加算: シンタクス 2

print(torch.add(x, y))
tensor([[ 0.2349, -0.0427, -0.5053],
        [ 0.6455,  0.1199,  0.4239],
        [ 0.1279,  0.1105,  1.4637],
        [ 0.4259, -0.0763, -0.9671],
        [ 0.6856,  0.5047,  0.4250]])

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

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 0.2349, -0.0427, -0.5053],
        [ 0.6455,  0.1199,  0.4239],
        [ 0.1279,  0.1105,  1.4637],
        [ 0.4259, -0.0763, -0.9671],
        [ 0.6856,  0.5047,  0.4250]])

加算: in-place

# adds x to y
y.add_(x)
print(y)
tensor([[ 0.2349, -0.0427, -0.5053],
        [ 0.6455,  0.1199,  0.4239],
        [ 0.1279,  0.1105,  1.4637],
        [ 0.4259, -0.0763, -0.9671],
        [ 0.6856,  0.5047,  0.4250]])

[NOTE]

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

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

print(x[:, 1])
tensor([-0.9135, -0.3675, -0.4947, -1.0247,  0.3420])

リサイズ: 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([1.9218])
1.9218417406082153

[Read later]:

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

 

NumPy ブリッジ

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

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

 

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

以上