본문 바로가기
Experience/- KT AIVLE School

KT AIVLE School 5주차 정리 - Keras (Functional)

by Yoojacha 2023. 3. 3.

기본 Functional API 방식

keras.backend.clear_session() # 모델 저장된 메모리 초기화

"""
Sequential과의 차이점
- 변수에 각 레이어의 결과를 담는다.
- 모델 변수를 처음과 끝 레이어 변수를 넣어서 따로 선언한다.
- Concatenate 등과 같이 히든레이어의 설정이 가능
"""
il = keras.layers.Input(shape=(1,))
hi = keras.layers.Dense(512, activation='swish', name='hidden1')(il)
hi = keras.layers.Dense(256, activation='swish', name='hidden2')(hi)
hi = keras.layers.Dense(128, activation='swish', name='hidden3')(hi)
ol = keras.layers.Dense(1, name='output')(hi)

model = keras.models.Model(il, ol) # 시작과 끝 레이어 지정하여 모델 선언

# Sequential 방식과 같음
model.compile(
               loss='로스함수', 
               metrics=['측정방식'],
               optimizer='옵티마이저'
             )

model.summary() # 요약

Concatenate() Layer

# 1. 세션 클리어
clear_session()

il1 = Input( shape=(2,) )
hl1 = Dense(2, activation='relu')(il1)

il2 = Input( shape=(2,) )
hl2 = Dense(2, activation='relu')(il2)

# connected layer (2개 이상의 레이어를 리스트로 인자를 넣어줌)
cl = Concatenate()([hl1, hl2]) # 괄호 두 번 주의
ol = Dense(3, activation='softmax')(cl)

model = Model([il1, il2], ol) # 인풋 레이어도 리스트로 인자를 넣기

model.compile(
               loss=categorical_crossentropy, 
               metrics=['accuracy'],
               optimizer=Adam()
             )

model.summary()

Add() Layer

keras.backend.clear_session()

il_se = keras.layers.Input(shape=(2,))
hl_se = keras.layers.Dense(4, activation='relu', name='hl_sepal')(il_se)

il_pe = keras.layers.Input(shape=(2,))
hl_pe = keras.layers.Dense(4, activation='relu', name='hl_petal')(il_pe)

add_l = keras.layers.Add()([hl_se, hl_pe])
ol = keras.layers.Dense(3, activation='softmax')(add_l)

model = keras.models.Model([il_se, il_pe], ol)

model.compile(loss='categorical_crossentropy', metrics=['accuracy'],
              optimizer='adam')

model.summary()

 

댓글