Moonss
Moon's
Moonss
전체 방문자
오늘
어제
  • 분류 전체보기 (24)
    • 환경 설정 (2)
    • git 사용법 (2)
    • Pandas (1)
    • 알고리즘 (7)
    • Pytorch (4)
    • GCP 환경 설정 (1)
    • cs231n (0)
    • Error (1)
    • 데이터 분석 (1)
    • 작성 전 글 저장 (0)

블로그 메뉴

  • ABOUT
  • POST
  • GUEST BOOK

공지사항

인기 글

태그

  • user.name
  • Linux OS
  • 알고리즘
  • GPU
  • error
  • git
  • git init
  • git config --unset
  • Linux
  • git config
  • Python
  • Blender
  • gcp
  • 3d
  • git config --global
  • 환경설정
  • IP
  • ifconfig
  • git config global --unset
  • BIG-O
  • user.email
  • github
  • 가상환경

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Moonss

Moon's

PyTorch - 1) 텐서(Tensor)
Pytorch

PyTorch - 1) 텐서(Tensor)

2021. 12. 29. 01:43

- 수정중

Tensor 란? 

파이토치에서 사용하는 데이터표현을 위한 기본 구조

텐서는 데이터를 담기위한 컨테이너로서 일반적으로 수치형 데이터를 저장 

넘파이와, ndarray와 유사 

Tensor 차원

이수안컴퓨터연구소 - 텐서의 모양

torch Data Type 

이수안컴퓨터연구소 - 데이터타입

 


 

Tensor 생성 

Tensor shape 지정 생성 하는 함수 

# 2x2 크기의 2D tensor 

torch.empty(2,2) # 비어있는 원소 
torch.zeros(2,2)
torch.ones(2,2) # 1인 원소
torch.rand(2,2) # 0~1사이의 원소 
torch.randn(2,2) #평균0이고 표준편차 1의 난수

# 추가 : 데이터 타입 입력 
torch.ones(2,2,dtype = torch.float)
torch.zeros(2,2,dtype = torch.double) #  tensor([[0., 0.],[0., 0.]], dtype=torch.float64)

# 추가 : 저장 공간 (gpu) 설정
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 
# torch.device 넣어도 된다.

x = torch.ones(4,device=device)
print(x) # tensor([1., 1., 1., 1.], device='cuda:0')

z = torch.zeros(4,device=device,dtype = torch.double) 
print(z) # tensor([0., 0., 0., 0.], device='cuda:0', dtype=torch.float64)

 

그 외 Tensor 생성  

# torch.randint(low=0,high,size) # low~high 사이의 랜덤값으로 채워진 size크기의 tensor 
x = torch.randint(3, size = (4,))
print(x) # tensor([0, 2, 1, 1])

# torch.arange(start = 0,end,step =1) # 파이썬 range()랑 역활 같음 
x = torch.arange(3)
print(x) # tensor([0, 1, 2])

 


 

Tensor 변경 

 Tensor 저장공간 및 타입 변경

# gpu, dtype 따로 변경 
x = torch.ones(2,dtype = torch.int)
print(x) # tensor([1, 1], dtype=torch.int32)

x = x.to(torch.double)
print(x) # tensor([1., 1.], dtype=torch.float64)

x = x.to(device) # cpu->gpu
print(x) # tensor([1., 1.], device='cuda:0', dtype=torch.float64)

# gpu, dtype 한번에 변경
y = torch.zeros(3)
print(y) # tensor([0., 0., 0.])

y = y.to(device,torch.double)
print(y) # tensor([0., 0., 0.], device='cuda:0', dtype=torch.float64)

기존 tensor shape 받고 요소 변경

torch.rand_like()
torch.randn_like()

torch.ones_like()

numpy, tensor 변환 

# data에서 tensor 자료형으로 바꾸는 방법 
data = [[1, 2],[3, 4]]
t_data = torch.tensor(data) # list -> tensor
n_data = np.array(data) # list->numpy array 

n = t_data.numpy() # tensor -> numpy 
t = torch.from_numpy(n_data) # numpy -> tensor

# numpy, tensor(cpu 저장된) 메모리 공간을 공유한다. 
n +=1 # numpy 값 변환
print(n) # [[2 3] [4 5]]
print(t_data) # tensor([[2, 3], [4, 5]])

t.add_(3) # tensor 값 변환
print(t) # tensor([[4, 5],[6, 7]])
print(n_data) # [[4 5] [6 7]]

# gpu 저장 시 메모리 공유 X
t = t.to(device) # 저장 공간 변경 (gpu)
t.add_(1) # tensor 값 변환 +1 
print(t) # tensor([[5, 6],[7, 8]], device='cuda:0')
print(n_data) # [[4 5]  [6 7]]

 


 

텐서의 속성값들 보기

tensor = torch.rand(3,4)
# 모양(size or shape) 확인 
tensor.shape
# 타입 확인 
tensor.dtype
# device 확인 
tensor.device 

 

 

Reference 

이수안컴퓨터연구소 - 파이토치 한번에 끝내기 : https://youtu.be/k60oT_8lyFw

Pytorch tutorial : https://tutorials.pytorch.kr/beginner/basics/tensorqs_tutorial.html

저작자표시

'Pytorch' 카테고리의 다른 글

torchvision.transforms 함수  (0) 2022.11.19
PyTorch - 2) 텐서(Tensor) 연산  (0) 2022.09.28
PyTorch 시작하기  (0) 2021.12.28
    'Pytorch' 카테고리의 다른 글
    • torchvision.transforms 함수
    • PyTorch - 2) 텐서(Tensor) 연산
    • PyTorch 시작하기
    Moonss
    Moonss

    티스토리툴바