-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmean_std.py
160 lines (123 loc) · 5.11 KB
/
mean_std.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
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
import numpy as np
import gym
import argparse
from reignforce import Agent
import sys
import matplotlib.pyplot as plt
import os
import pandas as pd
def plot(episode_rewards, policy, label, alpha, gamma, plot_path):
plt.figure()
plt.suptitle(policy)
plt.title(environment+r", $\alpha $ = "+str(alpha)+", $\gamma$ = "+str(gamma))
plt.plot(range(len(episode_rewards)),episode_rewards, '.-',label=label)
plt.xlabel('Number of Episodes')
plt.ylabel('Total reward')
plt.legend()
plt.savefig(plot_path+"/" + policy +"Reward.png")
plt.figure()
plt.suptitle(policy)
z1=pd.Series(episode_rewards).rolling(50).mean()
plt.title(environment+r", $\alpha $ = "+str(alpha)+", $\gamma$ = "+str(gamma)+ ", Best average reward: "+ str(np.max(z1)))
plt.plot(z1,label=label)
plt.xlabel('Number of Episodes')
plt.ylabel('Average Rewards over past 50 episodes')
plt.legend()
plt.savefig(plot_path+"/" + policy +"cumulative.png")
# plt.show()
def policy_sampling(env,agent,label, alpha, gamma, plot_path,ep=1000):
score_history = []
n_episodes = ep
for i in range(n_episodes):
done = False
score = 0
observation = env.reset()
while not done:
action = agent.choose_action(observation)
observation_,reward, done, info = env.step(action)
observation = observation_
score += reward
score_history.append(score)
print('episode ', i,'score %.1f' % score,
'average_score %.1f' % np.mean(score_history[-50:]))
plot(score_history, "Sampling_Policy",label, alpha, gamma, plot_path)
return [np.mean(score_history), np.std(score_history)]
def policy_max(env,agent,label, alpha, gamma, plot_path,ep=1000):
score_history = []
n_episodes = ep
for i in range(n_episodes):
done = False
score = 0
observation = env.reset()
while not done:
#Get the probability of performing actions
action_prob = agent.policy.predict(observation[np.newaxis, :])
#Get the location(action number) by finding the max position
action = np.argmax(action_prob)
observation_,reward, done, info = env.step(action)
observation = observation_
score += reward
score_history.append(score)
print('episode ', i,'score %.1f' % score,
'average_score %.1f' % np.mean(score_history[-50:]))
plot(score_history,"Max_Policy",label, alpha, gamma, plot_path)
return [np.mean(score_history), np.std(score_history)]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("path",help = "Folder Path to parents folder of weights of network, it should contain final.h5 and optimal.h5")
parser.add_argument("environment",help="CartPole or Acrobot or LunarLander or MountainCar")
args = parser.parse_args()
envs = {'CartPole': 'CartPole-v0',
'Acrobot': 'Acrobot-v1',
'LunarLander': 'LunarLander-v2',
'MountainCar':'MountainCar-v0'}
environment = args.environment
if environment in envs:
opengym_env = envs.get(environment, None)
else:
print("Please provide the right environment")
exit()
env = gym.make(opengym_env)
n_actions = env.action_space.n
n_states = len(env.observation_space.low)
givePath = args.path
if givePath[-1] != "/":
givePath+="/"
lists = ["final","optimal"]
for filename in os.listdir(givePath):
for types in lists:
temp = filename.rsplit("_")
label = temp[0]
gamma = 0.99
alpha = float(temp[1])
layers = ""
h1_layer = 0
h2_layer = 0
if(temp[2]=='1'):
h1_layer = int(temp[3])
elif(temp[2]=='2'):
h1_layer = int(temp[3])
h2_layer = int(temp[4])
for t in temp[3:]:
layers = layers + t
#Weights path
weight_path = givePath +filename + "/" + types +".h5"
#plots path
plot_path = givePath +filename + "/" + types + "/plot"
#mean std path
meanStd_path = givePath +filename + "/" + types + "/meanstd"
print(weight_path,plot_path,meanStd_path,h1_layer,h2_layer,layers,label,gamma,alpha)
if not os.path.exists(plot_path):
os.makedirs(plot_path)
agent = Agent(ALPHA = alpha, input_dims=n_states,
Gamma= gamma, n_actions = n_actions,layer1_size=h1_layer, layer2_size=h2_layer)
agent.policy.load_weights(weight_path)
print(agent.policy.get_weights())
episodes = 200
mean_std = []
print("----Max Policy----")
mean_std.append(policy_max(env, agent,label, alpha, gamma, plot_path,ep=episodes))
print("----Sampling Policy----")
mean_std.append(policy_sampling(env, agent,label, alpha, gamma, plot_path,ep=episodes))
print(mean_std)
np.save(meanStd_path,mean_std)