PyTorch 1.3 : Getting Started : PyTorch とは何か? (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/07/2019 (1.3.1)
* 本ページは、PyTorch 1.3 Tutorials の以下のページを翻訳した上で適宜、補足説明したものです:
- Getting Started : 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
[NOTE]
非初期化行列が宣言されますが、それが使用される前に確定された既知の値は含みません。非初期化行列が作成されたとき、その時に割当てメモリにどのような値があっても初期値として現れます。
非初期化の 5×3 行列をコンストラクトします :
x = torch.empty(5, 3) print(x)
tensor([[ 9.1398e+21, 4.5829e-41, -2.5977e+12], [ 3.0690e-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.0968, 0.4793, 0.7434], [0.6993, 0.7196, 0.1837], [0.2133, 0.0658, 0.8784], [0.6980, 0.6608, 0.9216], [0.9936, 0.0258, 0.7351]])
ゼロで満たされた 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.0746, 0.9749, 0.2021], [ 0.2313, 1.0035, 1.3243], [-0.8756, -0.1622, -0.3278], [-1.6786, -0.2889, 0.9756], [ 1.3692, 2.6928, -0.4980]])
そのサイズを得ます :
print(x.size())
torch.Size([5, 3])
[NOTE]
torch.Size は実際にはタプルですので、それは総てのタプル演算をサポートします。
演算
演算のために複数のシンタックスがあります。次の例では、加算演算を見ます。
加算: シンタクス 1
y = torch.rand(5, 3) print(x + y)
tensor([[ 0.1698, 1.5033, 0.4410], [ 0.2745, 1.4679, 2.2457], [-0.4422, 0.5490, 0.2639], [-1.2002, 0.0409, 1.8936], [ 2.0491, 3.1655, 0.4165]])
加算: シンタクス 2
print(torch.add(x, y))
tensor([[ 0.1698, 1.5033, 0.4410], [ 0.2745, 1.4679, 2.2457], [-0.4422, 0.5490, 0.2639], [-1.2002, 0.0409, 1.8936], [ 2.0491, 3.1655, 0.4165]])
加算: 出力テンソルを引数として提供します :
result = torch.empty(5, 3) torch.add(x, y, out=result) print(result)
tensor([[ 0.1698, 1.5033, 0.4410], [ 0.2745, 1.4679, 2.2457], [-0.4422, 0.5490, 0.2639], [-1.2002, 0.0409, 1.8936], [ 2.0491, 3.1655, 0.4165]])
加算: in-place
# adds x to y y.add_(x) print(y)
tensor([[ 0.1698, 1.5033, 0.4410], [ 0.2745, 1.4679, 2.2457], [-0.4422, 0.5490, 0.2639], [-1.2002, 0.0409, 1.8936], [ 2.0491, 3.1655, 0.4165]])
[NOTE]
tensor を in-place で変化させる任意の演算は _ で post-fix されます。例えば : x.copy_(y), x.t_(), は x を変更します。
標準的な NumPy-ライクなインデキシングもあらゆるものと一緒に使用できます!
print(x[:, 1])
tensor([ 0.9749, 1.0035, -0.1622, -0.2889, 2.6928])
リサイズ: 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.6958]) 0.6957961320877075
[Read later]:
転置、インデキシング, スライシング, 数学演算, 線形代数, ランダム数等を含む 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.6958], device='cuda:0') tensor([1.6958], dtype=torch.float64)
以上