🚀 Double DQN · LunarLander-v3
LunarLander-v3 를 1000 에피소드 학습시킨 Double DQN 에이전트입니다.
stable-baselines3 같은 RL 프레임워크는 쓰지 않고, Q네트워크 / 리플레이 버퍼 /
타깃 네트워크를 PyTorch 코드로 직접 다룹니다.
A Double DQN agent for LunarLander-v3, trained for 1000 episodes.
No RL framework (stable-baselines3 etc.) — the Q-network, replay buffer and target
network are plain PyTorch code.

출처 / Provenance
정확히 밝힙니다. 이 코드는 백지에서 새로 쓴 것이 아닙니다.
- 기반: 널리 쓰이는 DQN 튜토리얼 구현(Udacity 스타일)에서 출발한 Colab 노트북 코드
- 여기에 더한 것: 실행이 안 되던 import 누락 수정, Double DQN 전환, Huber 손실 + 그래디언트 클리핑, 은닉층 64→128, 타깃망 초기화 정리, 체크포인트 포맷, 평가/녹화 스크립트, 실시간 웹 대시보드, 착륙 품질 점수
- 작성: 위 수정·확장과 문서화는 Claude (Claude Code) 의 도움을 받아 진행했습니다.
Honest attribution: this is not a from-scratch implementation. It starts from a widely circulated DQN tutorial notebook (Udacity-style), with bug fixes and the additions listed above; that work and this model card were done with the help of Claude (Claude Code).
성능 / Results
아래 수치는 학습이 끝난 모델을 100번 착륙시켜 잰 평가 결과입니다
(학습 자체는 1000 에피소드 · 탐험 없음 ε=0 · 고정 시드, evaluate.py --episodes 100).
Evaluation over 100 episodes of the finished agent (training itself ran for 1000 episodes).
| 체크포인트 | 평균 보상 | 착륙 성공률 | 평균 착륙 품질 |
|---|---|---|---|
lunarlander_dqn.pth (기본) | 223.14 ± 84.58 | 74% | 61.3 / 100 |
lunarlander_dqn_softlanding.pth | 203.30 ± 62.41 | 84% | 64.5 / 100 |
- 평균 보상이 높은 쪽은 기본 모델, 깔끔하게 착지하는 빈도는 soft-landing 쪽이 높습니다.
- 학습 1000판 중 498판째에 200점 기준을 돌파했고, 이후 계속 학습해 1000판을 채웠습니다.
- 학습 중(ε=0.05) 최근 100판 이동평균 최고 기록: 260.5점, 그 구간 착륙 성공률 97~98% (이동평균의 "100"은 평균을 내는 창 크기이지, 학습 판수가 아닙니다.)
The default checkpoint scores higher on mean reward; the
softlandingone lands cleanly more often (its failures are mostly hovering until timeout rather than crashes).
사용법 / Usage
import gymnasium as gym, torch
from huggingface_hub import hf_hub_download
from dqn_agent import Agent # 이 저장소의 dqn_agent.py
ckpt = hf_hub_download("SionJang/lunarlander-v3-double-dqn", "lunarlander_dqn.pth")
env = gym.make("LunarLander-v3", render_mode="human")
agent = Agent(env.observation_space.shape[0], int(env.action_space.n)).load(ckpt)
state, _ = env.reset()
done = False
while not done:
action = agent.act(state, 0.0) # eps=0 → 탐험 없이 실력만
state, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
env.close()
저장소에 들어 있는 스크립트로 바로 돌릴 수도 있습니다:
python evaluate.py --ckpt lunarlander_dqn.pth --episodes 100 # 평가
python watch.py --ckpt lunarlander_dqn.pth # 웹으로 감상
python record_gif.py --ckpt lunarlander_dqn.pth # GIF 녹화
python train.py --episodes 1000 # 처음부터 재학습
학습 설정 / Training setup
| 항목 | 값 |
|---|---|
| 알고리즘 | Double DQN (행동 선택 = 학습망, 가치 평가 = 타깃망) |
| 신경망 | 8 → 128 → 128 → 4 (ReLU) |
| 옵티마이저 | Adam, lr 5e-4 |
| 손실 | Huber (smooth L1), grad clip 10 |
| 탐험 ε | 1.0 → 0.05, 판마다 ×0.995 |
| 에피소드 | 1000 (판당 최대 1000 스텝) |
| 리플레이 버퍼 | 100,000 / 배치 64 / 4스텝마다 학습 |
| 타깃망 | soft update τ = 0.001 |
| 감마 | 0.99 |
| 학습 시간 | 약 28분 (Intel i7-11800H, CPU만 사용 / CUDA 미사용) |
착륙 품질 점수 (Landing style score)
환경 보상은 "성공했는가"만 보기 때문에, "얼마나 깔끔하게 내렸는가"를 따로 0~100으로 매겼습니다
(style_score.py). The env reward only tells you whether it landed; this extra score measures how well.
| 항목 | 배점 | 기준 |
|---|---|---|
| 중앙 정확도 | 40 | 착륙대 정중앙에 가까울수록 |
| 접지 부드러움 | 25 | 접지 속도가 느릴수록 |
| 자세 수평 | 20 | 기울기·회전이 적을수록 |
| 연료 절약 | 15 | 엔진 점화 비율이 낮을수록 |
등급 / grades: S(90+) A(80+) B(65+) C(45+) D
실시간 학습 대시보드 / Live training dashboard
train.py는 학습 과정을 브라우저에서 실시간으로 보여주는 웹 대시보드를 함께 띄웁니다
(http://127.0.0.1:7000). Flask 같은 웹 프레임워크 없이 파이썬 표준 http.server 로
돌아가고, 화면 프레임을 JPEG로 바꾸는 데만 Pillow를 씁니다. 실시간 착륙 화면 + HUD,
학습 곡선, ε 감소 곡선, 착륙 품질 점수, 잘된 착륙 GIF 모음이 들어 있습니다.
train.py also serves a live dashboard — no web framework, just the stdlib http.server
(plus Pillow for JPEG encoding of frames): streamed render of the lander, telemetry HUD,
learning curve, ε schedule, and a hall of fame of the best landings.
한계 / Limitations
- 실패 사례 대부분은 추락이 아니라 착륙대 위에서 맴돌다 1000스텝 타임아웃입니다. ε=0의 결정론적 정책이 가진 전형적 약점입니다.
- 표준편차가 큽니다(±85). 시드에 따라 편차가 있으니 재현 시 참고하세요.