TensorFlow
Google TensorFlow
Google이 개발한 오픈소스 머신러닝 프레임워크입니다. 텐서(다차원 배열) 연산 그래프를 기반으로 딥러닝 모델을 구축하고 학습시킵니다. TensorFlow Lite와 TensorFlow.js로 모바일, 웹 등 다양한 플랫폼에 배포할 수 있습니다.
Google TensorFlow
Google이 개발한 오픈소스 머신러닝 프레임워크입니다. 텐서(다차원 배열) 연산 그래프를 기반으로 딥러닝 모델을 구축하고 학습시킵니다. TensorFlow Lite와 TensorFlow.js로 모바일, 웹 등 다양한 플랫폼에 배포할 수 있습니다.
TensorFlow는 2015년 Google Brain 팀이 공개한 오픈소스 머신러닝 프레임워크입니다. 이름의 "Tensor"는 다차원 배열을, "Flow"는 데이터 흐름 그래프를 의미합니다. TensorFlow 2.x부터는 Keras가 기본 고수준 API로 통합되어, 직관적인 모델 정의와 학습이 가능합니다. 현재 2.18 버전(2025년 기준)이 최신 안정 버전으로, CUDA 12.3과 cuDNN 8.9.7을 지원합니다.
TensorFlow의 핵심 강점은 프로덕션 배포입니다. TensorFlow Serving으로 모델을 REST/gRPC API로 서빙하고, TensorFlow Lite로 모바일/임베디드 기기에 배포하며, TensorFlow.js로 웹 브라우저에서 실행할 수 있습니다. 또한 TPU(Tensor Processing Unit) 하드웨어와의 최적화된 연동으로 Google Cloud에서 대규모 학습 시 뛰어난 성능을 발휘합니다.
TensorFlow는 Eager Execution(즉시 실행)과 Graph Execution(그래프 실행) 두 가지 모드를 지원합니다. TF 2.x에서는 Eager가 기본이지만, @tf.function 데코레이터로 성능이 중요한 부분을 그래프로 컴파일할 수 있습니다. 이 하이브리드 접근은 개발 편의성과 프로덕션 성능을 모두 얻을 수 있게 합니다.
TensorFlow 생태계에는 TensorBoard(시각화), TFX(ML 파이프라인), TF Hub(사전학습 모델), TF Extended(프로덕션 ML) 등 다양한 도구가 포함됩니다. 특히 TensorBoard는 학습 과정의 손실/정확도 그래프, 모델 구조, 임베딩 시각화 등을 제공하여 모델 디버깅과 분석에 필수적인 도구입니다.
Keras API를 사용한 이미지 분류 모델 구축 및 학습 예제입니다.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# GPU 메모리 동적 할당 설정
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# 샘플 데이터셋 로드 (CIFAR-10)
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# CNN 모델 정의
model = keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
# 모델 컴파일
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# 콜백 설정
callbacks = [
keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True),
keras.callbacks.TensorBoard(log_dir='./logs'),
keras.callbacks.ModelCheckpoint('best_model.keras', save_best_only=True)
]
# 모델 학습
history = model.fit(
x_train, y_train,
epochs=20,
batch_size=64,
validation_split=0.2,
callbacks=callbacks
)
# 모델 평가
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'테스트 정확도: {test_acc:.4f}')
# 모델 저장 및 로드
model.save('cifar10_model.keras')
loaded_model = keras.models.load_model('cifar10_model.keras')
# TFLite 변환 (모바일 배포용)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
TensorFlow 2.18 (2025년 1월 기준) 시스템 요구사항 및 버전별 비교입니다.
| 요구사항 | TensorFlow 2.18 | TensorFlow 2.15 |
|---|---|---|
| CUDA 버전 | 12.3 | 12.2 |
| cuDNN 버전 | 8.9.7 | 8.9.4 |
| Python 버전 | 3.9 - 3.12 | 3.9 - 3.11 |
| 최소 GPU | Pascal (compute 6.0) | Pascal (compute 6.0) |
| 권장 VRAM | 8GB 이상 | 8GB 이상 |
| 특성 | TensorFlow | PyTorch |
|---|---|---|
| 고수준 API | Keras (내장) | PyTorch Lightning |
| 모바일 배포 | TFLite (우수) | PyTorch Mobile |
| 프로덕션 서빙 | TF Serving | TorchServe |
| TPU 지원 | 네이티브 지원 | XLA 통해 지원 |
| 디버깅 용이성 | TF 2.x Eager 모드 | 기본 Eager |
| 연구 vs 프로덕션 | 프로덕션 강점 | 연구 강점 |
TensorFlow는 오픈소스로 무료 사용 가능. Google Cloud TPU 사용 시 별도 비용 발생
"텐서플로우 2점대로 마이그레이션 하면서 케라스 Sequential API 쓰니까 훨씬 간단해졌어요"
→ TensorFlow 2.x에서 Keras가 기본 API로 통합되어 모델 정의가 간편해졌음을 표현
"TFLite로 변환해서 안드로이드에 배포했는데, 양자화 적용하니까 모델 사이즈 4분의 1로 줄었어요"
→ TensorFlow Lite 모바일 배포와 양자화(quantization) 최적화 설명
"TensorBoard 켜놓고 학습 돌리면 loss 그래프 실시간으로 볼 수 있어서 좋아요"
→ TensorBoard 시각화 도구 활용
GPU 메모리 전체 점유 문제
TensorFlow는 기본적으로 GPU 메모리를 전부 할당합니다. set_memory_growth(True)를 설정하여 필요한 만큼만 사용하도록 해야 합니다.
TF 1.x와 2.x 코드 혼용
tf.compat.v1.Session() 같은 TF 1.x 스타일 코드는 2.x에서 비효율적입니다. tf.function과 Eager Execution을 활용하세요.
CUDA/cuDNN 버전 불일치
TensorFlow 버전마다 요구하는 CUDA/cuDNN 버전이 다릅니다. 공식 문서에서 호환성 표를 반드시 확인하세요.
모델 저장 포맷 혼동
.h5(구버전)와 .keras(신버전) 포맷이 있습니다. TF 2.x에서는 .keras 포맷을 권장합니다.