EZI 기술 블로그 JU

Keras 딥러닝 모델 작성 방법 세 가지 본문

Modeling

Keras 딥러닝 모델 작성 방법 세 가지

eziju 2023. 3. 20. 09:52

1. Sequential API

가장 기본적인 위에서 차례대로 쌓아나가는 형태로 복잡하고 유기적인 신경망을 설계하는 데는 한계가 있음

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# Optionally, the first layer can receive an `input_shape` argument:
model = Sequential()
model.add(Dense(8, input_shape=(16,)))
# Afterwards, we do automatic shape inference:
model.add(Dense(4))

2. Functional API

함수화 해서 모델을 구성하는 형태로 multimodal modeling 등 sequential api로는 표현하기 어려운 구조의 모델을 작성할 수 있음 

from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model

inputs = Input(shape=(10,))
hidden1 = Dense(64, activation='relu')(inputs)
hidden2 = Dense(64, activation='relu')(hidden1)
output = Dense(1, activation='sigmoid')(hidden2)

# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=outputs)

3. Sub-Classing API

subclassing api는 디버깅이 까다로우나 모델의 커스터마이징이 가장 자유로움 call()에서 loss tensor 작성 가능

import tensorflow as tf
from tf.keras.models import Model
from tf.keras.layers import Dense

class MyModel(Model):

  def __init__(self):
    super().__init__()
    self.dense1 = Dense(4, activation=tf.nn.relu)
    self.dense2 = Dense(5, activation=tf.nn.softmax)

  def call(self, inputs):
    x = self.dense1(inputs)
    return self.dense2(x)

model = MyModel()

 

 

https://www.tensorflow.org/guide/keras/custom_layers_and_models?hl=ko 

 

하위 클래스화를 통한 새로운 레이어 및 모델 만들기  |  TensorFlow Core

하위 클래스화를 통한 새로운 레이어 및 모델 만들기 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. !pip install -U tf-hub-nightlyimport tensorflow_hub as hubfrom tensorflow

www.tensorflow.org

 

 

반응형