텐서(tensor)는 배열(array)이나 행렬(matrix)과 매우 유사한 특수한 자료구조이다. PyTorch에서는 텐서를 사용하여 모델의 입력(input)과 출력(output), 그리고 모델의 매개변수들을 부호화(encode)한다.
텐서는 GPU나 다른 하드웨어 가속기에서 실행할 수 있다는 점만 제외하면 NumPy 의 ndarray와 유사하다. 실제로 텐서와 NumPy 배열(array)은 종종 동일한 내부(underly) 메모리를 공유할 수 있어 데이터를 복사할 필요가 없다. (NumPy 변환(Bridge) 참고) 텐서는 또한 자동 미분(automatic differentiation)에 최적화되어 있다.
텐서(tensor) 자료형 데이터를 만드는 방법
텐서 자료형 데이터를 만드는 방법은 3가지가 있다.
- 리스트나 Numpy 배열을 텐서로 변환
- 0 또는 1 등의 특정한 값을 가진 텐서를 생성
- 랜덤한 값을 가지는 텐서를 생성
1) 리스트나 Numpy 배열을 텐서로 변환
리스트를 텐서 자료형으로 바꾸려면 torch.tensor() 또는 torch.as_tensor(), torch.from_numpy() 명령을 사용한다.
데이터로부터 직접(directly) 생성하기
데이터로부터 직접 텐서를 생성할 수 있다. 데이터의 자료형(data type)은 자동으로 유추한다.
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
Numpy 배열로부터 생성하기
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
2) 0 또는 1 등의 특정한 값을 가진 텐서를 생성
- ones_like(x): x와 똑같은 shape의 1로 가득찬 tensor
- zeros_like(x): x와 똑같은 shape의 0으로 가득찬 tensor
=> 둘은 같은 device에 tensor를 선언해준다.
x_ones = torch.ones_like(x_data) # x_data의 속성을 유지합니다.
print(f"Ones Tensor: \n {x_ones} \n")
"""
Ones Tensor:
tensor([[1, 1],
[1, 1]])
"""
3) 랜덤한 값을 가지는 텐서를 생성
- torch.rand() : 0과 1 사이의 숫자를 균등하게 생성
- torch.rand_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
- torch.randn() : 평균이 0이고 표준편차가 1인 가우시안 정규분포를 이용해 생성
- torch.randn_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
- torch.randint() : 주어진 범위 내의 정수를 균등하게 생성, 자료형은 torch.float32
- torch.randint_like() : 사이즈를 튜플로 입력하지 않고 기존의 텐서로 정의
- torch.randperm() : 주어진 범위 내의 정수를 랜덤하게 생성
x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 속성을 덮어씁니다.
print(f"Random Tensor: \n {x_rand} \n")
"""
Random Tensor:
tensor([[0.3516, 0.5723],
[0.8038, 0.6293]])
"""
텐서의 속성(Attribute)
텐서의 속성은 텐서의 모양(shape), 자료형(datatype) 및 어느 장치에 저장되는지를 나타낸다.
tensor = torch.rand(3,4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Out:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
텐서 연산(Operation)
전치(transposing), 인덱싱(indexing), 슬라이싱(slicing), 수학 계산, 선형 대수, 임의 샘플링(random sampling) 등, 100가지 이상의 텐서 연산들을 여기에서 확인할 수 있다.
기본적으로 텐서는 CPU에 생성된다. .to 메소드를 사용하면 (GPU의 가용성(availability)을 확인한 뒤) GPU로 텐서를 명시적으로 이동할 수 있다. 장치들 간에 큰 텐서들을 복사하는 것은 시간과 메모리 측면에서 비용이 많이든다는 것을 기억하자.
# GPU가 존재하면 텐서를 이동합니다
if torch.cuda.is_available():
tensor = tensor.to('cuda')
Numpy식의 표준 인덱싱과 슬라이싱
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)
Out:
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
텐서 합치기
torch.cat을 사용하여 주어진 차원에 따라 일련의 텐서를 연결할 수 있다. torch.cat과 미묘하게 다른 또 다른 텐서 결합 연산인 torch.stack도 있다.
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
"""
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
"""
참고: https://tutorials.pytorch.kr/beginner/basics/tensorqs_tutorial.html, https://bigdatadiary0819.tistory.com/60
'Python > PyTorch' 카테고리의 다른 글
[Pytorch] Dataset과 Dataloader (0) | 2021.09.25 |
---|---|
[Pytorch] .requires_grad(), torch.no_grad(), model.eval() (0) | 2021.09.06 |
Custom Dataset 생성 (0) | 2021.08.25 |
[부스트코스] [파이토치로 시작하는 딥러닝 기초] 딥러닝을 학습시키는 단계 (0) | 2021.01.27 |
[Pytorch] torch has no "from_numpy" member (0) | 2020.08.02 |