tensorflow
-
[tensorflow 2.0] optimizer learning rate schedule데이터분석 2019. 12. 9. 23:15
섬세한 모형 튜닝을 위해서는 learning rate를 조금씩 줄여주는 작업이 필요하다. 특정 iteration마다 optimizer instance를 새로 생성해줘도 되지만, tensorflow에서는 optimizer의 learning rate scheduling이 가능하다. 가장 많이 쓰이는 ExponentialDecay는 계속 같은 비율로 learning rate를 감소시켜준다. 사용 예시는 아래와 같다. initial_learning_rate = 0.1 lr_schedule = keras.optimizers.schedules.ExponentialDecay( initial_learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True) opt..
-
[tensorflow 2.0] tf.pad데이터분석 2019. 12. 2. 01:12
이미지 전처리 중 shape 통일을 위해서 원본 이미지에 zero-padding을 해야할 경우가 있다. 그 때 손쉽게 패팅하는 방법이 tf.pad이다. tf.pad( tensor, paddings, mode='CONSTANT', constant_values=0, name=None ) 사용 방법은 padding만 신경쓰면 어렵지 않다. padding은 shape이 D x 2인 텐서이며, [D, 0]은 D차원(rank) 앞의 패딩 [D, 1]은 D차원 뒤의 패딩을 의미한다. 예를 들어, input tensor의 Shape이 (Batch_size, height, width, channel) 라면, 다음과 같이 height와 width에만 padding을 추가할 수 있다. padding = [[0, 0], [6..
-
[tensorflow 2.0] tf.data.Dataset enumerate데이터분석 2019. 12. 1. 17:55
tf.data.Dataset API를 보면 enumerate() 함수가 있다. 배치마다의 값 확인을 위해서 아래 함수를 쓰면 되겠구나! 했는데.. # NOTE: The following examples use `{ ... }` to represent the # contents of a dataset. a = { 1, 2, 3 } b = { (7, 8), (9, 10) } # The nested structure of the `datasets` argument determines the # structure of elements in the resulting dataset. a.enumerate(start=5)) == { (5, 1), (6, 2), (7, 3) } b.enumerate() == { (0,..
-
[Tensorflow 2.0] custom gradient 함수로 reverse gradient 구현하기데이터분석 2019. 11. 7. 20:15
Adversarial Network를 학습하기 위해서는 gradient를 반전해야 할 때가 있다. 그런 경우 Tensorflow 2.x에서는 custom gradient 함수를 정의하여 구현할 수 있다. 일단 공식 가이드의 custom gradient 예시를 보자. # custom gradient sample @tf.custom_gradient def log1pexp(x): e = tf.exp(x) def grad(dy): return dy * (1 - 1 / (1 + e)) return tf.math.log(1 + e), grad 먼저 @tf.custom_gradient 데코레이터를 사용한다. 그리고 정의하는 함수 내부에서 input 처리 및 gradient를 return하는 함수를 정의해서 다시 반환..
-
[tensorflow 2.0] tf.slice데이터분석 2019. 11. 1. 22:50
tf.slice( input_, begin, size, name=None ) tf.slice는 python list slice의 함수 형태로 이해하면 된다. input_: 원본 input tensor begin: 시작 위치 size: 잘라낼 size (shape) # 예제 tensor t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]]) # 원본 t에서 시작위치 [1, 0, 0]은 [3, 3, 3] 리스트의 맨 앞 [3] 이다. # 시작 위치에서 [1, 1, 3] shape으로 내용물을 꺼내오면, # 총 1*1*3 개의 원소가 차례대로 선택되고 # 그 결과는 [[[3, 3, 3]]] 이 된다. tf..
-
배열 3차원 이상 곱셈데이터분석 2019. 10. 16. 20:55
데이터 프레임워크를 사용하다보면 곱셈시 배열 차원(shape)이 매번 헷깔린다. 그래서 정리를 해보았다. 01. 2차원 곱셈 일단 기본 numpy 행렬곱으로 shape 특성을 이해해본다. 아래 예시에서 확인할 수 있듯이, 2차원의 행렬에서 shape은 (행, 열)을 의미한다. 이 상태에서는 크게 어려울 것이 없다. import numpy as np a = np.array([[1, 0], [0, 1], [1, 1]]) print(a.shape) # (3, 2) b = np.array([[4, 1], [2, 2]]) print(b.shape) # (2, 2) np.matmul(a, b) #array([[4, 1], # [2, 2], # [6, 3]]) 02. 3차원 이상 곱셈 여기서부터 매번 헷깔리기 시작한..