스터디노트 (PyTorch 1)

zoe·2023년 7월 14일
0

Tensor 다루기

import torch
import numpy as np
  • PyTorch에서는 Tensor type이 Variable과 Constant를 포함

  • 기존에는 Variable 타입이 있었지만, 이는 자동미분을 위한 것이었는데, 이 기능을 Tensor 타입에 포함시킴

기존의 데이터를 Torch의 Tensor

  • torch.tensor()
  • torch.as_tensor()
  • torch.from_numpy()

특정한 값의 Tensor 생성하기로

  • torch.arange(10)
  • torch.ones()
  • torch.zeros()
  • torch.zeros_like(arr) -> Tensor를 입력해야함.
    - torch.ones_like()
    - torch.zeros_like()
  • torch.linspace()
  • torch.logspace()

난수 생성하기

  • torch.manual_seed()
  • torch.rand() : 균등분포
  • torch.randn() : normal 분포
  • torch.randint

데이터 타입

  • tensor_var.type() -> inplace 명령이 아님

GPU 사용하기

GPU 를 사용하기 위해 Cuda에서 사용하는 데이터타입으로 바꾸어줘야 한다.
방법 세가지!

  • 만들 때, device 설정해두기
  • tensor_var.cuda()
  • tensor_var.to(device)

대부분 이렇게 사용

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

a = torch.rand(2)
print(a)

a = a.to(device)
print(a)




텐서 연산

import torch

기본 연산

x = torch.arange(0, 5)
y = torch.arange(1, 6)
print(x + y)
print(torch.add(x, y))
print(x.add(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))
print(x**y)
print(torch.pow(x, y))
print(x.pow(y))
print(-x)
print(torch.negative(x))
print(x.negative())
  • torch.abs: 절대값
  • torch.sign: 부호
  • torch.round: 반올림
  • torch.ceil: 올림
  • torch.floor: 내림
  • torch.square: 제곱
  • torch.sqrt: 제곱근
  • torch.maximum: 두 텐서의 각 원소에서 최댓값만 반환.
  • torch.minimum: 두 텐서의 각 원소에서 최솟값만 반환.
  • torch.cumsum: 누적합
  • torch.cumprod: 누적곱
print(torch.abs)
print(torch.sign)
print(torch.round)
print(torch.ceil)
print(torch.floor)
print(torch.square)
print(torch.sqrt)
print(torch.maximum)
print(torch.minimum)
print(torch.cumsum)
print(torch.cumprod)

차원 축소 연산

  • PyTorch는 기본이 reduce 연산
x = torch.randint(10, size=(5, 2, 4))
print(x.shape)
print(x)
print(torch.sum(x))
print(torch.sum(x).shape)
print(torch.sum(x, dim=1))
print(torch.sum(x, dim=1).shape)
print()
print(torch.sum(x, dim=2))
print(torch.sum(x, dim=2).shape)

행렬 연산

a = torch.tensor([[2, 0], [0, 1]], dtype=torch.float32)
b = torch.tensor([[1, 1], [1, 1]], dtype=torch.float32)
a, b
torch.matmul(a, b), torch.mm(a, b)
torch.linalg.inv(a)

크기와 차원을 바꾸는 명령

  • torch.reshape
  • .view
  • torch.transpose
print(a.view(4, -1), a.view((4, -1)), sep="\n")
print(a.view(4, -1).shape, a.view((4, -1)).shape)
torch.reshape(a, (4, -1))
# view함수가 있어 expand_dims 같은 함수가 따로 필요없다. 
a.view((1, 4, 1)), a.view((1, 4, 1)).shape
print(torch.squeeze(a.view((1, 4, 1)), dim=2))
print(torch.squeeze(a.view((1, 4, 1)), dim=2).shape)
  • expand_dims 함수 대신에 unsqueeze 함수가 있다.
print(torch.unsqueeze(a.view((1, 4)), dim=2))
print(torch.unsqueeze(a.view((1, 4)), dim=2).shape)
  • 여러 함수가 torch.명령어 형태, tensor.명령어 로 사용 할 수 있다.
a = torch.arange(10).view(5, 2)
a
a.transpose(1, 0)
torch.transpose(a, 1, 0)
  • 함수 끝에 _를 붙이면 inplace명령이 된다.(안되는 함수가 존재함)
a
print(a)
print(a.transpose_(0, 1))
print(a)
a.shape

형상 연산 중 유용한 것

a
b = torch.arange(10).view(2, 5)
b
# a = a.contiguous()
print(a.view_as(b))
print(a.reshape_as(b))

indexing, slicing

a[0]
a[0, 1]
a[4, 1]
a[:2]

텐서를 나누거나 두 개 이상의 텐서를 합치는 명령

  • 나누는 연산
c = torch.rand(3, 6)
c
c1, c2, c3 = torch.chunk(c, 3, dim=1)
print(c1)
print(c2)
print(c3)
c1, c2, c3 = torch.chunk(c, 3, dim=0)
print(c1)
print(c2)
print(c3)
torch.split(c, 1, dim=0)
torch.split(c, 2, dim=1)
torch.split(c, 3, dim=1)
  • 결합 연산
a = torch.ones(2, 3)
b = torch.zeros(3, 3)
a, b
torch.cat([a, b], dim=0)
torch.cat([a, b], dim=1)
a = torch.ones_like(b)
a, a.size()
b, b.size()
torch.stack([a, b], dim=1), torch.stack([a, b], dim=1).size()
torch.stack([a, b], dim=0), torch.stack([a, b], dim=0).size()
torch.stack([a, b], dim=2), torch.stack([a, b], dim=2).size()
torch.tile(a, (3, 1))
torch.tile(a, (1, 2))

어렵다...
💻 출처 : 제로베이스 데이터 취업 스쿨

profile
#데이터분석 #퍼포먼스마케팅 #데이터 #디지털마케팅

0개의 댓글