PyTorch

PyTorch Tensor의 자료형에 대하여

sejongmin 2024. 8. 7. 22:04

 

PyTorch()의 Tensor에는 여러가지 자료형이 있습니다.

여러가지 자료형에 대해 소개하고, Tensor에 적절한 자료형을 할당하는 방법입니다


Tensor의 자료형의 종류

1. 논리형

8비트 torch.bool True, False

 

2. 정수형

8비트 torch.int8 또는
torch.char
-2  ~ 2 - 1
(-128 ~ 128)
16비트 torch.int16 또는
torch.short
-2¹⁵ ~ 2¹⁵ - 1
(-32,768 ~ 32,767)
32비트 torch.int32 또는
torch.int
-2³¹ ~ 2³¹ - 1
(-2,147,483,648 ~ 2,147,483,647)
64비트 torch.int64 또는
torch.long
-2⁶³ ~ 2³    - 1
(-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807)

 

 

3. 실수형

16비트 torch.float16 또는 
torch.half
± 5.96 × 10  ~ ± 6.55 × 10
32비트 torch.float32 또는 
torch.float
± 1.40 × 10 ~ ± 3.40 × 10³
64비트 torch.float64 또는
torch.double
± 4.94 × 10³² ~ ± 1.79 × 10³

 

 

⭐️ 부호가 없는 정수형은 torch.uint8 (0~2), torch.uint16(0~2¹⁶) 등으로 표현할 수 있습니다.

Tensor 생성시 자료형 정해주기

1. dtype

- torch.tensor로 생성할 때 dtype을 통해 tensor의 데이터 타입을 정할 수 있습니다.

torch.tensor([1, 2], dtype=torch.int)
torch.tensor([1, 2], dtype=torch.float)

 

2. Tensor

- tensor의 종류에 따라 tensor의 데이터 타입을 정할 수 있습니다.

x = torch.CharTensor([1, 2])		# dtype int8
x = torch.ShortTensor([1, 2])		# dtype int16
x = torch.IntTensor([1, 2])		# dtype int32
x = torch.LongTensor([1, 2])		# dtype int64
x = torch.HalfTensor([1, 2])		# dtype float16
x = torch.FloatTensor([1, 2])		# dtype float32
x = torch.DoubleTensor([1, 2])		# dtype float64

Tensor 생성 이후 자료형 정해주기

1. int()

- 변환하고자 하는 데이터타입에 맞는 메소드를 이용해 변환할 수 있습니다.

x = x.int()		# dtype torch.int32
x = x.float()		# dtype torch.float32
x = x.double()		# dtype torch.float64

 

2. type()

- 데이터타입을 직접 지정해 변환할 수 있습니다.

x = x.type(torch.int32)		# dtype torch.int32
x = x.type(torch.long)		# dtype torch.int64
x = x.type(torch.float32)	# dtype torch.float32
x = x.type(torch.double)	# dtype torch.float64

 

3. to()

- 데이터타입을 직접 지정해 변환할 수 있습니다.

x = x.to(torch.int32)		# dtype torch.int32
x = x.to(torch.long)		# dtype torch.int64
x = x.to(torch.float32)		# dtype torch.float32
x = x.to(torch.double)		# dtype torch.float64

 

⭐️ Tensor의 자료형을 변환하는 것을 타입캐스팅 이라고 합니다.
⭐️ Tensor의 자료형을 변경시 할당하지 않으면 Tensor는 변하지 않습니다.
⭐️
데이터타입이 torch.float에서 torch.int로 변환하면 소수점은 버려집니다.
⭐️
데이터타입이 torch.bool에서 torch.int로 변환하면 True는 1, False는 0이 됩니다.

 


참고

Pytorch(https://pytorch.org/docs/stable/tensors.html#)