tensor 기초

 

tensor 생성 방법
  1. torch.rand() : 0과 1 사이의 숫자를 균등하게 생성
  2. torch.rand_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
  3. torch.randn() : 평균이 0이고 표준편차가 1인 가우시안 정규분포를 이용해 생성
  4. torch.randn_like() :  사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
  5. torch.randint() : 주어진 범위 내의 정수를 균등하게 생성, 자료형은 torch.float32
  6. torch.randint_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
  7. torch.randperm() : 주어진 범위 내의 정수를 랜덤하게 생성
  8. torch.empty() : 임의의 행렬을 생성

 

특정 값을 가지는 tensor 생성
  1. torch.arange() : 주어진 범위 내의 정수를 순서대로 생성
  2. torch.ones() : 주어진 사이즈의 1로 이루어진 텐서 생성
  3. torch.zeros() : 주어진 사이즈의 0으로 이루어진 텐서 생성
  4. torch.ones_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
  5. torch.zeros_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
  6. torch.linspace() : 시작점과 끝점을 주어진 갯수만큼 균등하게 나눈 간격점을 행벡터로 출력
  7. torch.logspace() : 시작점과 끝점을 주어진 갯수만큼 로그간격으로 나눈 간격점을 행벡터로 출력

 

 

# torch 생성
x = torch.rand(3, 3)    # 3 x 3 tensor 생성
print(x)

x = torch.rand_like(x, dtype=torch.float64) # 사이즈를 기존 텐서로 정의
print(x)

x = torch.randn(3, 3)
print(x)

x = torch.rand_like(x, dtype=float)
print(x)

x = torch.zeros(3, 2)
print(x)
print(x.size())

x = torch.tensor([1, 2, 3])
print(x)
print(x.size())

 

 

tensor 연산
x = torch.rand(2, 3)
y = torch.rand(2, 3)
print(x)
print(y)

# 덧셈
print(x + y)
print(torch.add(x, y))
result = torch.empty(2, 3)
torch.add(x, y, out=result)
print(result)
print(y.add_(x))        # in-place 방식

x = torch.Tensor([[1, 3,],
                  [4, 7]])
y = torch.Tensor([[2, 4],
                  [7, 9]])
print(x)
print(y)

# 뺄셈
print(x - y)
print(torch.sub(x, y))
print(x.sub_(y))

# 곲셈
print(x * y)
print(torch.mul(x, y))
print(x.mul_(y))

# 나눗셈
print(x / y)
print(torch.div(x, y))
print(x.div_(y))

# 행렬곱 - dot
print(torch.mm(x, y))

# 인덱싱
print(x)
print(x[: 1])

 

 

tensor 기초 함수
  1. view()
  2. item()
  3. squeeze()
  4. unsqueeze()
  5. stack()
  6. cat()
  7. chuck()
  8. split()
  9. numpy()
  10. from_numpy()
  11. to()
# view - 텐서의 크기나 모양을 변경
x = torch.randn(4, 5)
y = x.view(20)
z = x.view(4, -1)   # 4 x 자동으로

print(x.shape)
print(y.shape)
print(z.shape)


# item - 텐서에 값이 단 하나라도 존재하면 숫자값을 얻을 수 있음, 스칼라 값 하나만 존재해야함
x = torch.randn(1)
print(x)
print(x.item())
print(x.dtype)


# squeeze - 차원을 축소(제거)
print('\n\n')
tensor = torch.rand(1, 3, 3)
print(tensor)
print(tensor.shape) # [1, 3, 3]

t = tensor.squeeze()
print(t)
print(t.shape)  # [3, 3]


# unsqueeze - 차원을 증가(생성)
print('\n\n')
tensor = torch.rand(1, 3, 3)
print(tensor.shape) # [1, 3, 3]

t = tensor.unsqueeze(dim=0)
print(t)
print(t.shape)  # [1, 1, 3, 3]


# stack - 텐서간 결합
print('\n\n')
x = torch.FloatTensor([1, 4])
y = torch.FloatTensor([2, 5])
z = torch.FloatTensor([3, 6])
print(torch.stack([x, y, z]))


# cat
# - 텐서를 결합하는 메소드 (concatenate)
# - 넘파이의 stack과 유사하지만, 쌓을 dim이 존재해야함.
#   . 예를 들어, 해당 차원을 늘려준 후 결합

print('\n\n')
a = torch.randn(1, 1, 3, 3)
b = torch.randn(1, 1, 3, 3)
c = torch.cat((a, b), dim=2)

print(c)
print(c.size())


# chuck - 텐서를 여러개로 나눌때 사용, 몇개의 텐서로 나눌것이냐
print('\n\n')
tensor = torch.rand(3, 6)
t1, t2, t3 = torch.chunk(tensor, 3, dim=1)
print(tensor)
print(t1)
print(t2)
print(t3)




# split - chunk와 동일한 기능이지만 조금 다름. 하나의 텐서당 크기가 얼마냐
print('\n\n')
tensor = torch.rand(3, 6)
t1, t2 = torch.split(tensor, 3, dim=1)
print(tensor)
print(t1)
print(t2)

# torch <-> numpy
#  - numpy()
#  - from_numpy()
# (참고) tensor가 cpu 상에 있다면 numpy 배열은 메모리 공간을 공유하므로 하나가 변하면, 다른 하나도 변함
print('\n\n')

a = torch.ones(7)
print(a)

b = a.numpy()
print(b, type(b))

a.add_(1)
print(a)    # a 값이 변함
print(b)    # b 값도 변함


import numpy as np

a = np.ones(7)
b = torch.from_numpy(a)
np.add(a, 1, out=a)

print(a)    # a 값이 변함
print(b)    # b 값도 변함



# CUDA Tensor
#   - .to 메소드를 사용하여 텐서를 어떠한 장치로도 옮길 수 있음
print('\n\n')
x = torch.randn(1)
print(x)
print(x.item())
print(x.dtype)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

y = torch.ones_like(x, device=device)
x = x.to(device)
z = x + y
print(device)
print(z)
print(z.to('cpu', torch.double))

+ Recent posts