Introduction to Keras for engineers

Introduction to Keras for engineers

Keras를 처음 접하는 엔지니어를 위해, Keras 3의 핵심 워크플로를 한 노트북으로 정리한 자료예요. Keras 3는 TensorFlow, JAX, PyTorch를 서로 바꿔 가며 쓸 수 있는 딥러닝 프레임워크예요. 이번 가이드를 따라 MNIST 분류기 하나를 만들어 보면, 모델을 만들고 학습시키는 흐름이 자연스럽게 손에 익힐 거예요.

출처: Introduction to Keras for engineers

준비

여기서는 JAX 백엔드를 쓸 건데, 아래 문자열을 "tensorflow""torch"로 바꾸고 "Restart runtime"을 눌러도 노트북 전체가 그대로 동작해요. 이 가이드는 전부 백엔드에 무관(backend-agnostic)하게 작성되어 있어요.

import numpy as np
import os

os.environ["KERAS_BACKEND"] = "jax"

# Note that Keras should only be imported after the backend
# has been configured. The backend cannot be changed once the
# package is imported.
import keras

첫 예시: MNIST convnet

머신러닝의 Hello World라 할 수 있는, MNIST 숫자를 분류하는 convnet 학습부터 시작해 볼게요.

먼저 데이터를 불러와요.

# Load the data and split it between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

# Scale images to the [0, 1] range
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Make sure images have shape (28, 28, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print("x_train shape:", x_train.shape)
print("y_train shape:", y_train.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")
x_train shape: (60000, 28, 28, 1)
y_train shape: (60000,)
60000 train samples
10000 test samples

이제 모델을 만들 차례예요. Keras가 제공하는 모델 구성 방식은 여러 가지예요.

  • Sequential API (아래에서 사용)
  • Functional API (가장 흔함)
  • 모델 서브클래싱으로 직접 작성 (고급 유스케이스)
# Model parameters
num_classes = 10
input_shape = (28, 28, 1)

model = keras.Sequential(
    [
        keras.layers.Input(shape=input_shape),
        keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        keras.layers.MaxPooling2D(pool_size=(2, 2)),
        keras.layers.Conv2D(128, kernel_size=(3, 3), activation="relu"),
        keras.layers.Conv2D(128, kernel_size=(3, 3), activation="relu"),
        keras.layers.GlobalAveragePooling2D(),
        keras.layers.Dropout(0.5),
        keras.layers.Dense(num_classes, activation="softmax"),
    ]
)

모델 요약은 이렇게 확인해요.

model.summary()
Model: "sequential"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ conv2d (Conv2D)                 │ (None, 26, 26, 64)     │        640    │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d_1 (Conv2D)               │ (None, 24, 24, 64)     │     36,928    │
...

이어서 모델을 컴파일하고 학습·평가하는 흐름이 이어져요. model.compile()로 옵티마이저·손실·메트릭을 정하고, model.fit()으로 학습하고, model.evaluate()로 평가해요. Keras 3는 데이터 입력으로 NumPy 배열뿐 아니라 keras.utils.PyDataset 서브클래스, tf.data.Dataset, PyTorch DataLoader를 모두 받아요. 백엔드가 뭐든 데이터 파이프라인은 그대로 재사용할 수 있죠.

더 알아보기