본문 바로가기

dev_AI_framework

클래스 정보, get_config, from_config

get_config 는 객체나 클래스의 구성 configuration 을 반환하는 메서드로 사용, 

 

객체의 상태나 설정을 딕셔너리 형태로 반환한다. 나중에 객체를 동일한 상태로 복원하거나 저장, 직렬화할 때 사용된다 .

class MyLayer:
    def __init__(self, units, activation):
        self.units = units
        self.activation = activation

    def get_config(self):
        return {
            'units': self.units,
            'activation': self.activation
        }

    @classmethod
    def from_config(cls, config):
        return cls(**config)

# 객체 생성
layer = MyLayer(units=64, activation='relu')

# 구성 정보 가져오기
config = layer.get_config()
print(config)

# 구성 정보를 사용하여 객체 복원
new_layer = MyLayer.from_config(config)
print(new_layer.units, new_layer.activation)

 

config 를 통해 객체의 정보를 저장할 수 있음, 저장되는 객체의 정보가 특정 시점에 따라 달라질 수 있을 것 ( call 연산 수행 전후, build 전후 등등 )

 

from_config 에서 __init__ 의 호출로 해당 객체를 config 정보를 통한 복원이 가능하다 

 

Flatten Class 의 get, from_config 의 작성

    def __init__(self, input_shape, **kwargs):
        # 인스턴스 생성 시 어떤 값이 추가되어야 할 지에 대한 고민
        super().__init__(**kwargs)
        self.input_shape = input_shape

    # 객체 정보를 저장하는 get_config
    # 향후 from_config 를 통해 해당 객체를 복원할 수 있다. 
    def get_config(self):
        base_config = super().get_config()
        config = {
            "input_shape": self.input_shape
        }
        return {**base_config, **config}

    # 저장된 config 파일로 객체 생성
    def from_config(cls, config):
        return(cls **config)

get_config 가 실행되는 시점에서 추가되는 객체 속성값이 있을 것이고, 이에 따른 init 파라미터를 추가하거나 등의 가능

 

Dense 클래스의 get_config 작성

    def get_config(self):
        base_config = super().get_config()
        config = ({
            'units': self.units,
            'activation': self.activation,
        })
        return {**base_config, **config}