-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain_ray.py
191 lines (171 loc) · 5.62 KB
/
main_ray.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
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import numpy as np
import pandas as pd
import os
from time import time
import pickle
import ray
from scipy.optimize import minimize
from scipy.special import softmax
def get_data(raw):
eps = int(raw.readline().strip())
data = []
for ep in range(eps):
ep_data = []
T = int(raw.readline().strip())
for i in range(T):
ep_data.append(list(map(float, raw.readline().strip().split(','))))
data.append(ep_data)
return data
def estimate(pi_e, D, n, gamma=0.95):
est = 0.0
print(f"Starting PDIS estimation for {n} samples")
for ep in D:
w_t = 1
gamma_t = 1
for t in range(len(ep)):
s_t, a_t, r_t, pi_b = ep[t]
s_t = int(s_t)
a_t = int(a_t)
w_t *= softmax(pi_e[s_t])[a_t] / pi_b
est += gamma_t * w_t * r_t / n
gamma_t *= gamma
print(f"Average estimate of return: {est}")
return est
@ray.remote
def estimate_ray(pi_e, D, n, gamma=0.95):
est = 0.0
print(f"Starting PDIS estimation for {n} samples")
for ep in D:
w_t = 1
gamma_t = 1
for t in range(len(ep)):
s_t, a_t, r_t, pi_b = ep[t]
s_t = int(s_t)
a_t = int(a_t)
w_t *= softmax(pi_e[s_t])[a_t] / pi_b
est += gamma_t * w_t * r_t / n
gamma_t *= gamma
print(f"Average estimate of return: {est}")
return est
@ray.remote
def estimate_ray_vec(pi_e, D, n, gamma=0.95):
est = 0.0
pi_e = softmax(pi_e, axis=1)
# print(f"Starting PDIS estimation for {n} samples")
for ep in D:
ep = np.array(ep, dtype=np.float)
weights = np.cumprod(
pi_e[ep[:, 0].astype(np.int), ep[:, 1].astype(np.int)] * gamma / ep[:,
3]) / gamma
est += weights.dot(ep[:, 2])
# print(f"Average estimate of return: {est/n}")
return est/n
def estimate_vec(pi_e, D, n, gamma=0.95):
est = 0.0
pi_e = softmax(pi_e, axis=1)
# print(f"Policy: ")
# print(pi_e)
# print(f"Starting PDIS estimation for {n} samples")
for ep in D:
ep = np.array(ep, dtype=np.float)
weights = np.cumprod(
pi_e[ep[:, 0].astype(np.int), ep[:, 1].astype(np.int)] * gamma / ep[:,
3]) / gamma
est += weights.dot(ep[:, 2])
return est/n
def pdis_estimate(pi_e, D, S, A, gamma=0.95, minimize=True, verbose=False):
if D is None:
raise ValueError("Data D is None")
n = len(D)
if verbose:
print(f"Running PDIS estimation for the entire candidate data of {len(D)} samples")
a = time()
pi_e = pi_e.reshape(S, A)
# est = 0.0
# R = []
n_work = 12
idx = 0
works = []
for i in range(n_work):
start = int(n * i / n_work)
end = int(n * (i + 1) / n_work)
works.append(estimate_ray_vec.remote(pi_e, D[start:end], n, gamma))
results = ray.get(works)
if verbose:
print(f"Estimation for one complete run done in {time() - a} seconds")
est = sum(results)
# for ep in D:
# w_t = 1
# gamma_t = 1
# for t in range(len(ep)):
# s_t, a_t, r_t, pi_b = ep[t]
# s_t = int(s_t)
# a_t = int(a_t)
# w_t *= softmax(pi_e[s_t])[a_t] / pi_b
# est += gamma_t * w_t * r_t / n
# gamma_t *= gamma
print(f"Average estimate of return: {est}")
return est * (-1 if minimize else 1)
# Press the green button in the gutter to run the script.
if __name__ == '__main__1':
# data_raw = open("sample.txt", 'r')
data_raw = open("data.csv", 'r')
data = get_data(data_raw)
print(len(data))
pickle.dump(data, open("data.p", 'wb'))
if __name__ == '__main__2':
print("Loading data")
a = time()
data = pickle.load(open("data.p", "rb"))
print(f"Loaded data in {time() - a} seconds")
n = len(data)
print(f"number of episodes: {n}")
test = int(0.5 * n)
h_te = data[-test:]
h_tr = data[:-test]
S = 18
A = 4
t_0 = np.random.randn(S * A)
print(f"Running minimization over {n - test} episodes")
a = time()
pi_s = minimize(pdis_estimate, t_0, args=(h_tr, S, A), method='Powell')
print(f"Result: {pi_s}")
print(f"time taken: {time() - a} seconds")
pickle.dump(pi_s, open("results/res.p", "w"))
if __name__ == '__main__':
ray.init()
print("Loading data")
a = time()
data = np.load("data_np.npy", allow_pickle=True)
print(f"Loaded data in {time() - a} seconds")
n = len(data)
print(f"number of episodes: {n}")
test = int(0.5 * n)
h_te = data[-test:]
h_tr = data[:-test]
S = 18
A = 4
t_0 = np.random.randn(S * A)
print(f"Running minimization over {n - test} episodes")
a = time()
pi_s = minimize(pdis_estimate, t_0, args=(h_tr, S, A), method='Powell')
print(f"Result: {pi_s}")
print(f"time taken: {time() - a} seconds")
pickle.dump(pi_s, open("results/res.p", "w"))
if __name__ == '__main__1':
ray.init()
print("Loading data")
a = time()
data = pickle.load(open("data.p", "rb"))
print(f"Loaded data in {time() - a} seconds")
n = len(data)
print(f"number of episodes: {n}")
test = int(0.5 * n)
S = 18
A = 4
t_0 = np.ones(S * A)
print(f"Estimate: {pdis_estimate(t_0, data, S, A)}")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/