Tensor(텐서) : array(배열)이나 matrix(행렬)과 매우 유사한 자료구조
# GPU가 존재하면 tensor를 이동
if torch.cuda.is_available():
tensor = tensor.to("cuda")
import torch
import numpy as np
# list -> tensor
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
# numpy array -> tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
# tensor -> numpy array
new_np_array = x_np.numpy()
# tensor -> another tensor
x_ones = torch.ones_like(x_data) # x_data의 shape, type은 유지. value는 1
# print : tensor([[1, 1], [1, 1]])
x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 shape, type은 유지. value는 float type 중에서 random으로
# print : tensor([[0.0965, 0.2738], [0.9675, 0.2934]])
shape = (2,3,)
rand_tensor = torch.rand(shape)
# print : tensor([[0.8398, 0.8787, 0.4099], [0.6517, 0.2316, 0.1294]])
ones_tensor = torch.ones(shape)
# print : tensor([[1., 1., 1.], [1., 1., 1.]])
zeros_tensor = torch.zeros(shape)
# print : tensor([[0., 0., 0.], [0., 0., 0.]])
tensor = torch.rand(3,4)
tensor.dim() # 2 ( rank, 차원 )
tensor.shape # torch.Size([3, 4])
tensor.size() # torch.Size([3, 4])
tensor.dtype # ex. torch.float32
tensor.device # cpu or cuda(gpu)
tensor = torch.ones(4, 4)
# print : tensor([[1., 1., 1., 1.],
# [1., 1., 1., 1.],
# [1., 1., 1., 1.],
# [1., 1., 1., 1.]])
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
# print : 3가지 모두 tensor([1., 1., 1., 1.])
tensor[:,1] = 0
# print : tensor([[1., 0., 1., 1.],
# [1., 0., 1., 1.],
# [1., 0., 1., 1.],
# [1., 0., 1., 1.]])
t1 = torch.cat([tensor, tensor, tensor], dim=1)
# print : tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
# [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
# [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
# [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
# 두 텐서 간의 행렬 곱(matrix multiplication)을 계산합니다. y1, y2, y3은 모두 같은 값을 갖습니다.
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
# 요소별 곱(element-wise product)을 계산합니다. z1, z2, z3는 모두 같은 값을 갖습니다.
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
agg = tensor.sum() # 요소가 1개인 tensor ( scalar)
agg_item = agg.item() # tensor ( scalar ) -> python number value
print(agg_item, type(agg_item))
# 12.0 <class 'float'>
print(f"{tensor} \n")
# tensor([[1., 0., 1., 1.],
# [1., 0., 1., 1.],
# [1., 0., 1., 1.],
# [1., 0., 1., 1.]])
tensor.add_(5)
print(tensor)
# tensor([[6., 5., 6., 6.],
# [6., 5., 6., 6.],
# [6., 5., 6., 6.],
# [6., 5., 6., 6.]])
t = torch.ones(5)
# t: tensor([1., 1., 1., 1., 1.])
n = t.numpy()
# n: [1. 1. 1. 1. 1.]
bridge
t.add_(1)
# t: tensor([2., 2., 2., 2., 2.])
n = t.numpy()
# n: [2. 2. 2. 2. 2.]
n = np.ones(5)
t = torch.from_numpy(n)
bridge
np.add(n, 1, out=n)
# t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
# n: [2. 2. 2. 2. 2.]
참조