-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplay_policy_template.py
More file actions
56 lines (44 loc) · 1.4 KB
/
play_policy_template.py
File metadata and controls
56 lines (44 loc) · 1.4 KB
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
import sys
import numpy as np
import tensorflow as tf
try:
import gymnasium as gym
except ModuleNotFoundError:
print('gymnasium module not found. Try to install with')
print('pip install gymnasium[box2d]')
sys.exit(1)
# preprocessing function
def preprocess_image(obs):
img = tf.convert_to_tensor(obs, dtype=tf.float32)
img = tf.image.resize(img, (96, 96))
img = img / 255.0 # normalize to [0, 1]
return img
def play(env, model):
seed = 2000
obs, _ = env.reset(seed=seed)
# drop initial frames
action0 = 0
for _ in range(50):
obs,_,_,_,_ = env.step(action0)
done = False
simulation_score = 0
while not done:
preprocessed_obs = np.expand_dims(preprocess_image(obs), axis=0)
p = model.predict(preprocessed_obs)
action = np.argmax(p)
obs, reward, terminated, truncated, _ = env.step(action)
simulation_score += reward
done = terminated or truncated
print(simulation_score)
env_arguments = {
'domain_randomize': False,
'continuous': False,
'render_mode': 'human'
}
env_name = 'CarRacing-v2'
env = gym.make(env_name, **env_arguments)
print("Environment:", env_name)
print("Action space:", env.action_space)
print("Observation space:", env.observation_space)
model = tf.keras.models.load_model(sys.argv[1])
play(env, model)