2. 텐서의 생성

jaeyun·2021년 1월 22일
0

파이토치 기초

목록 보기
2/8
post-thumbnail

오늘은 기본 데이터 구조인 텐서 사용법에 대해서 알아보겠습니다.

텐서란?

-다차원 배열을 처리하기 위한 데이터 구조입니다.

-Numpy, ndarray와 거의 같은 API를 지니고 있으며, GPU를 사용한 계싼도 지원합니다.

-텐서는 각 데이터형별로 정의되어 있습니다.

텐서의 정의하기

텐서를 정의하는 방법은 다양합니다.

(1) 텐서를 직접 정의하는 방법

x1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]]) 
x2 = torch.rand(3,3)
x3 = torch.FloatTensor([[1,2,3],[4,5,6],[7,8,9]])
x4 = torch.LongTensor([[1,2,3],[4,5,6],[7,8,9]])
x5 = torch.ByteTensor([True,True,False])

(2) list, numpy배열을 이용하여 텐서 정의

# turn list into tensor
list_example = [[1,2,3],[4,5,6]]
list_to_tensor = torch.Tensor(list_example)

# turn numpy array into tensor
numpy_example = np.array([[1,2,3],[4,5,6]])
numpy_to_tensor = torch.Tensor(numpy_example)
이번에는 반대로 텐서를 list, numpy로 변환해 줄 수 있습니다.

# turn tensor into list
tensor_to_list = list_to_tensor.tolist()

# turn tensor into numpy array
tensor_to_numpy = numpy_to_tensor.numpy()

(3) GPU를 사용하는 텐서를 정의

GPU를 사용할 수 있게 텐서를 정의하려면, 아래와 같이 끝에 .cuda()를 붙여주시면 됩니다.

## tensor generation using GPU
tensor_example = torch.rand(3,3).cuda()

profile
벨로그에서는 인공지능 관련 포스팅만 합니다! 더 많은 정보는 소개를 참고해주세요!

0개의 댓글