[Pytorch] Tensor의 A-z 까지

Meosun·2024년 8월 9일

AI Tech

목록 보기
2/4

1.Tensor란?

Tensor는 Pytorch의 핵심 데이터 구조이다.
Numpy와 유사한 형태로 N차원의 데이터를 표현하며, 다양한 방법으로 코드 표현이 가능하다.

2.Tensor 생성

Pytorch에서 Tensor의 생성방법은 여러가지가 있다.
일정 값으로 초기화된 Tensor 생성, 값이 초기화 되지 않은 Tensor의 생성, List나 Numpy로 생성하는 방법이 있다.

2-1.초기화된 Tensor의 생성

메서드설명Example
torch.zeros([...])...수만큼 dimension을 가진 Tensor를 생성함(Value = 0)torch.zeros([3,2]) #0차원 = 3 / 1차원 = 2로 생성
torch.ones([...])...수만큼 dimension을 가진 Tensor를 생성함(Value = 1)torch.ones([3,2]) #0차원 = 3 / 1차원 = 2로 생성 [[[1,1],[1,1]],[[1,1],[1,1]]]
torch.rand([...])...수만큼 dimension을 가진 Tensor를 생성함(Value = 균등분포로 0~1사이 난수)torch.rand([3,2]) #0차원 = 3 / 1차원 = 2로 생성
torch.randn([...])...수만큼 dimension을 가진 Tensor를 생성함(Value = 정규분포의 난수)torch.randn([3,2]) #0차원 = 3 / 1차원 = 2로 생성
torch.arange(start = n, end = m, step = s)n 부터 m 까지 s씩 증가하는 1-D Tensor 생성torch.arange(0,100,1)

Tensor간 초기화된 값 변경하는 방법

메서드설명
B = torch.zeros_like(A)B에 A Tensor를 0으로 채운 값을 입력
B = torch.ones_like(A)B에 A Tensor를 1로 채운 값을 입력
B = torch.rand_like(A)B에 A Tensor를 균등분포의 0~1사이 난수로 채운 값을 입력
B = torch.randn_like(A)B에 A Tensor를 정규분포의 난수로 채운 값을 입력

2-2.초기화되지 않은 Tensor 생성

성능 향상메모리 사용에 최적화

  • 불필요하게 Tensor를 바로 덮어쓰기 할때
  • 불필요하게 Tensor를 바로 초기화 할때
메서드설명
B = torch.empty(n)n만큼 크기의 Random Value Tensor를 생성
B = A.fill_(n)Empty Tensor를 n으로 채움

2-3.List or Numpy로 Tensor 생성

메서드설명
B = torch.tensor([...])[...] 배열을 Tensor로 변경
B = torch.from_numpy(A)A-Numpy 배열을 Tensor로 생성

2-4.CPU Tensor 생성

  1. torch.IntTensor([...])
  2. torch.FloatTensor([...])
  3. torch.ByteTensor([...])
  4. torch.CharTensor([...])
  5. torch.ShortTensor([...])
  6. torch.LongTensor([...])
  7. torch.DoubleTensor([...])
  8. etc...

2-5.CUDA Tensor 생성

B = A.to('cuda') # 혹은
B = A.cuda() #로 가능하다.
#기존 Cuda로 작성된 Tensor를 변경할때는
B = A.to('cpu') #혹은
B = A.cpu() #로 가능하다.

2-6.Tensor 복제

  • B = A.clone()
  • B = A.detach()

detach()clone()의 차이점은 detach계산그래프에서 분리해서 Tensor를 복제한다는 점이다.

3.Tensor의 DataType

Tensor의 DataType에는 여러가지가 있다.
보통 dtype이라고 부르며, Tensor가 저장하는 데이터의 유형을 말한다.

유형설명Size
uint8부호가 없는 8bit 정수형(torch.uint8)0 ~ 255
uint16부호가 없는 16bit 정수형(torch.uint16)0 ~ 65,535
uint32부호가 없는 32bit 정수형(torch.uint32 or torch.uint)0 ~ 4,294,967,296
uint64부호가 없는 64bit 정수형(torch.uint64)0~
int8부호가 있는 8bit 정수형(torch.int8 or torch.char)-128 ~ 127
int16부호가 있는 16bit 정수형(torch.int16 or torch.short)-32,768 ~ 32,767
int32부호가 있는 32bit 정수형(torch.int32 or torch.int)-2,148,483,648 ~ 2,147,483,647
int64부호가 있는 64bit 정수형(torch.int64 or torch.long)-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807
float1616bit 실수형(torch.float16)-
float3232bit 실수형(torch.float32 or torch.float)-
float6464bit 실수형(torch.float64 or torch.double)-

3-1.Dtype Casting?

