데이터 엔지니어 · AI 엔지니어를 위한 핵심 요약
TensorFlow는 Google에서 개발한 오픈소스 머신러닝 프레임워크로, 데이터 플로우 그래프를 통해 수치 계산을 수행합니다. 딥러닝 모델의 개발부터 배포까지 end-to-end 지원하며, CPU/GPU/TPU에서 효율적으로 동작합니다. 실무에서 대규모 데이터셋 처리와 프로덕션 배포에 최적화되어 있습니다.
TensorFlow의 3대 핵심 능력:
TensorFlow Serving, Lite, Extended를 통해 모델을 프로덕션에 쉽게 배포. Kubernetes, Docker와 통합 우수.
Distributed training 지원 (MirroredStrategy, MultiWorkerMirroredStrategy). TPU에서 초고속 학습 가능.
Keras 고수준 API부터 저수준 Symbolic/Imperative 실행까지. Eager Execution으로 디버깅 용이.
PyTorch나 JAX 같은 대안 대비 TensorFlow는 프로덕션 안정성과 생태계가 강점입니다. 특히 MLOps 파이프라인에서 TensorFlow Extended(TFX)가 표준화되어 있습니다.
| 기능 | TensorFlow | PyTorch | JAX |
|---|---|---|---|
| Production Readiness | ⭐⭐⭐⭐⭐ (TFX, Serving) | ⭐⭐⭐ (TorchServe) | ⭐⭐ (Flax) |
| Distributed Training | ⭐⭐⭐⭐⭐ (TPU 지원) | ⭐⭐⭐⭐ (DDP) | ⭐⭐⭐⭐⭐ (XLA) |
| 모델 최적화 | ⭐⭐⭐⭐⭐ (Lite, Quantization) | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| 커뮤니티/생태계 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 학습 곡선 | 중간 (Keras 쉬움) | 쉬움 | 어려움 |
TensorFlow의 핵심은 데이터 플로우 그래프입니다. 노드(연산)와 엣지(텐서)로 구성되며, Eager Execution(즉시 실행)과 Graph Mode(정적 그래프)를 지원합니다. Keras는 고수준 API로 모델 빌드 간소화.
주요 개념:
이 아키텍처는 입력 데이터가 파이프라인을 거쳐 그래프 실행 후 하드웨어에서 병렬 처리됩니다.
pip install tensorflow[and-cuda] # GPU 지원
# 또는 conda
conda create -n tf python=3.10
conda activate tf
pip install tensorflow
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
import tensorflow as tf
from tensorflow import keras
# 데이터 로드
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
# 모델 빌드
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 학습
model.fit(x_train, y_train, epochs=5, batch_size=32)
# 평가
model.evaluate(x_test, y_test)
이 예제는 5 에폭 후 98% 정확도를 달성합니다. tf.data로 대규모 데이터셋에 확장하세요.
| 설정 | 코드 | 용도 |
|---|---|---|
| 메모리 성장 | tf.config.experimental.set_memory_growth(gpu, True) | GPU 메모리 동적 할당 |
| 분산 전략 | strategy = tf.distribute.MirroredStrategy() | 멀티 GPU 학습 |
| tf.function | @tf.function def train_step(...) | 그래프 컴파일 |
| Dataset 캐싱 | dataset.cache().prefetch(tf.data.AUTOTUNE) | 성능 최적화 |
| Mixed Precision | tf.keras.mixed_precision.set_global_policy('mixed_float16') | 메모리/속도 향상 |
| TPU 초기화 | resolver = tf.distribute.cluster_resolver.TPUClusterResolver() | Google Cloud TPU |
tf.data.Dataset을 사용해 데이터 로딩을 병렬화하세요. dataset.map(num_parallel_calls=tf.data.AUTOTUNE)로 CPU 활용 극대화.
GPU 메모리 초과 시: 배치 사이즈 줄이기, gradient accumulation 사용, 또는 set_memory_growth(True) 적용. Mixed Precision 활성화로 50% 절감.
tf.saved_model.save(model, 'path') 후 TensorFlow Serving으로 서빙. ONNX 변환: tf2onnx.convert.from_keras(model).
TensorFlow 2.15는 CUDA 12.2/CUDNN 8.9 필요. nvcc --version 확인 후 재설치: pip install tensorflow[and-cuda].
TensorBoard로 모니터링: %load_ext tensorboard; %tensorboard --logdir logs. tf.profiler로 병목 분석.