-
Notifications
You must be signed in to change notification settings - Fork 1
/
moreinforce_minecart_pixel.py
151 lines (120 loc) · 4.44 KB
/
moreinforce_minecart_pixel.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
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import gym
from datetime import datetime
import uuid
class Flatten(nn.Module):
def forward(self, x):
return torch.flatten(x, start_dim=1)
class Actor(nn.Module):
def __init__(self, nS, nA):
super(Actor, self).__init__()
self.nS = nS
self.nA = nA
self.common = nn.Sequential(
nn.Conv2d(nS[0], 32, kernel_size=8, stride=4),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, stride=1),
nn.ReLU(),
Flatten(),
nn.Linear(64, 20),
nn.Tanh()
)
self.actor = nn.Sequential(
nn.Linear(20, 20),
nn.Tanh(),
nn.Linear(20, nA),
)
def ortho(m, gain):
if hasattr(m, 'weight'):
nn.init.orthogonal_(m.weight, gain=gain)
self.common.apply(lambda m: ortho(m, np.sqrt(2)))
self.actor.apply(lambda m: ortho(m, 0.01))
def forward(self, state):
x = self.common(state)
x = self.actor(x)
x = F.log_softmax(x, dim=1)
return x
class TimestepEnv(gym.RewardWrapper):
def __init__(self, env, utility):
super(TimestepEnv, self).__init__(env)
self.utility = utility
def reward(self, rew):
rew = self.utility(rew.astype(np.float32).reshape(1, -1)).reshape(-1)
return rew
class RewardArray(gym.RewardWrapper):
def reward(self, rew):
return np.array([rew], dtype=np.float32)
class OneOre(gym.RewardWrapper):
def __init__(self, *args, **kwargs):
super(OneOre, self).__init__(*args, **kwargs)
self.reward_space = gym.spaces.Box(low=self.reward_space.low[1:], high=self.reward_space.high[1:])
def reward(self, rew):
return rew[1:]
def utility_contract_2d(values):
# values = torch.from_numpy(values)
ores, fuel = values[:,0], values[:,1]
target = 0.7; contract_price = 5.; market_price = 7.; compensation = 2.
penalty = ores < target
sales = ores.clamp(max=target)*contract_price + (ores-target).clamp(min=0)*market_price + - compensation*penalty
# return (sales + fuel/20.).view(-1).numpy()
return (sales + fuel/20.).view(-1, 1)
if __name__ == '__main__':
from agents.moreinforce import MOReinforce
from policies.policy import Categorical
from memory.memory import EpisodeMemory
from gym.wrappers import TimeLimit
from wrappers.one_hot import OneHotEnv
from wrappers.weighted_sum import WeightedSum
from wrappers.terminal import TerminalEnv
from wrappers.atari import Rescale42x42, NormalizedEnv
from wrappers.minecart_pixel import PixelMinecart
from wrappers.history import History
import argparse
import os
import envs.minecart
parser = argparse.ArgumentParser(description='')
parser.add_argument('--lr', default=3e-4, type=float)
parser.add_argument('--gamma', default=1.00, type=float)
parser.add_argument('--clip-grad-norm', default=50, type=float)
parser.add_argument('--timesteps', default=20000000, type=int)
args = parser.parse_args()
print(args)
device='cpu'
gamma = args.gamma
clip_grad_norm = args.clip_grad_norm
env = gym.make('MinecartDeterministic-v0')
env = TimeLimit(env, 1000)
env = OneOre(env)
env = PixelMinecart(env)
env = Rescale42x42(env)
env = NormalizedEnv(env)
env = History(env, history=2)
# env = DiscretizeEnv(env)
# env = TerminalEnv(env , utility_contract_2d)
# env = TimestepEnv(env, utility)
# env = WeightedSum(env, np.array([0., 0.99, 0.01]))
nS = env.observation_space.shape
actor = Actor(nS, env.action_space.n).to(device)
logdir = f'runs/minecart_contract_pixel/head_20-20/history_2/moreinforce/gamma_{gamma}/lr_{args.lr}/clip_grad_norm_{clip_grad_norm}/'
logdir += datetime.now().strftime('%Y-%m-%d_%H-%M-%S_') + str(uuid.uuid4())[:4] + '/'
agent = MOReinforce(
env,
Categorical(),
EpisodeMemory(device=device),
actor,
gamma=gamma,
lr=args.lr,
logdir=logdir,
# scheduler='linear',
# scheduler_steps=args.timesteps//n_steps_update,
clip_grad_norm=clip_grad_norm,
utility=utility_contract_2d
)
agent.train(timesteps=args.timesteps) #, eval_freq=0.1)
# from log.plotter import Plotter
# Plotter(logdir)