Commit da4837fb authored by Eduard Pizur's avatar Eduard Pizur
Browse files

updated parameters

parent 1b8690f5
# Default ignored files
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<list size="61">
<item index="0" class="java.lang.String" itemvalue="traitlets" />
<item index="1" class="java.lang.String" itemvalue="absl-py" />
<item index="2" class="java.lang.String" itemvalue="protobuf" />
<item index="3" class="java.lang.String" itemvalue="atomicwrites" />
<item index="4" class="java.lang.String" itemvalue="pickleshare" />
<item index="5" class="java.lang.String" itemvalue="python-dateutil" />
<item index="6" class="java.lang.String" itemvalue="py" />
<item index="7" class="java.lang.String" itemvalue="cycler" />
<item index="8" class="java.lang.String" itemvalue="pyasn1-modules" />
<item index="9" class="java.lang.String" itemvalue="Pygments" />
<item index="10" class="java.lang.String" itemvalue="pyzmq" />
<item index="11" class="java.lang.String" itemvalue="certifi" />
<item index="12" class="java.lang.String" itemvalue="oauthlib" />
<item index="13" class="java.lang.String" itemvalue="pyparsing" />
<item index="14" class="java.lang.String" itemvalue="Markdown" />
<item index="15" class="java.lang.String" itemvalue="pywin32" />
<item index="16" class="java.lang.String" itemvalue="Werkzeug" />
<item index="17" class="java.lang.String" itemvalue="pyglet" />
<item index="18" class="java.lang.String" itemvalue="kiwisolver" />
<item index="19" class="java.lang.String" itemvalue="jupyter-client" />
<item index="20" class="java.lang.String" itemvalue="ipykernel" />
<item index="21" class="java.lang.String" itemvalue="attrs" />
<item index="22" class="java.lang.String" itemvalue="atari-py" />
<item index="23" class="java.lang.String" itemvalue="jedi" />
<item index="24" class="java.lang.String" itemvalue="tensorboard" />
<item index="25" class="java.lang.String" itemvalue="backcall" />
<item index="26" class="java.lang.String" itemvalue="matplotlib" />
<item index="27" class="java.lang.String" itemvalue="gym" />
<item index="28" class="java.lang.String" itemvalue="idna" />
<item index="29" class="java.lang.String" itemvalue="rsa" />
<item index="30" class="java.lang.String" itemvalue="decorator" />
<item index="31" class="java.lang.String" itemvalue="jupyter-core" />
<item index="32" class="java.lang.String" itemvalue="more-itertools" />
<item index="33" class="java.lang.String" itemvalue="pluggy" />
<item index="34" class="java.lang.String" itemvalue="cloudpickle" />
<item index="35" class="java.lang.String" itemvalue="wcwidth" />
<item index="36" class="java.lang.String" itemvalue="pycodestyle" />
<item index="37" class="java.lang.String" itemvalue="numpy" />
<item index="38" class="java.lang.String" itemvalue="pyasn1" />
<item index="39" class="java.lang.String" itemvalue="requests" />
<item index="40" class="java.lang.String" itemvalue="requests-oauthlib" />
<item index="41" class="java.lang.String" itemvalue="tensorboard-plugin-wit" />
<item index="42" class="java.lang.String" itemvalue="prompt-toolkit" />
<item index="43" class="java.lang.String" itemvalue="urllib3" />
<item index="44" class="java.lang.String" itemvalue="autopep8" />
<item index="45" class="java.lang.String" itemvalue="scipy" />
<item index="46" class="java.lang.String" itemvalue="six" />
<item index="47" class="java.lang.String" itemvalue="tornado" />
<item index="48" class="java.lang.String" itemvalue="google-auth-oauthlib" />
<item index="49" class="java.lang.String" itemvalue="opencv-python" />
<item index="50" class="java.lang.String" itemvalue="parso" />
<item index="51" class="java.lang.String" itemvalue="pytest" />
<item index="52" class="java.lang.String" itemvalue="ipython" />
<item index="53" class="java.lang.String" itemvalue="packaging" />
<item index="54" class="java.lang.String" itemvalue="toml" />
<item index="55" class="java.lang.String" itemvalue="colorama" />
<item index="56" class="java.lang.String" itemvalue="future" />
<item index="57" class="java.lang.String" itemvalue="cachetools" />
<item index="58" class="java.lang.String" itemvalue="grpcio" />
<item index="59" class="java.lang.String" itemvalue="google-auth" />
<item index="60" class="java.lang.String" itemvalue="Pillow" />
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6" project-jdk-type="Python SDK" />
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<module fileurl="file://$PROJECT_DIR$/.idea/dp-2020.iml" filepath="$PROJECT_DIR$/.idea/dp-2020.iml" />
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
\ No newline at end of file
import collections
import cv2
import numpy as np
import os
os.environ.setdefault('PATH', '')
from collections import deque
import matplotlib.pyplot as plt
import gym
from gym import spaces
import cv2
from .wrappers import TimeLimit
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset.
No-op is assumed to be action 0.
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
self.noop_action = 0
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
def reset(self, **kwargs):
""" Do no-op action for a number of steps in [1, noop_max]."""
if self.override_num_noops is not None:
noops = self.override_num_noops
noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) #pylint: disable=E1101
assert noops > 0
obs = None
for _ in range(noops):
obs, _, done, _ = self.env.step(self.noop_action)
if done:
obs = self.env.reset(**kwargs)
return obs
def step(self, ac):
return self.env.step(ac)
class FireResetEnv(gym.Wrapper):
def __init__(self, env):
"""Take action on reset for environments that are fixed until firing."""
gym.Wrapper.__init__(self, env)
assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
assert len(env.unwrapped.get_action_meanings()) >= 3
def reset(self, **kwargs):
obs, _, done, _ = self.env.step(1)
if done:
obs, _, done, _ = self.env.step(2)
if done:
return obs
def step(self, ac):
return self.env.step(ac)
class EpisodicLifeEnv(gym.Wrapper):
def __init__(self, env):
"""Make end-of-life == end-of-episode, but only reset on true game over.
Done by DeepMind for the DQN and co. since it helps value estimation.
gym.Wrapper.__init__(self, env)
self.lives = 0
self.was_real_done = True
def plot_learning_curve(x, scores, epsilons, filename, lines=None):
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.plot(x, epsilons, color="C0")
ax.set_xlabel("Training Steps", color="C0")
ax.set_ylabel("Epsilon", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
N = len(scores)
running_avg = np.empty(N)
for t in range(N):
running_avg[t] = np.mean(scores[max(0, t-20):(t+1)])
ax2.scatter(x, running_avg, color="C1")
ax2.set_ylabel('Score', color="C1")
ax2.tick_params(axis='y', colors="C1")
if lines is not None:
for line in lines:
class RepeatActionAndMaxFrame(gym.Wrapper):
def __init__(self, env=None, repeat=4, clip_reward=False, no_ops=0,
super(RepeatActionAndMaxFrame, self).__init__(env)
self.repeat = repeat
self.shape = env.observation_space.low.shape
self.frame_buffer = np.zeros_like((2, self.shape))
self.clip_reward = clip_reward
self.no_ops = no_ops
self.fire_first = fire_first
def step(self, action):
obs, reward, done, info = self.env.step(action)
self.was_real_done = done
# check current lives, make loss of life terminal,
# then update lives to handle bonus lives
lives = self.env.unwrapped.ale.lives()
if lives < self.lives and lives > 0:
# for Qbert sometimes we stay in lives == 0 condition for a few frames
# so it's important to keep lives > 0, so that we only reset once
# the environment advertises done.
done = True
self.lives = lives
return obs, reward, done, info
def reset(self, **kwargs):
"""Reset only when lives are exhausted.
This way all states are still reachable even though lives are episodic,
and the learner need not know about any of this behind-the-scenes.
if self.was_real_done:
obs = self.env.reset(**kwargs)
# no-op step to advance from terminal/lost life state
obs, _, _, _ = self.env.step(0)
self.lives = self.env.unwrapped.ale.lives()
return obs
class MaxAndSkipEnv(gym.Wrapper):
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
gym.Wrapper.__init__(self, env)
# most recent raw observations (for max pooling across time steps)
self._obs_buffer = np.zeros((2,)+env.observation_space.shape, dtype=np.uint8)
self._skip = skip
def step(self, action):
"""Repeat action, sum reward, and max over last observations."""
total_reward = 0.0
done = None
for i in range(self._skip):
t_reward = 0.0
done = False
for i in range(self.repeat):
obs, reward, done, info = self.env.step(action)
if i == self._skip - 2: self._obs_buffer[0] = obs
if i == self._skip - 1: self._obs_buffer[1] = obs
total_reward += reward
if self.clip_reward:
reward = np.clip(np.array([reward]), -1, 1)[0]
t_reward += reward
idx = i % 2
self.frame_buffer[idx] = obs
if done:
# Note that the observation on the done=True frame
# doesn't matter
max_frame = self._obs_buffer.max(axis=0)
return max_frame, total_reward, done, info
def reset(self, **kwargs):
return self.env.reset(**kwargs)
max_frame = np.maximum(self.frame_buffer[0], self.frame_buffer[1])
return max_frame, t_reward, done, info
class ClipRewardEnv(gym.RewardWrapper):
def __init__(self, env):
gym.RewardWrapper.__init__(self, env)
def reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
class WarpFrame(gym.ObservationWrapper):
def __init__(self, env, width=84, height=84, grayscale=True, dict_space_key=None):
Warp frames to 84x84 as done in the Nature paper and later work.
If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which
observation should be warped.
self._width = width
self._height = height
self._grayscale = grayscale
self._key = dict_space_key
if self._grayscale:
num_colors = 1
num_colors = 3
new_space = gym.spaces.Box(
shape=(self._height, self._width, num_colors),
if self._key is None:
original_space = self.observation_space
self.observation_space = new_space
original_space = self.observation_space.spaces[self._key]
self.observation_space.spaces[self._key] = new_space
assert original_space.dtype == np.uint8 and len(original_space.shape) == 3
def observation(self, obs):
if self._key is None:
frame = obs
frame = obs[self._key]
def reset(self):
obs = self.env.reset()
no_ops = np.random.randint(self.no_ops)+1 if self.no_ops > 0 else 0
for _ in range(no_ops):
_, _, done, _ = self.env.step(0)
if done:
if self.fire_first:
assert self.env.unwrapped.get_action_meanings()[1] == 'FIRE'
obs, _, _, _ = self.env.step(1)
if self._grayscale:
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
frame = cv2.resize(
frame, (self._width, self._height), interpolation=cv2.INTER_AREA
if self._grayscale:
frame = np.expand_dims(frame, -1)
self.frame_buffer = np.zeros_like((2,self.shape))
self.frame_buffer[0] = obs
if self._key is None:
obs = frame
obs = obs.copy()
obs[self._key] = frame
return obs
class PreprocessFrame(gym.ObservationWrapper):
def __init__(self, shape, env=None):
super(PreprocessFrame, self).__init__(env)
self.shape = (shape[2], shape[0], shape[1])
self.observation_space = gym.spaces.Box(low=0.0, high=1.0,
shape=self.shape, dtype=np.float32)
class FrameStack(gym.Wrapper):
def __init__(self, env, k):
"""Stack k last frames.
Returns lazy array, which is much more memory efficient.
See Also
gym.Wrapper.__init__(self, env)
self.k = k
self.frames = deque([], maxlen=k)
shp = env.observation_space.shape
self.observation_space = spaces.Box(low=0, high=255, shape=(shp[:-1] + (shp[-1] * k,)), dtype=env.observation_space.dtype)
def observation(self, obs):
new_frame = cv2.cvtColor(obs, cv2.COLOR_RGB2GRAY)
resized_screen = cv2.resize(new_frame, self.shape[1:],
new_obs = np.array(resized_screen, dtype=np.uint8).reshape(self.shape)
new_obs = new_obs / 255.0
return new_obs
class StackFrames(gym.ObservationWrapper):
def __init__(self, env, repeat):
super(StackFrames, self).__init__(env)
self.observation_space = gym.spaces.Box(
env.observation_space.low.repeat(repeat, axis=0),
env.observation_space.high.repeat(repeat, axis=0),
self.stack = collections.deque(maxlen=repeat)
def reset(self):
ob = self.env.reset()
for _ in range(self.k):
return self._get_ob()
observation = self.env.reset()
for _ in range(self.stack.maxlen):
def step(self, action):
ob, reward, done, info = self.env.step(action)
return self._get_ob(), reward, done, info
def _get_ob(self):
assert len(self.frames) == self.k
return LazyFrames(list(self.frames))
class ScaledFloatFrame(gym.ObservationWrapper):
def __init__(self, env):
gym.ObservationWrapper.__init__(self, env)
self.observation_space = gym.spaces.Box(low=0, high=1, shape=env.observation_space.shape, dtype=np.float32)
return np.array(self.stack).reshape(self.observation_space.low.shape)
def observation(self, observation):
# careful! This undoes the memory optimization, use
# with smaller replay buffers only.
return np.array(observation).astype(np.float32) / 255.0
class LazyFrames(object):
def __init__(self, frames):
"""This object ensures that common frames between the observations are only stored once.
It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay
This object should only be converted to numpy array before being passed to the model.
You'd not believe how complex the previous solution was."""
self._frames = frames
self._out = None
def _force(self):
if self._out is None:
self._out = np.concatenate(self._frames, axis=-1)
self._frames = None
return self._out
def __array__(self, dtype=None):
out = self._force()
if dtype is not None:
out = out.astype(dtype)
return out
def __len__(self):
return len(self._force())
def __getitem__(self, i):
return self._force()[i]
def count(self):
frames = self._force()
return frames.shape[frames.ndim - 1]
def frame(self, i):
return self._force()[..., i]
return np.array(self.stack).reshape(self.observation_space.low.shape)
def make_atari(env_id, max_episode_steps=None):
env = gym.make(env_id)
assert 'NoFrameskip' in
env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
if max_episode_steps is not None:
env = TimeLimit(env, max_episode_steps=max_episode_steps)
return env
def make_env(env_name, shape=(84,84,1), repeat=4, clip_rewards=False,
no_ops=0, fire_first=False):
env = gym.make(env_name)
env = RepeatActionAndMaxFrame(env, repeat, clip_rewards, no_ops, fire_first)
env = PreprocessFrame(shape, env)
env = StackFrames(env, repeat)
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):
"""Configure environment for DeepMind-style Atari.
if episode_life:
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = WarpFrame(env)
if scale:
env = ScaledFloatFrame(env)
if clip_rewards:
env = ClipRewardEnv(env)
if frame_stack:
env = FrameStack(env, 4)
return env
\ No newline at end of file
......@@ -42,7 +42,7 @@ class Agent():
choosing action based on the Epsilon greedy strategy
if random.random() > self.epsilon:
state_ = T.tensor([state], dtype=T.float32)
state_ = T.tensor([state], dtype=T.float32).to(DEVICE)
actions =
action = T.argmax(actions).item()
......@@ -54,7 +54,7 @@ class Agent():
decay epsilon
self.epsilon *= self.eps_dec if self.epsilon > self.eps_min else self.eps_min
self.epsilon = self.epsilon - self.eps_dec if self.epsilon > self.eps_min else self.eps_min
def replace_weights(self):
......@@ -75,6 +75,12 @@ class Agent():
experiences = self.memory.sample()
states, actions, next_states, rewards, dones = zip(*experiences)
print("states", states)
import sys
states = T.tensor(states, dtype=T.float32).to(self.device)
rewards = T.tensor(rewards, dtype=T.int32).to(self.device)
actions = T.tensor(actions, dtype=T.int64).to(self.device)
......@@ -11,13 +11,15 @@ from dqn_agent import Agent
from gym.wrappers import AtariPreprocessing
from gym.wrappers import FrameStack
from atari_wrappers import make_env
from parameters import *
if __name__ == '__main__':
# Initialization env using warppers for Atari Games preprocessing from gym
env = gym.make(ENVIRONMENT)
env = AtariPreprocessing(env, noop_max=0)
env = FrameStack(env, 4)
env = make_env(ENVIRONMENT)
# env = gym.make(ENVIRONMENT)
# env = AtariPreprocessing(env, noop_max=0)
# env = FrameStack(env, 4)
# Initializing agent
agent = Agent(num_of_actions=env.action_space.n,
......@@ -31,6 +33,7 @@ if __name__ == '__main__':
best_score = 0
learn_steps = 0
scores = []
for episode in range(NUM_OF_EPISODES):
# initilization of each episode
......@@ -65,9 +68,13 @@ if __name__ == '__main__':
# replace best_score with higher score
best_score = score if best_score > score else best_score
best_score = score if best_score < score else best_score
print('episode', episode, 'score:', score, 'best score', best_score)
avg_score = np.mean(scores[-100:])
print('episode: ', episode,'score: ', score,
' average score %.1f' % avg_score, 'best score %.2f' % best_score,
'epsilon %.2f' % agent.epsilon, 'steps', learn_steps)
# tb.add_scalar('Score', score, learn_steps)
......@@ -2,13 +2,13 @@ import torch
# constants
ENVIRONMENT = "MsPacmanNoFrameskip-v4"