
- 作者:斎藤勇哉
- 発売日: 2020/11/30
- メディア: Kindle版
目次
目的
PyTorchのチュートリアル「What is PyTorch?」を参考にPyTorchで特有のテンソルの扱いになれること。
関連記事
チュートリアル
- 【PyTorch】チュートリアル(日本語版 )① 〜テンソル〜
- 【PyTorch】チュートリアル(日本語版 )② 〜AUTOGRAD〜
- 【PyTorch】チュートリアル(日本語版 )③ 〜NEURAL NETWORKS(ニューラルネットワーク)〜
- 【PyTorch】チュートリアル(日本語版 )④ 〜TRAINING A CLASSIFIER(画像分類)〜
前準備
PyTorchのインストールはこちらから。
初めて、Google Colaboratoryを使いたい方は、こちらをご覧ください。
コマンドラインの「>>>」の行がPythonで実行するコマンドです。 それ以外の行は、実行結果です。
関連記事
チュートリアル
- 【PyTorch】チュートリアル(日本語版 )① 〜テンソル〜
- 【PyTorch】チュートリアル(日本語版 )② 〜AUTOGRAD〜
- 【PyTorch】チュートリアル(日本語版 )③ 〜NEURAL NETWORKS(ニューラルネットワーク)〜
- 【PyTorch】チュートリアル(日本語版 )④ 〜TRAINING A CLASSIFIER(画像分類)〜
サンプル
- 【PyTorch】サンプル① 〜NUMPY〜
- 【PyTorch】サンプル② 〜TENSOR (テンソル) 〜
- 【PyTorch】サンプル③ 〜TENSORS AND AUTOGRAD(テンソルと自動微分)〜
- 【PyTorch】サンプル④ 〜Defining New autograd Functions(自動微分関数の定義)〜
- 【PyTorch】サンプル⑤ 〜Static Graphs(静的グラフ)〜
- 【PyTorch】サンプル⑥ 〜 nn パッケージ 〜
- 【PyTorch】サンプル⑦ 〜 optim パッケージ 〜
- 【PyTorch】サンプル⑧ 〜 複雑なモデルの構築方法 〜
- 【PyTorch】サンプル⑨ 〜 動的グラフ 〜
テンソル入門
PyTorchのテンソルはNumPyのndarrayと似ていますが、テンソルを使うことでGPUの計算を速くすることができます。
初めに、PyTorchのパッケージをインストールする。
>>> from __future__ import print_function >>> import torch
未初期化テンソル torch.empty()
5x3の行列を、torch.empty()で作ってみます。 torch.empty()では、明確な値が宣言されていないので、xは何らかの値で初期化されません。 この場合、割り当てられたメモリに存在する値が初期値となります。
>>> x = torch.empty(5, 3) >>> print(x) tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
乱数 torch.rand()
torch.rand()では、0から1の間で乱数を生成します。 乱数なので、以下の結果は皆さんとは違う数値となるでしょう。
>>> x = torch.rand(5, 3) >>> print(x) tensor([[0.8352, 0.4284, 0.9945], [0.0470, 0.6297, 0.8245], [0.3345, 0.2747, 0.4997], [0.4784, 0.6809, 0.9355], [0.3260, 0.4357, 0.4054]])
零行列 torch.zeros()
torch.zeros()は、零行列を生成します。dtype(data type)からデータの型を指定することができます。
>>> 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]])
任意のテンソル定義 torch.tensor()
torch.tensor()で、直接テンソルを定義することができます。
>>> x = torch.tensor([5.5, 3]) >>> print(x) tensor([5.5000, 3.0000])
テンソルの再定義 .new_*と.randn_like()
既に定義されたテンソルに基づいてテンソルを作成する場合、新たに入力されたテンソルのプロパティは前のテンソルのプロパティと同じものになります。 例えば、元々あったテンソルに新たに値を入力したとしても、dtypeは前のテンソルと変わりません。 このようにdtypeも含めてテンソルを再定義したい場合、.new_* ()メソッドあるいは、.randn_like()メソッドで実行できます。
以下の例では、テンソルxのdtypeをfloatとdoubleを行き来しています。
>>> x.dtype torch.float32 >>> x = x.new_ones(5, 3, dtype=torch.double) >>> print(x) tensor([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], dtype=torch.float64) >>> >>> x.dtype torch.float64 >>> x = torch.randn_like(x, dtype=torch.float) >>> print(x) tensor([[-0.3210, -1.4832, -0.2524], [-2.0422, 0.7449, 0.1984], [ 0.2876, -1.2218, 2.3327], [-0.5546, 0.3350, 1.1102], [ 0.0944, 0.0898, -0.3516]]) >>> x.dtype torch.float32
サイズの確認
テンソルサイズは、.size()メソッドで確認できる。
>>> print(x) tensor([[-0.3210, -1.4832, -0.2524], [-2.0422, 0.7449, 0.1984], [ 0.2876, -1.2218, 2.3327], [-0.5546, 0.3350, 1.1102], [ 0.0944, 0.0898, -0.3516]]) >>> print(x.size()) torch.Size([5, 3])
足し算
テンソルの足し算は、普段通りの単純な書き方で実行できる。
>>> x = torch.rand(5,3) >>> y = torch.rand(5,3) >>> print(x) tensor([[0.7466, 0.5271, 0.8535], [0.4013, 0.6994, 0.6155], [0.5134, 0.9600, 0.3479], [0.2490, 0.1273, 0.4822], [0.3450, 0.3346, 0.3434]]) >>> print(y) tensor([[0.2132, 0.5978, 0.9456], [0.6022, 0.3573, 0.5939], [0.3110, 0.2472, 0.1006], [0.8461, 0.5532, 0.2845], [0.2572, 0.4491, 0.6128]]) >>> print(x + y) tensor([[0.9598, 1.1249, 1.7991], [1.0035, 1.0567, 1.2095], [0.8245, 1.2073, 0.4485], [1.0951, 0.6805, 0.7668], [0.6021, 0.7837, 0.9562]])
torch.add()でも足し算ができる。
>>> print(torch.add(x, y)) tensor([[0.9598, 1.1249, 1.7991], [1.0035, 1.0567, 1.2095], [0.8245, 1.2073, 0.4485], [1.0951, 0.6805, 0.7668], [0.6021, 0.7837, 0.9562]])
足し算の結果を新たな変数として指定してやることもできます。
>>> result = torch.empty(5, 3) >>> torch.add(x, y, out=result) tensor([[0.9598, 1.1249, 1.7991], [1.0035, 1.0567, 1.2095], [0.8245, 1.2073, 0.4485], [1.0951, 0.6805, 0.7668], [0.6021, 0.7837, 0.9562]]) >>> print(result) tensor([[0.9598, 1.1249, 1.7991], [1.0035, 1.0567, 1.2095], [0.8245, 1.2073, 0.4485], [1.0951, 0.6805, 0.7668], [0.6021, 0.7837, 0.9562]])
.add_()メソッドを使ってでも足し算ができます。
>>> y.add(x) >>> print(y) tensor([[0.9598, 1.1249, 1.7991], [1.0035, 1.0567, 1.2095], [0.8245, 1.2073, 0.4485], [1.0951, 0.6805, 0.7668], [0.6021, 0.7837, 0.9562]])
スライス
PyTorchでもNumPyと同じようにスライスを使うことができます。 テンソルxから2列目を取り出す場合。
>>> print(x) tensor([[0.7466, 0.5271, 0.8535], [0.4013, 0.6994, 0.6155], [0.5134, 0.9600, 0.3479], [0.2490, 0.1273, 0.4822], [0.3450, 0.3346, 0.3434]]) >>> print(x[:, 1]) tensor([0.5271, 0.6994, 0.9600, 0.1273, 0.3346])
リサイズ
テンソルのresizeやreshapeはtorch.viewを使うことで実行できます。
以下の例では、xは4x4として、yはテンソルxを1x16にreshape、zはテンソルxを2x8にreshapeします。x.view(-1,8)の-1は他の次元の要素数から推測して埋められます。 この場合だと、要素数は16なので二次元目が8なので一次元目は2(=16/8)になります。
>>> 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])
テンソルに格納されている数値を通常の数値として取り出したい場合、.item()メソッドを使います。
>>> x = torch.randn(1) >>> print(x) tensor([-2.1301]) >>> print(x.item()) -2.130094289779663
テンソルとNumPyのやりとり
PyTorchがCPUで動作している場合、テンソルとNumpy arrayは割り当てられた同じメモリ領域を共有します。
テンソルからNumPy arrayの変換
テンソルからNumPy arrayの変換には.numpy()メソッドを使います。
>>> a = torch.ones(5) >>> print(a) tensor([1., 1., 1., 1., 1.]) >>> b = a.numpy() >>> print(b) [1. 1. 1. 1. 1.]
テンソルaに1を足したときテンソルbはこのように変化します。 テンソルaが更新されたのに合わせて、テンソルbも更新されていることがわかります。
>>> a.add_(1) tensor([2., 2., 2., 2., 2.]) >>> print(a) tensor([2., 2., 2., 2., 2.]) >>> print(b) [2. 2. 2. 2. 2.]
NumPy Arrayからテンソルの変換
NumPy arrayからテンソルの変換には、torch.from_numpy()を使用します。
>>> import numpy as np >>> a = np.ones(5) >>> b = torch.from_numpy(a) >>> np.add(a, 1, out=a) array([2., 2., 2., 2., 2.]) >>> print(a) [2. 2. 2. 2. 2.] >>> print(b) tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
頑張れ!、喝!!の代わりにB!ブックマークを押していただけるとただただうれしいです(^^)! ↓

- 作者:斎藤勇哉
- 発売日: 2020/11/30
- メディア: Kindle版