【Pytorch】 Pytorch 튜토리얼 1 - pytorch로 딥러닝하기

(Pytorch) Pytorch 튜토리얼 1 - pytorch로 딥러닝하기

# torch 사용법 백과사전 : https://pytorch.org/docs/stable/
import torch
torch.__version__

‘1.4.0’

# print function에 대하여, 2.x 3.x 버전 둘다 사용가능하게 해줌. print x,y; print(x,y)
from __future__ import print_function 
# 메모리 할당만 해주고, 값은 정의 하지 않는다. 쓰레기 값 저장되어 있을 것.
x = torch.empty(5,3)
print(x)
# 배열을 생성하고 싶을 때. 아래의 값들은 모두 tensor([[],[]])로 저장되어 있다. 
y = torch.rand(2,3)
z = torch.zeros(2,3)
k = torch.ones(2,3,dtype=torch.double)          # torch.double == torch.float64
j = torch.rand_like(k,dtype=torch.float)        # k와 동일한(like) 크기를 가지는 rand tensor를 만든다
# object.size() == object.shape. torch.size는 사실 튜플이다. 모든 곳에서 튜플처럼 이용할 수 있다. 
print(j.shape, ' ==? ',j.size())
n = torch.rand(j.shape) 
m = torch.rand(j.size())
print(type(j.size()))
# list를 가지고 있다면 직접 tensor생성
i = torch.tensor([1,2,3,4])
tensor([[9.2755e-39, 1.0561e-38, 1.0561e-38],
        [4.4082e-39, 4.4082e-39, 5.9694e-39],
        [8.9082e-39, 1.0194e-38, 9.1837e-39],
        [4.6837e-39, 9.2755e-39, 1.0837e-38],
        [8.4490e-39, 1.0194e-38, 9.0919e-39]])
torch.Size([2, 3])  ==?  torch.Size([2, 3])
<class 'torch.Size'>
# operator 같은 size 텐서에서 + - 연산 가능
q = y+z 
q = torch.add(y,z)
q = torch.empty(9,8)    #; print(q)
torch.add(y,z,out=q)    #; print(q)  # torch.add 함수는 자동으로 print해준다.
y.add(z)                # ; y += z 
tensor([[0.7769, 0.6797, 0.9659],
        [0.7994, 0.2708, 0.1580]])
# 바꿔치기 연산자. 어떤 변수를 통체로 바꿔버리고 싶다면 _ 를 사용하는 메소드를 사용하라.
k.copy_(z)              # 아무리 그래도 y와 z의 shape는 같아야 한다.
y.t_()
# 슬라이싱도 사용할 수 있다. numpy와 같은 방식이다.
print( y[:,1].type(torch.int) )
print( y[:,1].to(torch.int) )
tensor([0, 0, 0], dtype=torch.int32)
tensor([0, 0, 0], dtype=torch.int32)
# np.reshape == torch.view
y = torch.randint(10,(2,3))  # 10을 최대 정수로. 2*3행렬 탄생
print(y)
y.resize(6)                 # view도 가능하고 reshape도 가능하고
print(y.resize(6))
y.view(3,2)
print(y.view(3,2))
y.view(-1,6)                # -1을 넣으면 알아서, 적당한 값으로 변환된다.
print(y.view(-1,6))
# 1*1 텐서의 값을 뽑아주는 item메소드
interger = torch.tensor([2]).item()  
print(interger)
print(type(interger))
tensor([[5, 0, 1],
        [3, 3, 8]])
tensor([5, 0, 1, 3, 3, 8])
tensor([[5, 0],
        [1, 3],
        [3, 8]])
tensor([[5, 0, 1, 3, 3, 8]])
2
<class 'int'>
# tensor와 numpy의 관계는 copy of referecne 관계이다.
a = torch.tensor([1,1,1,2,2])
b = a.numpy()
print(b)
a.add_(1)
print(b,"\n -----")

# numpy를 tensor로 변환
import numpy as np
a = np.ones([2,3])
b = torch.from_numpy(a)
np.add(a,1,out=a)
print(a,"\n",b)
[1 1 1 2 2]
[2 2 2 3 3] 
 -----
[[2. 2. 2.]
 [2. 2. 2.]] 
 tensor([[2., 2., 2.],
        [2., 2., 2.]], dtype=torch.float64)
# cuda 사용하기. to 메소드를 사용하면 된다.
if torch.cuda.is_available():
    device = torch.device("cuda")           #cuda사용할 수 있는 gpu id를 device라는 것
    y = torch.ones_like(x,device=device)    #변수 선언을 할 때 처음부터 device를 지정해도 되고, 
    x = x.to(device)                        #나중에 to메소드를 사용해서 device를 지정해도 된다. 
    z.to("cpu", torch.double)



© All rights reserved By Junha Song.