Programmers 인공지능 데브코스 - Week 7 Day 3 - PyTorch 및 Tensorflow 실습

donchanee·2021년 1월 20일
0
post-thumbnail

PyTorch

Tensor는 NumPy의 ndarray와 유사합니다.
초기화되지 않은 5x3 행렬을 생성합니다 :

import torch

torch.__version__

x = torch.empty(5,3)
print(x)

무작위로 초기화된 행렬을 생성합니다:

x = torch.randn(5,3)  # normal distribution
print(x)
x = torch.rand(5,3) # 0~1
print(x)

dtype이 long이고 0과 1으로 채워진 행렬을 생성합니다:

x = torch.zeros(5,3, dtype=torch.long)
print(x)
x = torch.ones(5,3, dtype=torch.long)
print(x)

데이터로부터 직접 tensor를 생성할 때는:

x = torch.tensor([5.5 , 3])
print(x)

새로운 double타입의 x를 만들고, 이들 method들은 dtype을 생략시 원래의 속성을 따라갑니다.

x = x.new_ones(5,3,dtype=torch.double)
x = torch.randn_like(x, dtype=torch.float)

행렬의 크기를 구합니다:

x.size() or x.shape()

덧셈 문법:

x = torch.rand(5,3)
y = torch.rand(5,3)

print(x + y)
print(torch.add(x,y))

# 새로운 assign없이 기존의 tensor에 연산하는 방식
y.add_(x)

shape이나 차원 등 크기 변경:

x = torch.randn(4,4)    # 4 by 4
y = x.view(16)          # 1 by 16
z = y.view(-1,2)        # 8 by 2   -1은 자동으로 차원을 변경하라는 뜻

tensor에 하나의 값만 있다면 추출 가능:

x.item()

NumPy 변환(Bridge):

a = torch.ones(5)
b = a.numpy()
a.add_(1)

print(a, b)

# 따로 작업하고 싶을 시, a.clone() 으로 복제품 사용

CUDA Tensors:

x = torch.rand(4,4)
if torch.cuda.is_available():
	device = "cuda:0"
    y = torch.ones_like(x, device=device)
    print(y)
    
    x = x.to(device)
    z = x+y
    print(z)
    print(z.to("cpu", torch.double))
    
# gpu를 사용하는 법
# 또한 x = x.cuda()로도 사용 가능합니다.

Tensorflow

import tensorflow as tf

v = tf.Variable(tf.zeros([1,2,3]))

v = tf.Variable(0.0)
w = v + 1

# 값을 변수에 할당하는 방법
a = tf.Variable(0.0)
a.assign_add(1)
a.read_value()  # 1.0

# tf.Tensor 객체의 랭크는 그 차원의 수
# 랭크 0 == 스칼라, 랭크 1 == 벡터
s = tf.Variable([[7],[11]], tf.int16)
tf.rank(s)

my_image = tf.zeros([10, 299, 299, 3]) # 배치 높이 너비 색상

r = tf.rank(my_image)
r  # r == 4

squares = tf.Variable([[4,9],[16,25]], tf.int16)
row_vec = squares[1]
col_vec = squares[:, 1]

zeros = tf.zeros(squares.shape) # 객체 형태 얻기

# pytorch의 view와 유사
rank = tf.ones([3,4,5])
matrix = tf.reshape(rank, [6,10])  	  # 6 by 10
matrixB = tf.reshape(matrix, [3,-1])      # 3 by 20
matrixAlt = tf.reshape(matrixB, [4,3,-1]) # 4 by 3 by 5 tensor

i = tf.constant([1,2,3])
f = tf.cast(i, dtype=tf.float32)  # 자료형 변환

0개의 댓글