こんにちは
今回は「pytorchの基本操作」について解説したいと思います。
pytorchの基本操作
torchのインポート
import torch
まず、「torch」というライブラリをインポートします。
pytorchではこのtorchを使うことで機械学習を効率よく進めていくことができます。
任意のテンソルを作る
x = torch.tensor([1,2,3])
テンソル(ここでは単に多次元の配列を指す)を作りたいときにはtorch.tensorとします。
GPUでも計算できて便利だそうです。
ランダムなテンソル
x = torch.randn(2,3) print(x) # tensor([[-1.8543, 1.5295, 0.9487], [ 0.2283, -1.1588, 0.3942]])
要素が乱数のテンソルを作るには、randnとします。
これは標準正規分布(平均0, 分散1の正規分布)に従う乱数を作り出します。
テンソルの大きさを調べる
x = randn(2,3) print(x.size()) # torch.Size([2, 3])
\(x\)の大きさ(\(2\times 3\)の行列)が分かります。
テンソルの行・列・要素を取り出す
x = torch.randn([2,3]) print(x) print(x[1,:]) print(x[:,0]) print(x[1,0]) """ tensor([[0.7668, 0.3616, 0.1420], [0.4437, 0.0342, 0.1561]]) tensor([0.7668, 0.4437]) tensor([0.4437, 0.0342, 0.1561]) tensor(0.0342) """
x[1,;]で1行目の要素すべてを取り出し、x[:,0]で0列目の要素をすべて取り出します。また、x[1,0]で1行0列目の要素が取り出せます。
テンソルの変形
x = torch.randn(4, 4) y = x.view(16) z = x.view(-1, 8) print(x.size(), y.size(), z.size()) # torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
とします。viewで変形が行えます。-1を引数に指定することで、必要なサイズを自動で計算できます。
torch からnumpy, numpy からtorch への変換
a = torch.ones(5) b = a.numpy() print(a) print(b) print(type(a)) print(type(b)) import numpy as np a = np.ones(5) b = torch.from_numpy(a) print(a) print(b) print(type(a)) print(type(b)) """ tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.] <class 'torch.Tensor'> <class 'numpy.ndarray'> [1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64) <class 'numpy.ndarray'> <class 'torch.Tensor'> """
となります。numpy()で「torch \(\to\) numpy」, from_numpy()で「numpy \(\to\) torch」にテンソルを変換できます。