본문 바로가기
DL|ML

Keras backends?

by 이든Eden 2019. 9. 9.

Keras backends?

💡
from keras import backend as K 를 import 해서 K가 가지고 있는 함수들을 가끔 쓰곤 했다. 하지만 굳이 Keras가 아닌 tensorflow로 바로 쓸 수 있기 때문에 깊게 생각해본 적이 없었는데, 어제 PyTorch 코드를 보다가 이 코드를 Keras로 바꾼다면 어떻게 해야할까? 라고 생각하다 내가 Keras Backend에 대해 무지하다는 것을 깨달았다.

📎Keras 공식 문서인 이곳을 참고하면서 공부했다.

 

"backend" 가 뭐야?

➡️
Keras is a model-level library, providing high-level building blocks for developing deep learning models. It does not handle low-level operations such as tensor products, convolutions and so on itself.

Keras는 model-level의 라이브러리이기 때문에 딥러닝 모델을 만들 때 블록(레이어)을 제공한다. 그래서 low-level과 관련된 연산을 핸들링하지 못한다는 이야기이다.

그 대신 Keras는 backend로서 TensorFlow, Theano, CNTK를 사용할 수 있다.

 


Keras backend 모듈 쓰기

Keras는 low-level을 핸들링 하지 못한다고 했지만, Keras backend를 이용하면 TensorFlow처럼 Keras에서도 variable을 만들거나 연산을 할 수 있다 🤩

짧은 코드로 TensorFlow와 비교해보자.

'''
Shape이 (2,4,5)인 placeholder 만들기!
'''
>>> import tensorflow as tf # import tensorflow
>>> tf.placeholder(tf.float32, shape=(2, 4, 5))
<tf.Tensor 'Placeholder:0' shape=(2, 4, 5) dtype=float32>
>>> from keras import backend as K # import keras backend module 
Using TensorFlow backend.
>>> K.placeholder(shape=(2, 4, 5))
<tf.Tensor 'Placeholder_1:0' shape=(2, 4, 5) dtype=float32>

짜잔 결과는 둘 다 똑같이 data type이 float32이고, shape이 (2, 4, 5)인 placeholder가 만들어졌다. place holder외에도 TensorFlow에서 가능한 dot 연산 등등이 keras backend 모듈을 이용해서 가능하다.

하지만 아직까지도 언제 주로 Keras backend 모듈을 tensorflow 대신 쓰는지는 잘 모르겠다 🤔

 


내가 궁금했던 Keras backend 모듈

어젯밤에 PyTorch로 만든 cycleGAN 코드 보면서 이걸 Keras로 바꾸게 되면 어떻게 해야될까? 생각해보다가 TensorFlow와 Keras의 비슷한 함수가 정말 같은 역할을 하는지 궁금했다.

 

아래가 그 시발점이었던 코드이다.

def tensor2im(input_image, imtype=np.uint8):
    """"Converts a Tensor array into a numpy image array.

    Parameters:
        input_image (tensor) --  the input image tensor array
        imtype (type)        --  the desired type of the converted numpy array
    """
    if not isinstance(input_image, np.ndarray):
        if isinstance(input_image, torch.Tensor):  # get the data from a variable
            image_tensor = input_image.data
        else:
            return input_image
        image_numpy = image_tensor[0].cpu().float().numpy()  # convert it into a numpy array
        if image_numpy.shape[0] == 1:  # grayscale to RGB
            image_numpy = np.tile(image_numpy, (3, 1, 1))
        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0  # post-processing: tranpose and scaling
    else:  # if it is a numpy array, do nothing
        image_numpy = input_image
    return image_numpy.astype(imtype)

내가 궁금했던 것은 if isinstance(input_image, torch.Tensor) 부분을 바꾼다면

  • tf.is_tensor(x)

is_tensor()들의 역할은

  • keras.backend.is_tensor(x)
  • keras.backend.is_keras_tensor(x)

중에 어떤걸 써야하는지에 대한 문제였다. 그래서 지금 테스트해보려고 한다.

>>> x_tf = tf.placeholder(tf.float32, shape=(2, 4, 5))
>>> x_keras = K.placeholder(shape=(2, 4, 5))
>>>
>>> tf.is_tensor(x_tf)
True
>>> tf.is_tensor(x_keras)
True
>>> K.is_tensor(x_tf)
True
>>> K.is_tensor(x_keras)
True
>>> K.is_keras_tensor(x_tf)
False
>>> K.is_keras_tensor(x_keras)
False

위의 테스트를 통해서 tf.is_tensor() K.is_tensor() 는 같다는 걸 알았다. 그런데 K.is_keras_tensor()는 그렇지 않다. 얘는 뭘까.. 공식문서를 찾아보니 조금 다른 애였다. K.is_keras_tensor()에 대해서 조금 더 알아보자.

 


K.is_keras_tensor()

➡️
is_tensor(x)들의 역할은 x가 tensor이냐 아니냐에 대한 Boolean is_keras_tensor(x)의 역할은 xKeras tensor이냐 아니냐에 대한 Boolean return

그러면 "Keras Tensor"는 뭘까?

: "Keras Tensor"란 Keras Layer에 의해 return된 tensor! 여기서 말하는 Keras Layer는 딥러닝 모델을 만들 때 쓰는 Layer class 또는 Input class를 말한다.

 

공식문서에 있는 예제 코드로 조금 더 직관적인 이해를 해보자. 역시 이해해는 코드가 최고 👍

>>> from keras import backend as K
>>> from keras.layers import Input, Dense
>>> k_var = tf.placeholder('float32', shape=(1,1)) # make Tensor
>>> K.is_tensor(k_var) # k_var is a tensor. Not a Keras tenso
True
>>> K.is_keras_tensor(k_var)
False
>>> keras_input = Input([10]) # make Keras Tensor from Input Layer
>>> K.is_keras_tensor(keras_input) 
True
>>> keras_layer_output = Dense(10)(keras_input) # make Keras Tensor from Dense Layer
>>> K.is_keras_tensor(keras_layer_output)
True

Keras Layer인 Input, Dense class로 만들어진 Keras Tensor는 is_keras_tensor()의 결과값만이 True이다.

간단하게 정리하면, 내가 알던 일반적인 Tensor가 있었고, 그와 조금 다른 텐서인 Keras Tensor가 있기 때문에 is_tensor(), is_keras_tensor()가 역할이 달랐던 것이다 🎉🎉 이해 성공!