상세 컨텐츠

본문 제목

pytorch 기본 개념 , tensor , 차원

Coding/딥러닝 & opencv

by 세미531 2023. 1. 31. 17:05

본문

728x90
#텐서 생성
import torch
print(torch.tensor([[1,2],[3,4]])) #2차원형태 텐서
print(torch.tensor([[1,2],[3,4]], device="cuda:0")) # gpu에 텐서 생성
print(torch.tensor([[1,2],[3,4]], dtype=torch.float64)) #dtype 을 이용하여 텐서 생성
tensor([[1, 2],
        [3, 4]])
tensor([[1, 2],
        [3, 4]], device='cuda:0')
tensor([[1., 2.],
        [3., 4.]], dtype=torch.float64)

----

#텐서를 ndarray 로 변환
temp = torch.tensor([[1,2],[3,4]])
print(temp.numpy())
[[1 2]
 [3 4]]

----

#gpu 상의 텐서를 cpu 의 텐서로 변환한 후 ndarray 로 변환
temp = torch.tensor([[1,2],[3,4]],device="cuda:0")
print(temp.to("cpu").numpy())
[[1 2]
 [3 4]]

----

----

#tensor 의 인덱스 조작
# torch.FloatTensor : 32비트 부동 소수점
# torch.DoubleTensor : 64비트의 부동 소수점
# torch.LongTensor : 64비트의 부호가 있는 정수

temp = torch.FloatTensor([1,2,3,4,5,6,7]) #파이토치로 1차원벡터 생성
print(temp)
print(temp[0],temp[1],temp[-1])
print("---------")
print(temp[2:5],temp[4:-1])
tensor([1., 2., 3., 4., 5., 6., 7.])
tensor(1.) tensor(2.) tensor(7.)
---------
tensor([3., 4., 5.]) tensor([5., 6.])

----

#텐서의 차원 조작
# view 를 이용하는 것이 대표적 : 넘파이의 reshape 과 유사
# 텐서를 결함하는 cat, stack : 다른 길이의 텐서를 하나로 병합할때
# 차원을 교환하는 t, transpose 도 사용 : 행렬의 전치 외에도 차원의 순서를 변경할 때

temp = torch.tensor([[1,2],[3,4]]) # 2*2 행렬 생성

print(temp.shape)
print('---------------')
print(temp.view(4,1)) # 2*2 행렬을 4*1 로 변형
print('---------------')
print(temp.view(-1)) # 1차원 벡터로 변형
print('---------------')
print(temp.view(1,-1)) # -1 은 1*자동으로 라는 의미. 반대도 마찬가지이다. 여기서는 1*4가 된다.
torch.Size([2, 2])
---------------
tensor([[1],
        [2],
        [3],
        [4]])
---------------
tensor([1, 2, 3, 4])
---------------
tensor([[1, 2, 3, 4]])

pytorch

728x90

관련글 더보기

댓글 영역