PyTorch Tensor 생성과 조작 방법

AFL·2025년 9월 5일

특정 값으로 초기화된 tensor 생성

a = torch.zeros(*size) : 0으로 채워진 size 크기의 tensor 생성

a = torch.ones(*size) : 1로 채워진 size 크기의 tensor 생성

a = torch.zeros_like(input) : 0으로 채워진 input과 같은 크기의 tensor 생성

a = torch.ones_like(input) : 1로 채워진 input과 같은 크기의 tensor 생성

난수로 초기화된 tensor 생성

i = torch.rand(*size) : 0-1 사이의 연속균등분포에서 추출한 난수로 채워진 size 크기의 tensor 생성

i = torch.randn(*size) : 평균이 0이고 표준 편차가 1인 표준정규분포에서 추출한 난수로 채워진 size 크기의 tensor 생성

i = torch.rand_like(input) : input의 크기와 자료형이 같은 0-1 구간의 연속균등분포 난수 tensor 로 변환

i = torch.randn_like(input) : input의 크기와 자료형이 같은 표준정규분포 난수 tensor로 변환

초기화되지 않은 tensor 생성

a = torch.empty(*size) : 초기화되지 않은 값으로 size 크기의 tensor 생성

a.fill_(value) : tensor a를 value로 채움

numpy로부터 tensor 생성

u = np.array([[0,1], [2,3]])

v = torch.from_numpy(u) : numpy u 를 tensor v로 생성하는 코드

v = torch.from_numpy(u).float() : numpy로부터 생성된 tensor는 기본적으로 정수형이므로 실수형으로 타입캐스팅 필요

CUDA tensor

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

a.device : tensor가 어떤 device에 있는지 확인

torch.cuda.is_available() : cuda 쓸 수 있는 환경인지 확인

torch.cuda.get_device_name(device=0) : cuda device 이름 확인

a = torch.tensor([1,2,3]).to('cuda') : tensor를 gpu에 할당

a = torch.tensor([1,2,3]).cuda() : tensor를 gpu에 할당

b = a.to(device='cpu') : gpu에 할당된 tensor를 cpu에 할당

b = a.cpu() : gpu에 할당된 tensor를 cpu에 할당

tensor의 모양 변경

a = tensor.view(*shape) : tensor의 모양 변경하는 방법. tensor의 메모리가 연속적으로 할당된 경우 사용.

a = tensor.reshape(*shape) : tensor의 모양 변경하는 방법. 메모리가 연속적이지 않아도 사용 가능.

a = torch.flatten(input, start_dim=0, end_dim=-1) : input tensor를 평탄화. start_dim 차원 부터 end_dim 차원까지.

a = tensor.transpose(dim0, dim1) : tensor의 dim0 과 dim1 축을 바꿈.

a = torch.squeeze(input, dim) : tensor에서 특정 차원을 축소

a = torch.unsqueeze(input, dim) : tensor에서 특정 차원 확장

a = torch.stack(tensors, dim) : 새로운 차원으로 주어진 tensor들을 붙임

a = torch.cat(tensors, dim) : 주어진 차원 dim을 기준으로 주어진 tensor들을 붙임

a = tensor.expand(*size) : tensor의 차원이 크기가 1일 때, size로 크기를 확장

a = tensor.repeat(*repeats) : tensor의 요소를 반복해서 크기를 확장.

torch.view와 torch.reshape 함수의 차이

  • contiguous 속성을 만족하지 않는 텐서에 적용이 가능한지에 따라 다름, view는 contiguous 속성이 만족되지 않는 경우 사용이 제한됨.

torch.stack(), torch.cat() 의 차이

  • torch.cat()은 주어진 차원을 기준으로 주어진 텐서들을 붙이지만, torch.stack()은 새로운 차원으로 주어진 텐서들을 붙인다. 참고

torch.expand(size), torch.repeat(size) 의 차이

  • 둘 다 특정 텐서의 sizes 차원의 데이터를 반복하지만, expand()는 개수가 1인 차원에만 적용 가능하다.

tensor.numpy(), tensor.values 의 차이

  • tensor.numpy(): PyTorch Tensor → NumPy 배열로 변환함. 텐서가 CPU에 있어야 함 (GPU 텐서일 경우 .cpu().numpy()로 변환)
  • tensor.values: 주로 Pandas DataFrame, Series에서 사용.
profile
공부해서 남주자

0개의 댓글