0으로 채워진 벡터나 텐서를 만들 일이 제법 있다.
특히 다른 텐서와 똑같은 모양을 만들 일이 있는데 zeros, ones, zeros_like를 사용하면 tensor의 모양을 일일이 지정해주지 않아도 알아서 똑같은 모양으로 만들어준다.
굉장히 편리한 기능이다.
다음은 지정된 값으로 원하는 모양 shape의 텐서를 만드는 방법들이다.
- zeros는 0으로
- ones는 1로
- full은 지정된 값으로
- empty는 uninitialized values로 채워진다.
import torch
a = torch.zeros(2,3) # 0의 값들
b = torch.ones(2,3) # 1의 값들
c = torch.full((2,3),2) # 지정된 값, 2로 채운다.
d = torch.empty(2,3) # uninitialized values
print(a)
print(b)
print(c)
print(d)
>>
tensor([[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[2, 2, 2],
[2, 2, 2]])
tensor([[1.5766e-19, 1.0256e-08, 1.6408e-07],
[3.0270e+12, 1.7342e-07, 1.6599e-07]])
스택오버플로우를 찾아보니 Uninitialized values를 메모리 블록에 있는 디폴트 값이거나 이전에 저장된 값이라고 한다.
다음은 지정된 값으로, 원하는 텐서와 똑같은 shape의 텐서를 만드는 방법들이다.
아래는 (2, 3) 형태의 tensor c의 모양을 그대로 복사하는 코드다.
e = torch.zeros_like(c)
f = torch.ones_like(c)
g = torch.full_like(c,3)
h = torch.empty_like(c)
print(e)
print(f)
print(g)
print(h)
>>
tensor([[0, 0, 0],
[0, 0, 0]])
tensor([[1, 1, 1],
[1, 1, 1]])
tensor([[3, 3, 3],
[3, 3, 3]])
tensor([[93825571362288, 93825525538880, 160],
[ 112, 93802665438129, 0]])
- zeros_like는 0으로
- ones_like 는 1로
- full_like 은 지정된 값으로
- empty_like 는 uninitialized values로 채워진다.
아래는 좀 더 복잡한 3차원 이상의 텐서에 대한 예시다.
차원이 커져서 출력을 보면 더 헷갈리는거 같아서 생성된 텐서의 모양만 덧붙인다.
c = torch.full((2, 5, 3),2)
e = torch.zeros_like(c)
f = torch.ones_like(c)
g = torch.full_like(c,3)
h = torch.empty_like(c)
print(e.shape)
print(f.shape)
print(g.shape)
print(h.shape)
>>
torch.Size([2, 5, 3])
torch.Size([2, 5, 3])
torch.Size([2, 5, 3])
torch.Size([2, 5, 3])
추가적으로 identity matrix 단위 행렬을 만드는 방법도 추가한다.
torch.eye(3)
>> tensor([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
References:
https://velog.io/@dusruddl2/torch.ones-zeros-full-empty%EC%97%90-%EB%8C%80%ED%95%98%EC%97%AC
https://pytorch.org/docs/stable/generated/torch.empty.html
https://stackoverflow.com/questions/51140927/what-is-uninitialized-data-for-empty-in-pytorch
https://pytorch.org/docs/stable/generated/torch.eye.html#torch.eye
'AI Codes > PyTorch' 카테고리의 다른 글
PyTorch Random Number Generating (0) | 2025.04.20 |
---|---|
PyTorch Products (0) | 2025.04.20 |
nanoGPT, PyTorch DDP, LLM 시각화 (0) | 2025.04.18 |
PyTorch pre-trained Models (0) | 2025.04.17 |
PyTorch Tensor의 차원 변환 (0) | 2025.04.16 |