Spaces:
Sleeping
Sleeping
File size: 16,870 Bytes
64bc84e f19494d 64bc84e 80fd094 64bc84e 80fd094 64bc84e f82f049 64bc84e 3f76244 64bc84e 3f76244 64bc84e 3f76244 64bc84e 7bdb218 64bc84e 80fd094 64bc84e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | """
CarRacing-v3: ๋๋ค ์์ด์ ํธ vs DQN ์์ด์ ํธ ๋น๊ต ๋ฐ๋ชจ
Hugging Face Spaces (Gradio)์ฉ ์ฑ
๊ธฐ๋ฅ:
1. ์ฌ์ ํ์ต ๋ชจ๋ธ ๋ฐ๋ชจ (dqn_carracing.pth ๋ก๋)
2. ์ง์ ํ์ต์ํค๊ธฐ (์ํผ์๋ ์ ์ ํ โ ์ค์๊ฐ ํ์ต โ ๊ฒฐ๊ณผ ๋น๊ต)
"""
import gradio as gr
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import gymnasium as gym
import cv2
import random
import copy
import time
import tempfile
import os
from collections import deque
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 1. ๋ชจ๋ธ & ํ๊ฒฝ ์ ์ (5-1 ๋
ธํธ๋ถ๊ณผ ๋์ผ)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def preprocess_frame(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
resized = cv2.resize(gray, (84, 84))
return resized.astype(np.float32) / 255.0
def discrete_to_continuous(action):
action_map = {
0: np.array([-0.5, 0.1, 0.0]), # ์ขํ์ (๊ฐ์์ 0.1๋ก ๋ฎ์ถค)
1: np.array([0.0, 0.3, 0.0]), # ์ง์ง (๊ฐ์์ 0.3์ผ๋ก ๋ฎ์ถค)
2: np.array([0.5, 0.1, 0.0]), # ์ฐํ์ (๊ฐ์์ 0.1๋ก ๋ฎ์ถค)
3: np.array([0.0, 0.0, 0.8]) # ๋ธ๋ ์ดํฌ (์ ์ง)
}
return action_map.get(action, np.array([0.0, 0.0, 0.0]))
class CarRacingWrapper:
def __init__(self, render_mode=None):
self.env = gym.make("CarRacing-v3", render_mode=render_mode)
self.frames = deque(maxlen=4)
def reset(self):
obs, _ = self.env.reset()
p = preprocess_frame(obs)
for _ in range(4):
self.frames.append(p)
return np.array(list(self.frames))
def step(self, action):
obs, r, term, trunc, info = self.env.step(discrete_to_continuous(action))
self.frames.append(preprocess_frame(obs))
return np.array(list(self.frames)), r, term, trunc, info
def render(self):
return self.env.render()
def close(self):
self.env.close()
class DQN(nn.Module):
def __init__(self, action_dim=4, input_channels=4):
super().__init__()
self.conv1 = nn.Conv2d(input_channels, 32, 8, 4)
self.conv2 = nn.Conv2d(32, 64, 4, 2)
self.conv3 = nn.Conv2d(64, 64, 3, 1)
with torch.no_grad():
d = torch.zeros(1, input_channels, 84, 84)
d = F.relu(self.conv1(d))
d = F.relu(self.conv2(d))
d = F.relu(self.conv3(d))
self._cs = d.view(1, -1).size(1)
self.fc1 = nn.Linear(self._cs, 512)
self.fc2 = nn.Linear(512, action_dim)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
return self.fc2(x)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 2. ReplayBuffer & DQNAgent (5-1 ๋
ธํธ๋ถ๊ณผ ๋์ผ)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class ReplayBuffer:
def __init__(self, cap):
self.buffer = deque(maxlen=cap)
def push(self, s, a, r, ns, d):
self.buffer.append((s, a, r, ns, d))
def sample(self, bs):
batch = random.sample(self.buffer, bs)
s, a, r, ns, d = zip(*batch)
return (torch.FloatTensor(np.array(s)),
torch.LongTensor(np.array(a)),
torch.FloatTensor(np.array(r)),
torch.FloatTensor(np.array(ns)),
torch.BoolTensor(np.array(d)))
def __len__(self):
return len(self.buffer)
class DQNAgent:
def __init__(self, lr=0.0001, gamma=0.99, eps_start=1.0, eps_end=0.05,
eps_decay=0.995, buf_size=10000, batch_size=32, target_update=1000):
self.action_dim = 4
self.gamma = gamma
self.batch_size = batch_size
self.target_update_freq = target_update
self.main_net = DQN(4).to(device)
self.target_net = copy.deepcopy(self.main_net)
self.optimizer = optim.Adam(self.main_net.parameters(), lr=lr)
self.buffer = ReplayBuffer(buf_size)
self.epsilon = eps_start
self.eps_end = eps_end
self.eps_decay = eps_decay
self.step_count = 0
def select_action(self, state, training=True):
if training and random.random() < self.epsilon:
return random.randint(0, 3)
with torch.no_grad():
st = torch.FloatTensor(state).unsqueeze(0).to(device)
return self.main_net(st).argmax(1).item()
def update(self):
if len(self.buffer) < self.batch_size:
return None
s, a, r, ns, d = self.buffer.sample(self.batch_size)
s, a, r, ns, d = s.to(device), a.to(device), r.to(device), ns.to(device), d.to(device)
cq = self.main_net(s).gather(1, a.unsqueeze(1)).squeeze(1)
with torch.no_grad():
tq = r + self.gamma * self.target_net(ns).max(1)[0] * (~d).float()
loss = F.smooth_l1_loss(cq, tq)
self.optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(self.main_net.parameters(), 10.0)
self.optimizer.step()
self.step_count += 1
if self.step_count % self.target_update_freq == 0:
self.target_net.load_state_dict(self.main_net.state_dict())
return loss.item()
def decay_epsilon(self):
self.epsilon = max(self.eps_end, self.epsilon * self.eps_decay)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 3. ์ฌ์ ํ์ต ๋ชจ๋ธ ๋ก๋
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
MODEL_PATH = "dqn_carracing.pth"
pretrained_model = DQN(4).to(device)
if os.path.exists(MODEL_PATH):
try:
pretrained_model.load_state_dict(
torch.load(MODEL_PATH, map_location=device)
)
pretrained_model.eval()
MODEL_LOADED = True
print(f"โ
์ฌ์ ํ์ต ๋ชจ๋ธ ๋ก๋ ์๋ฃ: {MODEL_PATH}")
except Exception as e:
MODEL_LOADED = False
print(f"โ ๋ชจ๋ธ ๋ก๋ ์คํจ: {e}")
else:
MODEL_LOADED = False
print(f"โ ๏ธ ๋ชจ๋ธ ํ์ผ({MODEL_PATH})์ด ์์ต๋๋ค.")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 4. ์์ ๋
นํ ํจ์
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def record_episode(model, use_model=True, max_steps=400):
"""์ํผ์๋ ํ ํ์ ๋
นํํด์ mp4 ๊ฒฝ๋ก์ ์ด ๋ณด์์ ๋ฐํ"""
env = CarRacingWrapper(render_mode="rgb_array")
state = env.reset()
frames = []
total_reward = 0.0
for step in range(max_steps):
frame = env.render()
if frame is not None:
frames.append(frame)
if use_model:
with torch.no_grad():
st = torch.FloatTensor(state).unsqueeze(0).to(device)
action = model(st).argmax(1).item()
else:
action = random.randint(0, 3)
state, reward, term, trunc, _ = env.step(action)
total_reward += reward
if term or trunc:
break
env.close()
if not frames:
return None, 0.0
h, w, _ = frames[0].shape
tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(tmp.name, fourcc, 30, (w, h))
for f in frames:
writer.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR))
writer.release()
return tmp.name, total_reward
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 5. DQN ํ์ต ํจ์ (5-1 ๋
ธํธ๋ถ์ train_dqn ๊ธฐ๋ฐ)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def train_dqn(num_episodes, progress=gr.Progress()):
"""DQN์ ์ฒ์๋ถํฐ ํ์ตํ๊ณ , ํ์ต ๊ณผ์ ๊ณผ ๊ฒฐ๊ณผ ์์์ ๋ฐํ"""
num_episodes = int(num_episodes)
max_steps = 400
env = CarRacingWrapper(render_mode="rgb_array")
agent = DQNAgent(eps_decay=0.99)
episode_rewards = []
episode_losses = []
epsilons = []
start_time = time.time()
for episode in range(num_episodes):
progress((episode + 1) / num_episodes,
desc=f"ํ์ต ์ค: ์ํผ์๋ {episode+1}/{num_episodes}")
state = env.reset()
ep_reward = 0
ep_losses = []
# [์ถ๊ฐ] ์ฐ์ ๊ฐ์ (์์ ๋ณด์)์ ์ธ๋ ์นด์ดํฐ
negative_reward_count = 0
for step in range(max_steps):
action = agent.select_action(state)
next_state, reward, terminated, truncated, info = env.step(action)
done = terminated or truncated
# [์ถ๊ฐ] ํธ๋ ์ดํ ๋ฐฉ์ง ๋ฐ ๊ฐ์ ์ข
๋ฃ ๋ก์ง
if reward < 0:
negative_reward_count += 1
else:
negative_reward_count = 0 # ์์ ๋ณด์์ ๋ฐ์ผ๋ฉด ์นด์ดํฐ ์ด๊ธฐํ
# 50 ํ๋ ์(์ฝ 1.5์ด~2์ด) ์ฐ์์ผ๋ก ๊ฐ์ ๋ง ๋ฐ์๋ค๋ฉด ๊ธธ์ ์์ ๊ฒ์ผ๋ก ๊ฐ์ฃผ
if negative_reward_count >= 50:
done = True # ์ํผ์๋ ๊ฐ์ ์ข
๋ฃ
reward -= 20.0 # ํธ๋์ ์ดํํ ๊ฒ์ ๋ํ ๊ฐ๋ ฅํ ํ๋ํฐ ๋ถ์ฌ
agent.buffer.push(state, action, reward, next_state, done)
loss = agent.update()
if loss is not None:
ep_losses.append(loss)
state = next_state
ep_reward += reward
if done:
break
agent.decay_epsilon()
episode_rewards.append(ep_reward)
episode_losses.append(np.mean(ep_losses) if ep_losses else 0)
epsilons.append(agent.epsilon)
total_time = time.time() - start_time
env.close()
# ํ์ต๋ ๋ชจ๋ธ์ eval ๋ชจ๋๋ก ์ ํ
agent.main_net.eval()
# ํ์ต ์๋ฃ ํ ๊ฒฐ๊ณผ ์์ ๋
นํ
random_path, random_reward = record_episode(agent.main_net, use_model=False, max_steps=500)
trained_path, trained_reward = record_episode(agent.main_net, use_model=True, max_steps=500)
# ํ์ต ๋ก๊ทธ ์์ฑ
log_lines = []
for i in range(len(episode_rewards)):
if (i + 1) % 10 == 0 or i == 0 or i == len(episode_rewards) - 1:
avg_r = np.mean(episode_rewards[max(0, i-9):i+1])
log_lines.append(
f"์ํผ์๋ {i+1:>4}/{num_episodes} | "
f"๋ณด์: {episode_rewards[i]:>7.1f} | "
f"์ต๊ทผ10 ํ๊ท : {avg_r:>7.1f} | "
f"ฮต: {epsilons[i]:.3f}"
)
result_summary = (
f"=== ํ์ต ์๋ฃ ({num_episodes} ์ํผ์๋, {total_time/60:.1f}๋ถ ์์) ===\n"
f"์ต์ข
ํ๊ท ๋ณด์ (๋ง์ง๋ง 10): {np.mean(episode_rewards[-10:]):.1f}\n"
f"์ต๊ณ ๋ณด์: {np.max(episode_rewards):.1f}\n"
f"์ต์ ๋ณด์: {np.min(episode_rewards):.1f}\n"
f"\n--- ๋ฐ๋ชจ ๊ฒฐ๊ณผ ---\n"
f"๐ฒ ๋๋ค: {random_reward:.1f} vs ๐ง ํ์ต๋ DQN: {trained_reward:.1f} "
f"({'DQN ์น๋ฆฌ! ๐' if trained_reward > random_reward else '๋๋ค์ด ์ด๊น ๐
' if random_reward > trained_reward else '๋ฌด์น๋ถ'})"
)
log_text = "\n".join(log_lines)
return random_path, trained_path, result_summary, log_text
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 6. ์ฌ์ ํ์ต ๋ชจ๋ธ ๋ฐ๋ชจ ํธ๋ค๋ฌ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def run_pretrained_demo():
if not MODEL_LOADED:
return None, None, "โ ๏ธ ์ฌ์ ํ์ต ๋ชจ๋ธ ํ์ผ(dqn_carracing.pth)์ด ์์ต๋๋ค."
random_path, random_reward = record_episode(pretrained_model, use_model=False, max_steps=400)
trained_path, trained_reward = record_episode(pretrained_model, use_model=True, max_steps=400)
info = (
f"๐ฒ ๋๋ค: {random_reward:.1f} vs ๐ง ์ฌ์ ํ์ต DQN: {trained_reward:.1f} "
f"({'DQN ์น๋ฆฌ! ๐' if trained_reward > random_reward else '๋๋ค์ด ์ด๊น ๐
' if random_reward > trained_reward else '๋ฌด์น๋ถ'})"
)
return random_path, trained_path, info
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 7. Gradio UI
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Blocks(
title="๐๏ธ CarRacing: Random vs DQN",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown(
"""
# ๐๏ธ CarRacing-v3 : ๋๋ค vs DQN ์์ด์ ํธ
๊ฐํํ์ต(DQN)์ผ๋ก ํ์ตํ ์๋์ฐจ ์์ด์ ํธ์ ๋๋ค ์์ด์ ํธ๋ฅผ ๋น๊ตํฉ๋๋ค.
"""
)
# โโ ํญ 1: ์ฌ์ ํ์ต ๋ชจ๋ธ ๋ฐ๋ชจ โโ
with gr.Tab("๐ฆ ์ฌ์ ํ์ต ๋ชจ๋ธ ๋ฐ๋ชจ"):
gr.Markdown(
"### ๋ฏธ๋ฆฌ ํ์ต๋ ๋ชจ๋ธ(dqn_carracing.pth)๋ก ๋ฐ๋ก ๋น๊ต\n"
"์ด์ ์ ํ์ตํ์ฌ ์ ์ฅํ ๋ชจ๋ธ์ ๋ถ๋ฌ์ ๋๋ค ์์ด์ ํธ์ ๋น๊ตํฉ๋๋ค."
)
btn_pretrained = gr.Button("๐ ์ฌ์ ํ์ต ๋ชจ๋ธ ์คํ", variant="primary", size="lg")
with gr.Row():
vid_pre_r = gr.Video(label="๐ฒ ๋๋ค ์์ด์ ํธ")
vid_pre_t = gr.Video(label="๐ง ์ฌ์ ํ์ต DQN ์์ด์ ํธ")
txt_pre = gr.Textbox(label="๋น๊ต ๊ฒฐ๊ณผ", interactive=False)
btn_pretrained.click(
fn=run_pretrained_demo,
outputs=[vid_pre_r, vid_pre_t, txt_pre],
)
# โโ ํญ 2: ์ง์ ํ์ต์ํค๊ธฐ โโ
with gr.Tab("๐ ์ง์ ํ์ต์ํค๊ธฐ"):
gr.Markdown(
"### DQN์ ์ฒ์๋ถํฐ ํ์ต์ํค๊ณ ๊ฒฐ๊ณผ๋ฅผ ํ์ธ\n"
"์ํผ์๋ ์๋ฅผ ์ ํํ๋ฉด ํด๋น ํ์๋งํผ **์ค์ ๋ก ํ์ต**ํ ํ ๋๋ค ์์ด์ ํธ์ ๋น๊ตํฉ๋๋ค.\n"
"์ํผ์๋๊ฐ ๋ง์์๋ก ์ฑ๋ฅ์ด ์ข์์ง์ง๋ง ํ์ต ์๊ฐ๋ ๋์ด๋ฉ๋๋ค.\n\n"
"โฑ๏ธ **์์ ์์ ์๊ฐ** (CPU ๊ธฐ์ค): 50 ์ํผ์๋ ~5๋ถ / 100 ์ํผ์๋ ~10๋ถ / 300 ์ํผ์๋ ~30๋ถ"
)
num_episodes = gr.Slider(
10, 500, value=50, step=10,
label="ํ์ต ์ํผ์๋ ์",
info="DQN ํ์ต์ ์ฌ์ฉํ ์ํผ์๋ ์ (๋ง์์๋ก ์ฑ๋ฅ ํฅ์, ์๊ฐ ์ฆ๊ฐ)"
)
btn_train = gr.Button("๐ ํ์ต ์์", variant="primary", size="lg")
with gr.Row():
vid_train_r = gr.Video(label="๐ฒ ๋๋ค ์์ด์ ํธ")
vid_train_t = gr.Video(label="๐ง ํ์ต๋ DQN ์์ด์ ํธ")
txt_train_result = gr.Textbox(label="ํ์ต ๊ฒฐ๊ณผ ์์ฝ", interactive=False)
txt_train_log = gr.Textbox(label="ํ์ต ๋ก๊ทธ (10 ์ํผ์๋๋ง๋ค)", interactive=False, lines=10, max_lines=20)
btn_train.click(
fn=train_dqn,
inputs=[num_episodes],
outputs=[vid_train_r, vid_train_t, txt_train_result, txt_train_log],
)
# โโ ํ๋จ ์ ๋ณด โโ
gr.Markdown(
"""
---
**์ฌ์ฉ ๋ฐฉ๋ฒ**
1. **์ฌ์ ํ์ต ๋ชจ๋ธ ๋ฐ๋ชจ**: ๋ฏธ๋ฆฌ ํ์ต๋ ๋ชจ๋ธ(dqn_carracing.pth)๋ก ๋ฐ๋ก ๊ฒฐ๊ณผ๋ฅผ ํ์ธํฉ๋๋ค.
2. **์ง์ ํ์ต์ํค๊ธฐ**: ์ํผ์๋ ์๋ฅผ ์ ํํ๊ณ DQN์ ์ฒ์๋ถํฐ ํ์ต์ํต๋๋ค.
- ์ํผ์๋ ์๊ฐ ๋ง์์๋ก ๋ ์ ํ์ต๋ฉ๋๋ค.
- ํ์ต ์๋ฃ ํ ๋๋ค ์์ด์ ํธ์ ๋น๊ต ์์์ ์๋์ผ๋ก ์์ฑํฉ๋๋ค.
**๋ชจ๋ธ ํ์ผ**: `dqn_carracing.pth` (์ด์ ํ์ต ๋
ธํธ๋ถ์์ ์ ์ฅํ ํ์ผ)๋ฅผ ์ด Space์ ํจ๊ป ์
๋ก๋ํ์ธ์.
"""
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 8. ์คํ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
demo.launch()
|