더북(TheBook)

케라스의 Layer 클래스

간단한 API는 모든 것이 중심에 모인 하나의 추상화를 가져야 합니다. 케라스에서는 Layer 클래스가 그렇습니다. 케라스의 모든 것은 Layer 또는 Layer와 밀접하게 상호 작용하는 무엇입니다.

Layer는 상태(가중치)와 연산(정방향 패스)을 캡슐화한 객체입니다. 가중치는 (생성자인 __init__() 메서드에서 만들 수도 있지만) 일반적으로 build() 메서드에서 정의하고 연산은 call() 메서드에서 정의합니다.

이전 장에서 2개의 Wb를 가지고 output = activation(dot(input, W) + b) 계산을 수행하는 NaiveDense 클래스를 정의했습니다. 다음은 이와 동일한 케라스 층입니다.

코드 3-22 Layer의 서브클래스(subclass)로 구현한 Dense 층

from tensorflow import keras 

class SimpleDense(keras.layers.Layer): 
    def __init__(self, units, activation=None):
        super().__init__()
        self.units = units
        self.activation = activation  

    def build(self, input_shape): 
        input_dim = input_shape[-1]
        self.W = self.add_weight(shape=(input_dim, self.units), 
                                 initializer="random_normal")
        self.b = self.add_weight(shape=(self.units,),
                                 initializer="zeros") 

    def call(self, inputs): 
        y = tf.matmul(inputs, self.W) + self.b
        if self.activation is not None:
            y = self.activation(y)
       return y

모든 케라스 층은 Layer 클래스를 상속합니다.

build() 메서드에서 가중치를 생성합니다.

add_weight()는 가중치를 간편하게 만들 수 있는 메서드입니다. self.W = tf.Variable(tf.random.uniform(w_shape))와 같이 독립적으로 변수를 생성하고 층의 속성으로 할당할 수도 있습니다.

call() 메서드에서 정방향 패스 계산을 정의합니다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.