부스트캠프 AI Tech 2일차

Ryu Jihoon·2024년 8월 6일
post-thumbnail

데이터 타입

PyTorch Docs datatype

tensor 생성 함수

a = torch.tensor(1, dtype = torch.uint8)

정수형

  • 부호 유무, 크기에 따라 나뉨
  • u는 unsigned(부호가 없음)을 뜻함, signed보다 양의 정수를 2배+1 더 표현 가능
  • 크기에 따라 int8/uint8(byte 불가), int16/uint16(short), int32/uint32(int), int64/uint64(long)

실수형

  • 32,64 bit 부동소수점
  • float32(float), float64(double)

타입 캐스팅

b=a.float()
c=b.double()

  • 메모리 부담 줄일 수 있음

기초 함수 및 메소드

  • torch.sum(a): 합
  • torch.prob(a): 곱
  • torch.mean(a): 평균
  • torch.var(a): 표본분산
  • torch.std(a): 표본표준편차
  • a.dim(): 치원 수
  • a.size(): tensor의 모양(크기), 함수
  • a.shape: tensor의 모양(크기), attribute
  • a.numel(): tensor의 요소의 총 개수
    (number of elements)

Tensor 생성

  • default data type은 float32

  • a=torch.zeros(5): 0으로 초기된 1차원 tensor

  • b=torch.ones([1,4,3]): 1로 초기된 3차원 tensor

  • c=torch.zeros_like(b): 크기와 자료형 유지한 채로 원소들만 0으로 초기화, 원본 tensor와 같은 device상에 있는 메모리 주소에 할당됨

  • d=torch.ones_loke(a): 크기와 자료형 유지한 채로 원소들만 1로 초기화, 원본 tensor와 같은 device상에 있는 메모리 주소에 할당됨

  • j = torch.rand([2, 3]): 0~1 사이의 연속균등분포에서 추출한 난수로 채워진 특정 크기의 tensor를 생성

  • k = torch.randn(3): 표준정규분포에서 추출한 난수로 채워진 특정 크기의 tensor를 생성

  • m = torch.rand_like(k): 크기와 자료형 유지한 채로 [0, 1] 구간의 연속균등분포 난수 tensor

  • n = torch.randn_like(i): 크기와 자료형 유지한 채로 표준정규분포 난수 tensor

  • o = torch.arange(start = 1, end = 11, step = 2): 범위 내에서 일정 간격의 값을 가진 tensor (arange=array range) (매개뱐수 생략 가능, 인자 중 하나라도 실수면 dtype은 float로 바뀜, 현재는 int64)

  • q = torch.empty(5): 초기화 되지 않은 tensor (성능 향상, 메모리 사용 최적화)

  • q.fill_(3.0): 초기화 되지 않은 tensor에 다른 데이터로 수정, 메모리 주소 유지

  • t = torch.tensor(s): list로 tensor 생성 (s = [1, 2, 3, 4, 5, 6])

  • v = torch.from_Numpy(u): numpy 데이터로 tensor 생성 (u = np.array([[0, 1], [2, 3]]))

  • CPU tensor=legacy constructor?

Tensor 복제

x = torch.tensor([1, 2, 3, 4, 5, 6])

  • y = x.clone()/z = x.detach()
  • 메모리 관리: clone()은 원본 텐서와 별도의 메모리 공간을 사용하지만, detach()는 원본과 동일한 데이터를 공유
  • 계산 그래프: clone()은 계산 그래프에 남아 있을 수 있지만, detach()는 계산 그래프에서 분리되어 역전파에 영향 x
    (아직 이해 못 함)

CUDA Tensor

a = torch.tensor([1, 2, 3])

  • a.device: tensor의 현재 device 위치
  • torch.cuda.is_available(): CUDA 기술을 사용할 수 있는 환경인지 확인
  • torch.cuda.get_device_name(device=0): CUDA device 이름을 확인
  • Tensor를 GPU에 할당: b = torch.tensor([1, 2, 3, 4, 5]).to(‘cuda’)/b = torch.tensor([1, 2, 3, 4, 5]).cuda()
  • Tensor를 CPU Tensor로 변환: c = b.to(device = ‘cpu’)/c = b.cpu()
profile
CSE Junior

0개의 댓글