-
Notifications
You must be signed in to change notification settings - Fork 0
/
navigation.py
92 lines (76 loc) · 2.54 KB
/
navigation.py
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
from unityagents import UnityEnvironment
import numpy as np
from utils import load_cfg
from ddqn import ddqn
from ddqn_agent import Agent
import matplotlib.pyplot as plt
# Load configuration from YAML
cfg = load_cfg()
# Define global configuration variables
env_path = cfg["Environment"]["Filepath"]
brain_index = cfg["Agent"]["Brain_index"]
def load_environment(env_path=env_path, brain_index=brain_index):
"""Load Unity environment
Params
======
env_path (str): The path of the Unity executable
brain_index (int): The index of the agent we want to act
"""
env = UnityEnvironment(file_name=env_path)
# get the default brain
brain_name = env.brain_names[brain_index]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector_observations[0]
print('States look like:', state)
state_size = len(state)
print('States have length:', state_size)
return env, state_size, action_size, brain_name
def save_weights(agent, fname="checkpoint.pth"):
"""Save weights of PyTorch model
Params
======
agent (Agent class): A Double-DQN Agent
fname (str): file name of weights to write to disk
"""
torch.save(agent.qnetwork_local.state_dict(), fname)
def plot_scores(scores):
"""Plot scores from training episodes
Params
======
scores (list<float>): episode scores during training
"""
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(np.arange(len(scores)), scores)
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.show()
def main():
"""Main function that ties it all together
Description
===========
Loads environment, instantiates agent, trains agent, saves weights,
and plots the scores.
"""
# Load the UnityMLAgents environment
env, state_size, action_size, brain_name = load_environment()
# Instantiate the agent
agent = Agent(state_size=state_size, action_size=action_size, seed=0)
# Use Double-DQN to train the agent
scores = ddqn(env, agent)
# Persist the weights of the learned model
save_weights(agent)
# Plot the scores from the training episodes.
plot_scores(scores)
# Clean up the workspace once finished.
env.close()
if __name__ == "__main__":
main()