The Sequential model
The Sequential model
가장 간단한 모델 구성 방식부터 시작해 볼게요. Sequential 모델은 각 레이어가 정확히 하나의 입력 텐서와 하나의 출력 텐서를 갖는, 레이어가 평평하게 쌓인 구조에 적합해요. 딥러닝 모델의 첫 시작이라면 Sequential 모델로 감을 잡는 게 자연스러운 흐름이에요.
Sequential 모델을 써야 할 때
Sequential 모델은 각 레이어가 입력 텐서 하나와 출력 텐서 하나만 갖는 단순한 레이어 스택에 적합해요. 개념적으로 다음 Sequential 모델은:
# Define Sequential model with 3 layers
model = keras.Sequential(
[
layers.Dense(2, activation="relu", name="layer1"),
layers.Dense(3, activation="relu", name="layer2"),
layers.Dense(4, name="layer3"),
]
)
# Call model on a test input
x = ops.ones((3, 3))
y = model(x)
이런 함수와 동일해요:
# Create 3 layers
layer1 = layers.Dense(2, activation="relu", name="layer1")
layer2 = layers.Dense(3, activation="relu", name="layer2")
layer3 = layers.Dense(4, name="layer3")
# Call layers on a test input
x = ops.ones((3, 3))
y = layer3(layer2(layer1(x)))
Sequential 모델이 적합하지 않은 경우도 있어요.
- 모델에 입력이나 출력이 여러 개일 때
- 어떤 레이어가 입력이나 출력을 여러 개 가질 때
- 레이어 공유(shared layer)가 필요할 때
- 비선형 토폴로지(잔차 연결, 다중 분기 모델 등)를 원할 때
Sequential 모델 만들기
Sequential 생성자에 레이어 리스트를 넘겨 만들 수 있어요.
model = keras.Sequential(
[
layers.Dense(2, activation="relu"),
layers.Dense(3, activation="relu"),
layers.Dense(4),
]
)
레이어는 layers 속성으로 접근할 수 있어요.
model.layers
[<Dense name=dense, built=False>,
<Dense name=dense_1, built=False>,
<Dense name=dense_2, built=False>]
add() 메서드로 점진적으로 레이어를 추가할 수도 있어요.
model = keras.Sequential()
model.add(layers.Dense(2, activation="relu"))
model.add(layers.Dense(3, activation="relu"))
model.add(layers.Dense(4))
pop() 메서드로 레이어를 제거할 수도 있어요. Sequential 모델은 레이어 리스트와 아주 비슷하게 동작하죠.
model.pop()
print(len(model.layers)) # 2
Sequential 생성자는 Keras의 다른 레이어·모델처럼 name 인자를 받아요. TensorBoard 그래프에 의미 있는 이름을 주석으로 다는 데 유용해요.
model = keras.Sequential(name="my_sequential")
model.add(layers.Dense(2, activation="relu", name="layer1"))
model.add(layers.Dense(3, activation="relu", name="layer2"))
model.add(layers.Dense(4, name="layer3"))
입력 shape를 미리 지정하기
일반적으로 Keras의 모든 레이어는 가중치를 만들려면 입력의 shape를 알아야 해요. 그래서 이렇게 레이어를 만들면 처음에는 가중치가 없어요:
layer = layers.Dense(3)
layer.weights # Empty
[]
가중치는 레이어에 데이터가 처음 들어올 때 생성돼요. Sequential 모델을 만들 때 keras.Input으로 입력 shape를 명시하면, 남은 레이어들의 shape을 미리 추론해서 모델 그래프가 더 빨리 완성돼요.
더 알아보기
- Introduction to Keras for engineers — Keras 3 워크플로
- The Functional API — 더 유연한 모델 정의
- Training & evaluation — 학습·평가