Type Casting이란 먼저 선언한 dtype을 다른 dtype으로 변경하는 것을 말한다.
ex) torch.int -> torch.float etc...

  • 변경 방법
    test = torch.tensor([...],dtype = torch.int8) 일때
    test2 = test.double() 로 하게되면 test2에 dtype = double로 casting된 test가 들어가게 된다.

4.Tensor Indexing & Slicing

Indexing이란 Tensor의 특정위치(Index)에 접근하는 것을 말한다.
Slicing이란 Tensor들 중 일부(부분집합)을 분리하여 새로운 Tensor를 생성하는 과정을 말한다.

  • Index 접근 방법 : A[0,3] #0차원 = 0dim/ 1차원 = 3dim 인 곳에 접근한다. 0행3열 접근
  • Slicing 사용 법 : A[n:m:s] #n부터 m까지 s씩 건너뛰며 선택

5.Tensor의 차원 변경

Tensor의 차원변경 방법에는 여러가지가 있다.

메서드설명
A.reshape(n,m...,z)Tensor A를 (n,m,..z)까지 차원의 수로 변경 한다. -1을 사용하면 자동으로 남은 Dim을 맞춰서 계산해줌
A.view(n,m...,z)reshape()과 동일하지만, 메모리의 연속성이 성립한 경우만 사용 가능하다.(등비수열 혹은 정렬)
A.flatten()Tensor A 1-D Tensor로 평탄화 한다. 혹은 (n,m)등의 값을 입력할 경우 n부터 m차원까지 평탄화
A.transpose(n,m)n번째 차원과 m번째 차원의 dim을 치환
A.squeeze()차원의 축이 1인 것을 축소하는 메서드. argument로 dim=n으로 입력할 경우 n번째 차원의 축이 1인 것을 축소
A.unsqueeze(dim=n)Tensor A를 n번재 차원에 축을 추가(확장)함(축은 1)

6.Tensor간의 연결&결합

메서드설명
torch.stack([A,B],dim =n)A와 B를 쌓는다. 단 둘의 Size가 동일해야만 사용가능하다. Tensor 행렬 값이 입력된 부분은 유지
torch.cat([A,B],dim=n)A와 B를 연결. n번째 차원에 연결한다.

7.Tensor 차원 확장

메서드설명
A.expand(n,m)A-Tensor를 확장. m번째 차원(dim=1)을 n배 만큼 확장한다.
A.repeat(n,m,z...)A-Tensor를 0차원은 n배, 1차원은 m배, 2차원은 z배 ... 반복해서 확장한다.

8.Tensor간의 연산

연산은 서로의 size가 어느정도 달라도 계산이 가능하다.
단 행렬의 기본 연산 방식과 동일하기때문에, 최소한의 조건은 맞춰서 계산해야한다.
계산하고자하는 행렬 갯수가 맞고, 일부 column이 부족한 부분에 대해서는 expand되어 계산된다

  • 산술연산
메서드설명
torch.add(A,B)A-Tensor와 B-Tensor(혹은 상수 B)간 합 계산(동일한 위치 기준)
torch.sub(A,B)A-Tensor와 B-Tensor(혹은 상수 B)간 차 계산(동일한 위치 기준)
torch.mul(A,B)A-Tensor와 B-Tensor(혹은 상수 B)간 곱 계산(동일한 위치 기준)
torch.div(A,B)A-Tensor와 B-Tensor(혹은 상수 B)간 나누기 계산(동일한 위치 기준)
torch.pow(A,B)A-Tensor와 B-Tensor(혹은 상수 B)간 제곱 계산(동일한 위치 기준)
  • 비교연산
메서드설명
torch.eq(A,B)A=B Equal
torch.ne(A,B)A≠B Not Equal
torch.gt(A,B)A>B Greater
torch.ge(A,B)A≥B Greater or Equal
torch.lt(A,B)A<B Lower
torch.le(A,B)A≤B Lower or Eqaul
  • 논리연산
메서드설명
torch.logical_and()논리곱 AND 연산
torch.logical_or()논리합 OR 연산
torch.logical_xor()배타적 논리 합 XOR연산. Scalar가 동일하면 False / Scalar가 다르면 False

9.Inpace 함수와 일반 Torch 함수

Inplcae 함수란 무엇일까?

Inplcae함수는 말그대로 내부 값을 수정시켜주는 함수이다.
예를 들어 A.add가 있고 A.add_라는 함수가 있다. 둘다 A-Tensor에 더해주는 함수이지만 차이가 있다.
A.addA-Tensor값은 그대로 두고 새로 객체를 생성한다.
A.add_A-Tensor의 값 자체를 변경하며, Return 객체로 A를 반환한다.

이처럼 A-Tensor 자체에 접근해서 사용이 필요할때는 Inplcae함수를 쓰면 된다.
Traning시에는 메모리 주소 혹은 값이 꼬일 수 있으니 사용시 유의!

profile
데이터와 AI를 잘 활용하는 Backend Developer가 되자

0개의 댓글