テンソル
テンソルは配列や行列によく似た特殊データの構造。PyTorchではモデルの入出力そしてモデルのパラmー他をエンコードするために使用
必要な資材のインポート
import torch
import numpy as np
テンソルを初期化する
#データから直接
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
print(x_data)
#NumPy配列から
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print(x_np)
#別なテンソルから
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
tensor([[1, 2],
[3, 4]])
tensor([[1, 2],
[3, 4]])
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.9813, 0.7410],
[0.8749, 0.3660]])
ランダム値または低数値を使用する場合
shape
→テンソルの次元を表す(タプル形式)
rand
→ランダムな値をセット
ones
→ALL1をセット
zeros
→ALL0をセット
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
Random Tensor:
tensor([[0.0996, 0.2866, 0.8525],
[0.7895, 0.0966, 0.6891]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
テンソルの属性
.shape
→テンソルのサイズを出力
.dtype
→データの型を出力
.device
→格納されたデバイスを出力
tensor = torch.rand(3,4)
print(tensor)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
テンソルに対する演算
torch.accelerator.is_available()
→テンソルはデフォルトではCPU上で実行される。アクセラレータの場合下記行が実行される。
# We move our tensor to the current accelerator if available
if torch.accelerator.is_available():
tensor = tensor.to(torch.accelerator.current_accelerator())
標準的なNumPyライクなインデックス付けとスライス
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 1., 0., 1.],
[1., 1., 0., 1.],
[1., 1., 0., 1.],
[1., 1., 0., 1.]])
テンソルは結合できる
torch.catでtensor同士で結合できる
dim=0:縦方向に結合、dim=1:横方向に結合
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
算術演算
※下記は内積の計算(意味不)
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)
# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
単一要素テンソル
.item()でPythonの数値に変換できる
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
12.0
インプレース操作
add_
→メモリ領域を直接操作することが可能
(※履歴からすぐ消えてしまうため推奨されないよう、、、)
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor([[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.]])
NumPyへの変換
torch.onesで1の配列を作成。テンソルの形で作成される
.numpy()でnumpyに変換
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t.add_(1)を追加し、実行すると
print(f"t: {t}")
print(f"n: {n}")
tensor,numpy配列両方に反映される
:::note
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
:::
t = torch.from_numpy(n)
→numpyからtensorに変換できる
*NumPy配列に変更を加えたらtensorにも変更が行われる