Untitled
Anonymous
Plain Text
10/05/2025 1:11 PM
1.8 KB
16
Indexable
Never
import random
import torch
import numpy as np
import gymnasium as gym
from collections import deque
import config
from agent.agent import Agent
def train_agent(n_episodes=config.MAX_EPISODES, max_t=config.MAX_TIMESTEPS):
"""Train a reinforcement learning agent using the given environment and parameters."""
env = gym.make(config.ENV_NAME)
agent = Agent(
state_size=env.observation_space.shape[0],
action_size=env.action_space.n,
device=config.DEVICE
)
scores_on_100_episodes = deque(maxlen=100)
eps = config.EPS_START
for i_episode in range(1, n_episodes + 1):
state, _ = env.reset(seed=config.SEED)
total_reward = 0
for t in range(max_t):
action = agent.act(state, eps)
next_state, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
agent.step(state, action, reward, next_state, done)
state = next_state
total_reward += reward
if done:
break
# Decay epsilon
eps = max(config.EPS_END, config.EPS_DECAY * eps)
scores_on_100_episodes.append(total_reward)
avg_score = np.mean(scores_on_100_episodes)
print(
f"\rEpisode {i_episode}\tAvg(100): {avg_score:.2f}",
end="",
flush=True
)
# Stop early if environment is solved
if avg_score >= 200.0:
print(f"\nEnvironment solved in {i_episode} episodes!")
break
env.close()
return scores_on_100_episodes
if __name__ == "__main__":
random.seed(config.SEED)
np.random.seed(config.SEED)
torch.manual_seed(config.SEED)
train_agent()
Editor is loading...
Leave a Comment