-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary_example.py
300 lines (230 loc) · 9.56 KB
/
binary_example.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from cmath import log
import numpy as np
import pickle
import os
import argparse
from Model.Linear_Feature_Model import Linear_Class, Feature_Dataset
class BinaryEnv():
def __init__(self, obs_eps, transit_eps, ep_len=100):
self.obs_eps = obs_eps
self.transit_eps = transit_eps
self.ep_len = ep_len
def reset(self):
self.counter = 0
if np.random.rand() < 0.5:
self.state = 0.0
else:
self.state = 1.0
self.obs = self.create_obs()
return self.obs
# transition model P(S'=S) = 1-self.transit_eps
def step(self, action):
self.counter += 1
reward = self.state * action
if np.random.rand() > self.transit_eps:
self.state = self.state
else:
self.state = 1.0 - self.state
done = self.counter >= self.ep_len
self.obs = self.create_obs()
return self.obs, reward, done, {}
# emission model P(O=S) = 1-self.obs_eps
def create_obs(self):
if np.random.rand() > self.obs_eps:
obs = self.state
else:
obs = 1.0 - self.state
return obs
def get_obs(self):
return self.obs
def get_current_state(self):
return self.state
class Policy():
def __init__(self, epsilon):
self.epsilon = epsilon
# take action pi(A=O/S) w.p. 1-self.epsilon
def get_action(self, obs):
if np.random.rand() > self.epsilon:
return obs
else:
return 1.0 - obs
def get_prob_with_act(self, obs, act):
return 1.0 * (obs == act) * (1 - 2 * self.epsilon) + self.epsilon
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--obs-eps', type = float, default = 0.2, help='size of obs noise')
parser.add_argument('--trans-eps', type = float, default = 0.2, help='size of obs noise')
parser.add_argument('--ep-len', type = int, default = 100, help='size of obs noise')
parser.add_argument('--ep-num', type = int, default = 2000, help='size of obs noise')
parser.add_argument('--gamma', type = float, default = 0.95, help='size of obs noise')
parser.add_argument('--target-eps', type = float, default = 0.5, help='size of obs noise')
parser.add_argument('--behavior-eps', type = float, default = 0.2, help='size of obs noise')
args = parser.parse_args()
return args
def generate_data(env, ep_num, policy, gamma=0.95):
sample_size = ep_num * env.ep_len
init_states_list = []
last_states_list = []
llast_states_list = [] # the state before last state
states_list = []
next_states_list = []
init_obs_list = []
init_last_obs_list = []
last_obs_list = []
llast_obs_list = [] # the obs before last obs
obs_list = []
next_obs_list = []
init_acts_list = []
act_list = []
last_act_list = []
next_acts_list = []
rew_list = []
done_list = []
is_init_list = []
step_num_list = []
ep_num = 0
total_return = 0.0
while True:
ep_num += 1
step_num = 0
obs = env.reset()
init_obs_list.append(obs)
obs_list.append(obs)
last_obs_list.append(np.random.randint(2))
llast_obs_list.append(np.random.randint(2))
init_last_obs_list.append(last_obs_list[-1])
state = env.get_current_state()
init_states_list.append(state)
states_list.append(state)
last_states_list.append(np.random.randint(2))
llast_states_list.append(np.random.randint(2))
is_init_list.append(True)
done = False
is_init_step = True
factor = 1.0
while True:
act = policy.get_action(state) # here the behavior policy is based on state (instead of noisy observation)
next_obs, rew, done, _ = env.step(act)
next_state = env.get_current_state()
if is_init_step:
is_init_step = False
init_acts_list.append(act)
last_act_list.append(np.zeros_like(act))
else:
next_acts_list.append(act)
assert len(next_acts_list) == len(act_list), '{}!={}'.format(len(next_acts_list), len(act_list))
act_list.append(act)
rew_list.append(rew)
next_obs_list.append(next_obs)
next_states_list.append(next_state)
done_list.append(done)
step_num_list.append(step_num)
step_num += 1
factor *= gamma
total_return += factor * rew
if done:
act = policy.get_action(state)
next_acts_list.append(act)
break
last_act_list.append(act)
last_obs = obs
last_state = state
obs = next_obs
state = next_state
last_obs_list.append(last_obs)
llast_obs_list.append(last_obs_list[-1])
last_states_list.append(last_state)
llast_states_list.append(last_states_list[-1])
obs_list.append(obs)
states_list.append(state)
is_init_list.append(False)
if ep_num % 100 == 0:
print('\n\n')
print('Average Discounted Return ', total_return / ep_num)
print('Average Return ', np.sum(rew_list) / ep_num)
print('Average Ep_Len ', len(rew_list) / ep_num)
print('Sample Size till Now ', len(obs_list))
if len(obs_list) >= sample_size:
break
return {
'init_states': np.array(init_states_list)[:, np.newaxis],
'states': np.array(states_list[:sample_size])[:, np.newaxis],
'last_states': np.array(last_states_list[:sample_size])[:, np.newaxis],
'llast_states': np.array(llast_states_list[:sample_size])[:, np.newaxis],
'next_states': np.array(next_states_list[:sample_size])[:, np.newaxis],
'init_last_obs': np.array(init_last_obs_list)[:, np.newaxis],
'init_obs': np.array(init_obs_list)[:, np.newaxis],
'last_obs': np.array(last_obs_list[:sample_size])[:, np.newaxis],
'llast_obs': np.array(llast_obs_list[:sample_size])[:, np.newaxis],
'obs': np.array(obs_list[:sample_size])[:, np.newaxis],
'next_obs': np.array(next_obs_list[:sample_size])[:, np.newaxis],
'init_acts': np.array(init_acts_list)[:, np.newaxis],
'acts': np.array(act_list[:sample_size])[:, np.newaxis],
'last_acts': np.array(last_act_list[:sample_size])[:, np.newaxis],
'next_acts': np.array(next_acts_list[:sample_size])[:, np.newaxis],
'rews': np.array(rew_list[:sample_size])[:, np.newaxis],
'done': np.array(done_list[:sample_size])[:, np.newaxis],
'is_init': np.array(is_init_list[:sample_size])[:, np.newaxis],
'step_num': np.array(step_num_list[:sample_size])[:, np.newaxis],
}
def eval_target_policy(env, policy, gamma, ep_num):
ep_rets = []
for i in range(ep_num):
done = False
ep_rets.append(0.0)
obs = env.reset()
factor = 1.0
while not done:
act = policy.get_action(obs)
obs, rew, done, _ = env.step(act)
ep_rets[-1] += rew * factor
factor *= gamma
return np.mean(ep_rets)
def main():
args = get_parser()
obs_dim = 1
act_dim = 2
feature_dim = 4
ep_num = args.ep_num
args.obs_eps = args.behavior_eps
env = BinaryEnv(args.obs_eps, args.trans_eps, args.ep_len)
log_dir = './Dataset/Binary/Tr{}_Obs{}_TargetPi{}_BehPi{}_EpNum{}.pickle'.format(args.trans_eps, args.obs_eps, args.target_eps, args.behavior_eps, ep_num)
target_policy = Policy(epsilon=args.target_eps)
behavior_policy = Policy(epsilon=args.behavior_eps)
if not os.path.exists(log_dir):
if not os.path.exists('./Dataset/Binary'):
os.makedirs('./Dataset/Binary')
dataset = generate_data(env, ep_num=ep_num, policy=behavior_policy, gamma=args.gamma)
with open(log_dir, 'wb') as f:
pickle.dump(dataset, f)
else:
with open(log_dir, 'rb') as f:
dataset = pickle.load(f)
# compute \pi_e(A|O) for all (O, A) in the dataset in advance
dataset['acts_probs'] = target_policy.get_prob_with_act(dataset['obs'], dataset['acts'])
dataset['last_acts_probs'] = target_policy.get_prob_with_act(dataset['last_obs'], dataset['last_acts'])
dataset['init_acts_probs'] = [None] * act_dim
dataset['next_acts_probs'] = [None] * act_dim
for act in range(act_dim):
dataset['init_acts_probs'][act] = target_policy.get_prob_with_act(dataset['init_obs'], act * np.ones(shape=[dataset['init_obs'].shape[0], 1]))
dataset['next_acts_probs'][act] = target_policy.get_prob_with_act(dataset['next_obs'], act * np.ones(shape=[dataset['next_obs'].shape[0], 1]))
print(dataset['next_acts_probs'][act].shape)
# compute the true value:
true_val = eval_target_policy(env, target_policy, gamma=args.gamma, ep_num=2000)
print('true_val ', true_val)
# learn
feature_dataset = Feature_Dataset(dataset, num_acts=2, feature_dim=feature_dim,
alpha=None, feature_type='one-hot',)
linear_class = Linear_Class(
obs_dim=obs_dim,
obs_ft_dim=feature_dim,
num_acts=act_dim,
gamma=args.gamma,
dataset=dataset,
feature_dataset=feature_dataset,
)
estimator, baseline_estimator = linear_class.learn()
print('estimator ', estimator)
print('baseline_estimator ', baseline_estimator)
if __name__ == '__main__':
main()