ImaghT commited on
Commit
9523beb
·
verified ·
1 Parent(s): 71ca605

Upload Unit_4_2_continue.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. Unit_4_2_continue.py +488 -0
Unit_4_2_continue.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # Unit 4: Policy Gradient (REINFORCE) for Pixelcopter-PLE-v0
3
+ # Deep Reinforcement Learning Course - Hugging Face
4
+ # 支持继续训练版本
5
+ # ============================================================
6
+
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ from collections import deque
10
+ import gymnasium as gym
11
+ from gymnasium import spaces
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torch.optim as optim
16
+ import pickle
17
+ import os
18
+ from datetime import datetime
19
+
20
+ # ===== 修正的PLE环境导入和Wrapper =====
21
+ from ple.games.pixelcopter import Pixelcopter
22
+ from ple import PLE
23
+
24
+ class PLEWrapper(gym.Env):
25
+ def __init__(self):
26
+ super().__init__()
27
+ self.game = Pixelcopter()
28
+ # 只使用fps参数,移除display参数
29
+ self.env = PLE(self.game, fps=30)
30
+ self.env.init()
31
+
32
+ # 定义观察和动作空间
33
+ state_dim = len(self.env.getGameState())
34
+ self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(state_dim,), dtype=np.float32)
35
+ self.action_space = spaces.Discrete(len(self.env.getActionSet()))
36
+ self.actions = self.env.getActionSet()
37
+
38
+ def reset(self, seed=None):
39
+ self.env.reset_game()
40
+ state = np.array(list(self.env.getGameState().values()), dtype=np.float32)
41
+ return state, {}
42
+
43
+ def step(self, action):
44
+ reward = self.env.act(self.actions[action])
45
+ state = np.array(list(self.env.getGameState().values()), dtype=np.float32)
46
+ terminated = self.env.game_over()
47
+ return state, reward, terminated, False, {}
48
+
49
+ # ============================================================
50
+ # 设备配置
51
+ # ============================================================
52
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
53
+ print(f"Using device: {device}")
54
+
55
+ # ============================================================
56
+ # 环境配置
57
+ # ============================================================
58
+ env = PLEWrapper()
59
+ eval_env = PLEWrapper()
60
+ s_size = env.observation_space.shape[0]
61
+ a_size = env.action_space.n
62
+ print(f"Environment: Pixelcopter-PLE")
63
+ print(f"Observation Space: {s_size}, Action Space: {a_size}")
64
+
65
+ # ============================================================
66
+ # 策略网络定义
67
+ # ============================================================
68
+ class Policy(nn.Module):
69
+ """
70
+ 策略网络:输入状态,输出动作概率分布
71
+ """
72
+ def __init__(self, s_size, a_size, h_size=128):
73
+ """
74
+ 初始化策略网络
75
+ Args:
76
+ s_size: 状态空间维度
77
+ a_size: 动作空间维度
78
+ h_size: 隐藏层大小
79
+ """
80
+ super(Policy, self).__init__()
81
+ self.fc1 = nn.Linear(s_size, h_size)
82
+ self.fc2 = nn.Linear(h_size, h_size * 2)
83
+ self.fc3 = nn.Linear(h_size * 2, a_size)
84
+
85
+ # 添加dropout提高泛化能力
86
+ self.dropout = nn.Dropout(0.1)
87
+
88
+ def forward(self, x):
89
+ """
90
+ 前向传播
91
+ Args:
92
+ x: 输入状态
93
+ Returns:
94
+ 动作概率分布
95
+ """
96
+ x = F.relu(self.fc1(x))
97
+ x = self.dropout(x)
98
+ x = F.relu(self.fc2(x))
99
+ x = self.dropout(x)
100
+ x = self.fc3(x)
101
+ return F.softmax(x, dim=1)
102
+
103
+ def act(self, state):
104
+ """
105
+ 根据当前策略选择动作
106
+ Args:
107
+ state: 当前状态
108
+ Returns:
109
+ action: 选择的动作
110
+ log_prob: 该动作的对数概率(用于梯度计算)
111
+ """
112
+ # 转换状态为tensor并移到正确设备
113
+ state = torch.from_numpy(state).float().unsqueeze(0).to(device)
114
+
115
+ # 获取动作概率分布(保持在同一设备上)
116
+ probs = self.forward(state)
117
+
118
+ # 创建分类分布
119
+ m = torch.distributions.Categorical(probs)
120
+
121
+ # 采样动作(基于概率分布,不是贪心选择)
122
+ action = m.sample()
123
+
124
+ # 返回动作值和对数概率
125
+ return action.item(), m.log_prob(action)
126
+
127
+ # ============================================================
128
+ # 学习率调度器
129
+ # ============================================================
130
+ class LearningRateScheduler:
131
+ def __init__(self, optimizer, initial_lr, decay_rate=0.95, decay_episodes=5000):
132
+ self.optimizer = optimizer
133
+ self.initial_lr = initial_lr
134
+ self.decay_rate = decay_rate
135
+ self.decay_episodes = decay_episodes
136
+
137
+ def step(self, episode):
138
+ if episode > 0 and episode % self.decay_episodes == 0:
139
+ new_lr = self.initial_lr * (self.decay_rate ** (episode // self.decay_episodes))
140
+ for param_group in self.optimizer.param_groups:
141
+ param_group['lr'] = new_lr
142
+ print(f"📉 Learning rate decayed to: {new_lr:.2e}")
143
+
144
+ # ============================================================
145
+ # 改进的REINFORCE算法实现
146
+ # ============================================================
147
+ def reinforce_continued(policy, optimizer, n_training_episodes, max_t, gamma, print_every,
148
+ previous_scores=[], model_path=None, lr_scheduler=None):
149
+ """
150
+ 支持继续训练的REINFORCE算法
151
+ Args:
152
+ policy: 策略网络
153
+ optimizer: 优化器
154
+ n_training_episodes: 新增训练轮数
155
+ max_t: 每轮最大步数
156
+ gamma: 折扣因子
157
+ print_every: 打印间隔
158
+ previous_scores: 之前的训练分数
159
+ model_path: 模型保存路径
160
+ lr_scheduler: 学习率调度器
161
+ Returns:
162
+ scores: 所有得分列表(包括之前的)
163
+ """
164
+ scores_deque = deque(maxlen=100) # 保存最近100轮得分
165
+ scores = previous_scores.copy() # 保留之前的训练历史
166
+
167
+ # 如果有之前的分数,用最近的分数初始化deque
168
+ if previous_scores:
169
+ recent_scores = previous_scores[-100:] if len(previous_scores) >= 100 else previous_scores
170
+ scores_deque.extend(recent_scores)
171
+ print(f"📈 Resuming with recent average score: {np.mean(scores_deque):.2f}")
172
+ print(f"📊 Previous best score: {max(previous_scores):.2f}")
173
+
174
+ start_episode = len(previous_scores) + 1
175
+ best_avg_score = max([np.mean(previous_scores[max(0, i-99):i+1]) for i in range(len(previous_scores))]) if previous_scores else -float('inf')
176
+
177
+ print(f"🚀 Starting continued training from episode {start_episode}")
178
+ print(f"🎯 Target: Beat previous best average score of {best_avg_score:.2f}")
179
+ print()
180
+
181
+ for i_episode in range(start_episode, start_episode + n_training_episodes):
182
+ saved_log_probs = [] # 保存每步的log概率
183
+ rewards = [] # 保存每步的奖励
184
+ state, _ = env.reset()
185
+
186
+ # --- 1. 收集一条完整轨迹 ---
187
+ for t in range(max_t):
188
+ # 根据当前策略选择动作
189
+ action, log_prob = policy.act(state)
190
+ saved_log_probs.append(log_prob)
191
+
192
+ # 执行动作,获取下一状态和奖励
193
+ state, reward, terminated, truncated, _ = env.step(action)
194
+ rewards.append(reward)
195
+
196
+ # 检查是否结束
197
+ if terminated or truncated:
198
+ break
199
+
200
+ # 记录本轮总得分
201
+ episode_score = sum(rewards)
202
+ scores_deque.append(episode_score)
203
+ scores.append(episode_score)
204
+
205
+ # --- 2. 计算折扣回报 (Discounted Returns) ---
206
+ returns = deque(maxlen=max_t)
207
+ n_steps = len(rewards)
208
+
209
+ # 从后往前计算累计折扣回报:G_t = r_t + γ*r_{t+1} + γ²*r_{t+2} + ...
210
+ G = 0
211
+ for r in reversed(rewards):
212
+ G = r + gamma * G
213
+ returns.appendleft(G)
214
+
215
+ # 标准化回报(重要的工程技巧,提高训练稳定性)
216
+ returns = torch.tensor(returns).to(device)
217
+ if len(returns) > 1: # 避免标准差为0的情况
218
+ returns = (returns - returns.mean()) / (returns.std() + 1e-8)
219
+
220
+ # --- 3. 计算策略梯度损失 ---
221
+ # 策略梯度定理:∇J(θ) = E[∇log π(a|s) * G_t]
222
+ # 损失函数:L = -∑(log_prob * return) (负号因为要最大化回报)
223
+ policy_loss = []
224
+ for log_prob, return_val in zip(saved_log_probs, returns):
225
+ policy_loss.append(-log_prob * return_val)
226
+
227
+ # 合并所有损失
228
+ policy_loss = torch.cat(policy_loss).sum()
229
+
230
+ # --- 4. 反向传播更新参数 ---
231
+ optimizer.zero_grad()
232
+ policy_loss.backward()
233
+
234
+ # 添加梯度裁剪以提高训练稳定性
235
+ torch.nn.utils.clip_grad_norm_(policy.parameters(), max_norm=1.0)
236
+
237
+ optimizer.step()
238
+
239
+ # 学习率调度
240
+ if lr_scheduler:
241
+ lr_scheduler.step(i_episode)
242
+
243
+ # 打印训练进度
244
+ if i_episode % print_every == 0:
245
+ current_avg = np.mean(scores_deque)
246
+ current_lr = optimizer.param_groups[0]['lr']
247
+ print(f'Episode {i_episode:6d} | Avg Score: {current_avg:7.2f} | Last Score: {episode_score:7.2f} | Steps: {len(rewards):4d} | LR: {current_lr:.2e}')
248
+
249
+ # 检查是否创造新纪录
250
+ if current_avg > best_avg_score:
251
+ best_avg_score = current_avg
252
+ print(f"🎉 New best average score: {best_avg_score:.2f}")
253
+
254
+ # 保存最佳模型
255
+ if model_path:
256
+ best_model_path = model_path.replace('.pth', '_best.pth')
257
+ torch.save({
258
+ 'policy_state_dict': policy.state_dict(),
259
+ 'optimizer_state_dict': optimizer.state_dict(),
260
+ 's_size': s_size,
261
+ 'a_size': a_size,
262
+ 'hidden_size': policy.fc1.out_features,
263
+ 'scores': scores,
264
+ 'episode': i_episode,
265
+ 'best_avg_score': best_avg_score,
266
+ 'timestamp': datetime.now().isoformat()
267
+ }, best_model_path)
268
+ print(f"💾 Best model saved: {best_model_path}")
269
+
270
+ # 定期保存检查点
271
+ if model_path and i_episode % (print_every * 2) == 0:
272
+ checkpoint_path = model_path.replace('.pth', f'_checkpoint_{i_episode}.pth')
273
+ torch.save({
274
+ 'policy_state_dict': policy.state_dict(),
275
+ 'optimizer_state_dict': optimizer.state_dict(),
276
+ 's_size': s_size,
277
+ 'a_size': a_size,
278
+ 'hidden_size': policy.fc1.out_features,
279
+ 'scores': scores,
280
+ 'episode': i_episode,
281
+ 'timestamp': datetime.now().isoformat()
282
+ }, checkpoint_path)
283
+ print(f"💾 Checkpoint saved: {checkpoint_path}")
284
+
285
+ print()
286
+
287
+ return scores
288
+
289
+ # ============================================================
290
+ # 评估函数
291
+ # ============================================================
292
+ def evaluate_policy(policy, eval_env, n_eval_episodes=10):
293
+ """
294
+ 评估策略性能
295
+ Args:
296
+ policy: 训练好的策略网络
297
+ eval_env: 评估环境
298
+ n_eval_episodes: 评估轮数
299
+ Returns:
300
+ episode_rewards: 每轮奖励列表
301
+ mean_reward: 平均奖励
302
+ std_reward: 奖励标准差
303
+ """
304
+ episode_rewards = []
305
+
306
+ # 设置为评估模式
307
+ policy.eval()
308
+
309
+ for i in range(n_eval_episodes):
310
+ state, _ = eval_env.reset()
311
+ episode_reward = 0
312
+ done = False
313
+ steps = 0
314
+
315
+ while not done and steps < 10000: # 添加最大步数限制
316
+ # 评估时使用确定性策略(不采样,选择概率最大的动作)
317
+ with torch.no_grad():
318
+ state_tensor = torch.from_numpy(state).float().unsqueeze(0).to(device)
319
+ probs = policy.forward(state_tensor)
320
+ action = torch.argmax(probs, dim=1).item()
321
+
322
+ state, reward, terminated, truncated, _ = eval_env.step(action)
323
+ episode_reward += reward
324
+ done = terminated or truncated
325
+ steps += 1
326
+
327
+ episode_rewards.append(episode_reward)
328
+ print(f"Eval Episode {i+1:2d}: Reward = {episode_reward:7.2f} | Steps = {steps:4d}")
329
+
330
+ # 恢复训练模式
331
+ policy.train()
332
+
333
+ mean_reward = np.mean(episode_rewards)
334
+ std_reward = np.std(episode_rewards)
335
+
336
+ print(f"\n{'='*50}")
337
+ print(f"Evaluation Results:")
338
+ print(f"Mean Reward: {mean_reward:.2f}")
339
+ print(f"Std Reward: {std_reward:.2f}")
340
+ print(f"Score (mean - std): {mean_reward - std_reward:.2f}")
341
+ print(f"Required for Pixelcopter-PLE-v0: 5.0")
342
+ print(f"{'='*50}")
343
+
344
+ return episode_rewards, mean_reward, std_reward
345
+
346
+ # ============================================================
347
+ # 模型加载函数
348
+ # ============================================================
349
+ def load_model(model_path, policy, optimizer):
350
+ """
351
+ 加载已保存的模型
352
+ """
353
+ if os.path.exists(model_path):
354
+ print(f"🔄 Loading existing model from {model_path}")
355
+ checkpoint = torch.load(model_path, map_location=device, weights_only=False)
356
+
357
+ # 加载模型参数
358
+ policy.load_state_dict(checkpoint['policy_state_dict'])
359
+ optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
360
+
361
+ # 加载训练历史
362
+ previous_scores = checkpoint.get('scores', [])
363
+ episode = checkpoint.get('episode', 0)
364
+ best_avg_score = checkpoint.get('best_avg_score', -float('inf'))
365
+
366
+ print(f"✅ Model loaded successfully!")
367
+ print(f"📊 Loaded {len(previous_scores)} previous training episodes")
368
+ if previous_scores:
369
+ print(f"🎯 Previous best score: {max(previous_scores):.2f}")
370
+ print(f"🏆 Previous best average score: {best_avg_score:.2f}")
371
+
372
+ return previous_scores, episode, best_avg_score
373
+ else:
374
+ print("🆕 No existing model found, starting fresh training")
375
+ return [], 0, -float('inf')
376
+
377
+ # ============================================================
378
+ # 主训练流程
379
+ # ============================================================
380
+ if __name__ == "__main__":
381
+ # 超参数设置 - 针对继续训练优化
382
+ HIDDEN_SIZE = 256
383
+ INITIAL_LEARNING_RATE = 2e-5 # 继续训练时使用较小的学习率
384
+ N_TRAINING_EPISODES = 20000 # 继续训练的轮数
385
+ MAX_T = 10000
386
+ GAMMA = 0.995 # 稍微提高折扣因子
387
+ PRINT_EVERY = 1000
388
+
389
+ # 模型路径
390
+ MODEL_PATH = "/home/eason/Workspace/Result_DRL/reinforce_pixelcopter.pth"
391
+
392
+ print("="*60)
393
+ print("REINFORCE Continued Training for Pixelcopter-PLE-v0")
394
+ print("="*60)
395
+ print(f"📅 Training started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
396
+ print()
397
+
398
+ # 初始化策略网络和优化器
399
+ policy = Policy(s_size, a_size, HIDDEN_SIZE).to(device)
400
+ optimizer = optim.Adam(policy.parameters(), lr=INITIAL_LEARNING_RATE)
401
+
402
+ # 初始化学习率调度器
403
+ lr_scheduler = LearningRateScheduler(optimizer, INITIAL_LEARNING_RATE, decay_rate=0.95, decay_episodes=5000)
404
+
405
+ print(f"🧠 Policy Network: {policy}")
406
+ print(f"⚙️ Optimizer: Adam (initial_lr={INITIAL_LEARNING_RATE:.2e})")
407
+ print(f"📈 Training Episodes: {N_TRAINING_EPISODES}")
408
+ print(f"⏱️ Max Steps per Episode: {MAX_T}")
409
+ print(f"💰 Discount Factor: {GAMMA}")
410
+ print()
411
+
412
+ # 尝试加载已有模型
413
+ previous_scores, last_episode, best_avg_score = load_model(MODEL_PATH, policy, optimizer)
414
+
415
+ # 更新优化器学习率(确保使用当前设定的学习率)
416
+ for param_group in optimizer.param_groups:
417
+ param_group['lr'] = INITIAL_LEARNING_RATE
418
+
419
+ print(f"📚 Current learning rate: {INITIAL_LEARNING_RATE:.2e}")
420
+ print()
421
+
422
+ # 开始训练
423
+ print("🚀 Starting training...")
424
+ print("-" * 80)
425
+
426
+ scores = reinforce_continued(
427
+ policy=policy,
428
+ optimizer=optimizer,
429
+ n_training_episodes=N_TRAINING_EPISODES,
430
+ max_t=MAX_T,
431
+ gamma=GAMMA,
432
+ print_every=PRINT_EVERY,
433
+ previous_scores=previous_scores,
434
+ model_path=MODEL_PATH,
435
+ lr_scheduler=lr_scheduler
436
+ )
437
+
438
+ print("\n" + "="*60)
439
+ print("Training Completed!")
440
+ print("="*60)
441
+
442
+ # 保存最终模型
443
+ final_model_data = {
444
+ 'policy_state_dict': policy.state_dict(),
445
+ 'optimizer_state_dict': optimizer.state_dict(),
446
+ 's_size': s_size,
447
+ 'a_size': a_size,
448
+ 'hidden_size': HIDDEN_SIZE,
449
+ 'scores': scores,
450
+ 'total_episodes': len(scores),
451
+ 'final_avg_score': np.mean(scores[-100:]) if len(scores) >= 100 else np.mean(scores),
452
+ 'training_completed_at': datetime.now().isoformat(),
453
+ 'hyperparameters': {
454
+ 'learning_rate': INITIAL_LEARNING_RATE,
455
+ 'gamma': GAMMA,
456
+ 'hidden_size': HIDDEN_SIZE,
457
+ 'max_t': MAX_T
458
+ }
459
+ }
460
+
461
+ torch.save(final_model_data, MODEL_PATH)
462
+ print(f"✅ Final model saved to {MODEL_PATH}")
463
+
464
+ # 评估训练好的模型
465
+ print("\n" + "="*60)
466
+ print("Evaluating Final Policy")
467
+ print("="*60)
468
+
469
+ episode_rewards, mean_reward, std_reward = evaluate_policy(policy, eval_env, n_eval_episodes=10)
470
+
471
+ # 训练结果总结
472
+ print(f"\n🎉 Final Training Results:")
473
+ print(f" Total Episodes Trained: {len(scores)}")
474
+ print(f" Final Average Score (last 100): {np.mean(scores[-100:]) if len(scores) >= 100 else np.mean(scores):.2f}")
475
+ print(f" Best Single Episode Score: {max(scores):.2f}")
476
+ print(f" Evaluation Mean Reward: {mean_reward:.2f}")
477
+ print(f" Evaluation Std Reward: {std_reward:.2f}")
478
+ print(f" Final Score (mean - std): {mean_reward - std_reward:.2f}")
479
+ print(f" Required for Pixelcopter-PLE-v0: 5.0")
480
+
481
+ if mean_reward - std_reward >= 5.0:
482
+ print(f" Status: ✅ PASSED! Congratulations!")
483
+ else:
484
+ needed_improvement = 5.0 - (mean_reward - std_reward)
485
+ print(f" Status: ❌ Need {needed_improvement:.2f} more points")
486
+ print(f" Suggestion: Continue training with lower learning rate or adjust network architecture")
487
+
488
+ print(f"\n📅 Training completed at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")