この文書の現在のバージョンと選択したバージョンの差分を表示します。
| 両方とも前のリビジョン 前のリビジョン 次のリビジョン | 前のリビジョン | ||
|
プログラミング:python:ディープラーニング:pytorch:基本的な使い方 [2019/07/15 07:12] sotoyama |
プログラミング:python:ディープラーニング:pytorch:基本的な使い方 [2019/07/15 07:37] (現在) sotoyama [numpy] |
||
|---|---|---|---|
| ライン 1: | ライン 1: | ||
| ===== 基本的な使い方 ===== | ===== 基本的な使い方 ===== | ||
| ==== 基本 ==== | ==== 基本 ==== | ||
| - | === テンソルの初期化 === | + | === テンソルの生成 === |
| <code python> | <code python> | ||
| import torch | import torch | ||
| ライン 16: | ライン 16: | ||
| x = torch.zeros(5, 3, dtype=torch.long) | x = torch.zeros(5, 3, dtype=torch.long) | ||
| print(x) | print(x) | ||
| + | |||
| + | # 初期値を与えて生成 | ||
| + | x = torch.zeros(5, 3, dtype=torch.long) | ||
| + | print(x) | ||
| + | |||
| + | # 生成済みのtensorから、初期値1で生成 | ||
| + | x = x.new_ones(5, 3, dtype=torch.double) | ||
| + | print(x) | ||
| + | |||
| + | # 生成済みのtensorから、平均0分散1のランダム値で生成 | ||
| + | x = torch.randn_like(x, dtype=torch.float) | ||
| + | print(x) | ||
| + | |||
| </code> | </code> | ||
| + | |||
| + | |||
| ●出力結果 | ●出力結果 | ||
| ライン 35: | ライン 50: | ||
| [0, 0, 0], | [0, 0, 0], | ||
| [0, 0, 0]]) | [0, 0, 0]]) | ||
| + | tensor([5.5000, 3.0000]) | ||
| + | tensor([[1., 1., 1.], | ||
| + | [1., 1., 1.], | ||
| + | [1., 1., 1.], | ||
| + | [1., 1., 1.], | ||
| + | [1., 1., 1.]], dtype=torch.float64) | ||
| + | tensor([[ 0.1537, -0.6557, -0.2691], | ||
| + | [-0.8783, 0.2801, 0.5254], | ||
| + | [ 0.9600, -1.9478, -1.0159], | ||
| + | [ 0.8738, -0.4998, 0.6234], | ||
| + | [ 1.3175, -1.0214, 0.2186]]) | ||
| </code> | </code> | ||
| + | |||
| + | === テンソルのサイズ取得 === | ||
| + | <code python> | ||
| + | x = torch.zeros(5, 3, dtype=torch.long) | ||
| + | x.size() | ||
| + | </code> | ||
| + | |||
| + | === テンソルの演算 === | ||
| + | 通常の四則演算(+, -, *, /)も使用できるが、他の方法もあります。 | ||
| + | <code python> | ||
| + | # 加算 | ||
| + | x = torch.rand(5, 3) | ||
| + | y = torch.rand(5, 3) | ||
| + | ret = torch.empty(5, 3) | ||
| + | |||
| + | # その1 | ||
| + | torch.add(x, y, out=ret) | ||
| + | |||
| + | # その2 | ||
| + | y.add(x) | ||
| + | </code> | ||
| + | |||
| + | |||
| + | === tensor→numpyへの変換 === | ||
| + | <code python> | ||
| + | a = torch.ones(5) | ||
| + | b = a.numpy() | ||
| + | </code> | ||
| + | |||
| + | === numpy→tensorへの変換 === | ||
| + | <code python> | ||
| + | import numpy as np | ||
| + | a = np.ones(5) | ||
| + | b = torch.from_numpy(a) | ||
| + | </code> | ||
| + | |||
| + | |||
| + | === XXXX === | ||
| + | <code python> | ||
| + | |||
| + | </code> | ||
| + | === XXXX === | ||
| + | <code python> | ||
| + | |||
| + | </code> | ||
| + | === XXXX === | ||
| + | <code python> | ||
| + | |||
| + | </code> | ||
| + | === XXXX === | ||
| + | <code python> | ||
| + | |||
| + | </code> | ||
| + | === XXXX === | ||
| + | <code python> | ||
| + | |||
| + | </code> | ||
| + | === XXXX === | ||
| + | <code python> | ||
| + | |||
| + | </code> | ||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||