Deep Q-Learning (DQN) 개념 및 구현
1. 개요
Deep Q-Learning(DQN)은 강화 학습에서 가장 널리 사용되는 알고리즘 중 하나로, 기존의 Q-Learning을 신경망(Deep Neural Network)과 결합하여 더욱 복잡한 환경에서도 학습할 수 있도록 확장한 기법입니다. 특히, DQN은 게임 AI, 로봇 제어, 자율 주행 등 다양한 분야에서 활용됩니다.
이 글에서는 DQN의 개념을 설명하고, Python과 TensorFlow/Keras를 사용하여 간단한 예제를 구현해 보겠습니다.
2. Q-Learning 복습
DQN을 이해하기 위해 먼저 기본적인 Q-Learning 개념을 복습하겠습니다.
2.1 Q-Learning이란?
Q-Learning은 가치 기반(Value-based) 강화 학습 기법으로, 상태(state)와 행동(action)에 대한 Q-값(Q-value)을 학습하여 최적의 정책을 찾는 방법입니다.
Q-값은 다음 벨만 방정식(Bellman Equation)에 의해 업데이트됩니다.
$$ Q(s, a) \leftarrow Q(s, a) + \alpha \big(R + \gamma \max_{a'} Q(s', a') - Q(s, a)\big) $$
- $ s $: 현재 상태
- $ a $: 수행한 행동
- $ R $: 보상
- $ s' $: 다음 상태
- $ \alpha $: 학습률(Learning Rate)
- $ \gamma $: 할인율(Discount Factor)
하지만, Q-Table을 이용한 기존의 Q-Learning은 상태 공간이 커질수록 테이블 크기가 기하급수적으로 증가하여 현실적인 문제에 적용하기 어렵습니다.
3. Deep Q-Network (DQN)의 등장
DQN은 기존 Q-Learning의 한계를 극복하기 위해 신경망(Neural Network)을 활용하여 Q-값을 근사하는 방법입니다.
3.1 DQN의 핵심 개념
DQN은 Q-Learning을 신경망으로 확장하면서 다음과 같은 기법을 도입하여 안정성을 향상시켰습니다.
Experience Replay:
- 학습 데이터(상태, 행동, 보상, 다음 상태)를 버퍼에 저장한 후, 무작위로 샘플링하여 학습함으로써 데이터 간의 상관관계를 줄입니다.
Target Network:
- 훈련 중에 사용되는 목표 네트워크(Target Network)와 실시간으로 업데이트되는 주 네트워크(Main Network)를 분리하여 학습 안정성을 높입니다.
Huber Loss 사용:
- 기존의 MSE(Mean Squared Error) 대신 Huber Loss를 사용하여 학습 과정에서 발생하는 큰 오차를 완화합니다.
4. DQN 구현하기 (CartPole 예제)
이제 Python과 TensorFlow를 이용하여 간단한 DQN을 구현해 보겠습니다. OpenAI Gym의 CartPole-v1 환경을 사용합니다.
4.1 필요한 라이브러리 설치
pip install gym tensorflow numpy matplotlib
4.2 DQN 구현 코드
import gym
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
import random
from collections import deque
# 환경 설정
env = gym.make("CartPole-v1")
# 하이퍼파라미터 설정
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
gamma = 0.95 # 할인율
learning_rate = 0.001 # 학습률
epsilon = 1.0 # 탐험률
epsilon_min = 0.01
epsilon_decay = 0.995
batch_size = 32
memory_size = 2000
dqn_memory = deque(maxlen=memory_size)
def build_model():
model = Sequential([
Dense(24, activation='relu', input_shape=(state_size,)),
Dense(24, activation='relu'),
Dense(action_size, activation='linear')
])
model.compile(loss='mse', optimizer=Adam(learning_rate=learning_rate))
return model
# 모델 생성
model = build_model()
target_model = build_model()
def replay():
if len(dqn_memory) < batch_size:
return
minibatch = random.sample(dqn_memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
target += gamma * np.amax(target_model.predict(next_state.reshape(1, -1), verbose=0))
target_f = model.predict(state.reshape(1, -1), verbose=0)
target_f[0][action] = target
model.fit(state.reshape(1, -1), target_f, epochs=1, verbose=0)
def train(episodes=1000):
global epsilon
for e in range(episodes):
state, _ = env.reset()
state = np.reshape(state, [1, state_size])
total_reward = 0
for time in range(500):
if np.random.rand() <= epsilon:
action = random.randrange(action_size)
else:
action = np.argmax(model.predict(state, verbose=0))
next_state, reward, done, _, _ = env.step(action)
next_state = np.reshape(next_state, [1, state_size])
dqn_memory.append((state, action, reward, next_state, done))
state = next_state
total_reward += reward
if done:
print(f"Episode: {e+1}, Score: {total_reward}, Epsilon: {epsilon:.2f}")
break
replay()
if epsilon > epsilon_min:
epsilon *= epsilon_decay
if e % 10 == 0:
target_model.set_weights(model.get_weights())
# 학습 시작
train(500)
5. 결론
이 글에서는 Deep Q-Learning(DQN)의 개념과 구현 방법을 살펴보았습니다. DQN은 기존 Q-Learning의 한계를 극복하며, 다양한 환경에서 효율적인 강화 학습 모델을 구축할 수 있도록 해줍니다.
다음 단계로 Double DQN, Dueling DQN, Prioritized Experience Replay와 같은 기법을 추가하여 성능을 더욱 향상시킬 수 있습니다.
DQN을 활용하여 다양한 강화 학습 환경에서 실험해 보시기 바랍니다!
'Python > Deep Learning' 카테고리의 다른 글
| 간단한 게임 에이전트 만들기 (CartPole 예제) (0) | 2026.02.03 |
|---|---|
| Q-Learning 알고리즘의 이해 및 구현 (0) | 2026.01.20 |
| 강화 학습(Reinforcement Learning)이란? 기초 개념 정리 (0) | 2026.01.19 |
| 전이 학습을 활용한 스타일 변환(Style Transfer) (1) | 2026.01.18 |
| Fine-Tuning을 이용한 모델 성능 개선 (1) | 2026.01.15 |