torch.Tensorの基本操作(作成、演算、形状変更など)

PyTorchにおけるtorch.Tensorは、NumPyのndarrayと類似した多次元配列であり、機械学習モデルのデータ保持や演算処理の中心的な役割を果たします。以下に、torch.Tensorの基本操作として「作成」「演算」「形状変更」などを中心に詳しく説明します。


1. Tensorの作成

1.1 データから直接作成

python
import torch x = torch.tensor([1.0, 2.0, 3.0]) # 1次元テンソル y = torch.tensor([[1, 2], [3, 4]]) # 2次元テンソル

1.2 特定の値を持つTensor

python
torch.zeros(3, 4) # 3×4のゼロテンソル torch.ones(2, 2) # 2×2のすべて1のテンソル torch.full((2, 3), 5) # すべて5のテンソル torch.eye(3) # 単位行列(3×3)

1.3 ランダムな値で作成

python
torch.rand(2, 2) # 一様分布 [0, 1) torch.randn(2, 2) # 標準正規分布 N(0, 1) torch.randint(0, 10, (2, 3)) # 整数値 [0, 10)

1.4 他のテンソルから作成

python
a = torch.ones(2, 3) b = torch.empty_like(a) # 同じサイズ、未初期化 c = torch.rand_like(a) # 同じサイズでランダム値

2. Tensorの演算

2.1 要素ごとの演算

python
a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6]) c = a + b # 加算 d = a * b # 乗算(要素ごと) e = a ** 2 # 累乗

2.2 行列演算

python
A = torch.tensor([[1., 2.], [3., 4.]]) B = torch.tensor([[5., 6.], [7., 8.]]) C = torch.matmul(A, B) # 行列積 D = A @ B # 同じく行列積(Python 3.5以降)

2.3 統計的演算

python
x = torch.tensor([[1., 2.], [3., 4.]]) x.sum() # 合計 x.mean() # 平均 x.max() # 最大値 x.min() # 最小値 x.std() # 標準偏差

3. 形状変更(Reshape)

3.1 view()reshape()

python
x = torch.arange(6) # tensor([0, 1, 2, 3, 4, 5]) x = x.view(2, 3) # (2, 3) に変形 # または x = x.reshape(3, 2) # (3, 2) に再変形

3.2 次元の追加と削除

python
x = torch.tensor([1.0, 2.0, 3.0]) x_unsqueezed = x.unsqueeze(0) # shape: (1, 3) x_squeezed = x_unsqueezed.squeeze(0) # shape: (3,)

3.3 転置と次元の入れ替え

python
x = torch.tensor([[1, 2], [3, 4]]) x_t = x.t() # 転置(2次元のみ) y = torch.rand(2, 3, 4) y_perm = y.permute(2, 0, 1) # 次元を並べ替え

4. Tensorの属性とデバイス管理

python
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32) x.shape # torch.Size([2, 2]) x.dtype # torch.float32 x.device # CPU or CUDA # GPUへの転送 if torch.cuda.is_available(): x = x.to("cuda")

まとめ

PyTorchのtorch.Tensorは、配列の操作性とGPU対応を両立する強力なデータ構造です。基本的な作成・演算・形状変更は、機械学習モデルの実装やデータ前処理において頻繁に使われるため、確実に理解しておくことが重要です。必要に応じて、NumPyと連携させたり、GPU上で高速処理することも可能です。

生成日:2025/05/22