import torch
import numpy as np
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
x_ones = torch.ones_like(x_data) # x_data의 속성을 유지합니다.
print(f"Ones Tensor: \n {x_ones} \n")
#ones_like 1로 채워진 텐서를 만들어줌
x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 속성을 덮어씁니다.
print(f"Random Tensor: \n {x_rand} \n")
#int로 정하고 싶으면 torch.randint_like를 사용해야함
->결과
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}")
->결과
tensor = torch.rand(3,4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
#넘파이 배열이니까 float32
print(f"Device tensor is stored on: {tensor.device}")
->결과
-기본적으로 Tensor는 CPU에 생성됩니다.
-.to 메서드를 사용하면 GPU의 가용성을 확인한 뒤 GPU로 텐서를 명시적으로 이동할 수있음
* 장치간에 큰 tensor들을 복사하는 것은 시간과 메모리 측면에서 비용이 많이 들어감
# GPU가 존재하면 텐서를 이동합니다
if torch.cuda.is_available():
tensor = tensor.to("cuda")
print(torch.acos(tensor))
-결과
코드
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)
결과
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
#torch.stack은 뭐가 다른 것인가?,stack의 dim=2이해 https://rfriend.tistory.com/781
t2 = torch.stack([tensor,tensor,tensor], dim=1)
print(t2)
cat의 경우 새로운 차원으로 확장하지 않고 주어진 차원을 기준으로
-합치려는 차원을 제외한 나머지 차원의 shape는 모두 동일해야함
stack은 새로운 차원으로 주어진 텐서들을 붙입니다.
-예를 들어 (3,4) shape(크기)의 텐서 A를 붙이는 경우
-torch.cat([A,A], dim=0)의 결과는 (6,4)의 크기를 갖고
-torch.stack([A,A], dim=0)의 결과는 (2,3,4)의 크기를 갖습니다.
-결과
# 두 텐서 간의 행렬 곱(matrix multiplication)을 계산합니다. y1, y2, y3은 모두 같은 값을 갖습니다.
# ``tensor.T`` 는 텐서의 전치(transpose)를 반환합니다.
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)
#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)
-결과
-텐서의 모든 값을 하나로 집계하여 요소가 하나인 텐서의 경우, item()을 사용하여 python 숫자 값으로 반환할 수 있습니다.
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
결과
-연산 결과를 피연산자(operand)에 저장하는 연산을 바꿔치기 연산이라고 부르며, 접미사를 갖습니다. 예를 들어: x.copy(y) 나 x.t()는 x를 변경합니다.
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
결과
-Note
-바꿔치기 연산은 메모리를 일부 절약하지만, 기록(history)이 즉시 삭제되어 도함수(derivative) 계산에 문제가 발생할 수 있습니다. 따라서, 사용을 권장하지 않습니다.
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
결과
-텐서의 변경 사항이 Numpy 배열에 반영됩니다.
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
n = np.ones(5)
t = torch.from_numpy(n)
-Numpy 배열의 변경 사항이 텐서에 반영됩니다.
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
-결과
좋은 글 감사합니다. 자주 올게요 :)