forked from devsisters/neural-combinatorial-rl-tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 4
/
data_loader.py
243 lines (200 loc) · 8.67 KB
/
data_loader.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
# Most of the codes are from
# https://github.com/vshallc/PtrNets/blob/master/pointer/misc/tsp.py
import os
import re
import zipfile
import itertools
import threading
import numpy as np
from tqdm import trange, tqdm
from collections import namedtuple
import tensorflow as tf
from download import download_file_from_google_drive
GOOGLE_DRIVE_IDS = {
'tsp5_train.zip': '0B2fg8yPGn2TCSW1pNTJMXzFPYTg',
'tsp10_train.zip': '0B2fg8yPGn2TCbHowM0hfOTJCNkU',
'tsp5-20_train.zip': '0B2fg8yPGn2TCTWNxX21jTDBGeXc',
'tsp50_train.zip': '0B2fg8yPGn2TCaVQxSl9ab29QajA',
'tsp20_test.txt': '0B2fg8yPGn2TCdF9TUU5DZVNCNjQ',
'tsp40_test.txt': '0B2fg8yPGn2TCcjFrYk85SGFVNlU',
'tsp50_test.txt.zip': '0B2fg8yPGn2TCUVlCQmQtelpZTTQ',
}
TSP = namedtuple('TSP', ['x', 'y', 'name'])
def length(x, y):
return np.linalg.norm(np.asarray(x) - np.asarray(y))
# https://gist.github.com/mlalevic/6222750
def solve_tsp_dynamic(points):
#calc all lengths
all_distances = [[length(x,y) for y in points] for x in points]
#initial value - just distance from 0 to every other point + keep the track of edges
A = {(frozenset([0, idx+1]), idx+1): (dist, [0,idx+1]) for idx,dist in enumerate(all_distances[0][1:])}
cnt = len(points)
for m in range(2, cnt):
B = {}
for S in [frozenset(C) | {0} for C in itertools.combinations(range(1, cnt), m)]:
for j in S - {0}:
B[(S, j)] = min( [(A[(S-{j},k)][0] + all_distances[k][j], A[(S-{j},k)][1] + [j]) for k in S if k != 0 and k!=j]) #this will use 0th index of tuple for ordering, the same as if key=itemgetter(0) used
A = B
res = min([(A[d][0] + all_distances[0][d[1]], A[d][1]) for d in iter(A)])
return np.asarray(res[1]) + 1 # 0 for padding
def generate_one_example(n_nodes, rng):
nodes = rng.rand(n_nodes, 2).astype(np.float32)
solutions = solve_tsp_dynamic(nodes)
return nodes, solutions
def read_paper_dataset(paths, max_length):
x, y = [], []
for path in paths:
tf.logging.info("Read dataset {} which is used in the paper..".format(path))
length = max(re.findall('\d+', path))
with open(path) as f:
for l in tqdm(f):
inputs, outputs = l.split(' output ')
x.append(np.array(inputs.split(), dtype=np.float32).reshape([-1, 2]))
y.append(np.array(outputs.split(), dtype=np.int32)[:-1]) # skip the last one
return x, y
class TSPDataLoader(object):
def __init__(self, config, rng=None):
self.config = config
self.rng = rng
self.task = config.task.lower()
self.batch_size = config.batch_size
self.min_length = config.min_data_length
self.max_length = config.max_data_length
self.is_train = config.is_train
self.use_terminal_symbol = config.use_terminal_symbol
self.random_seed = config.random_seed
self.data_num = {}
self.data_num['train'] = config.train_num
self.data_num['test'] = config.test_num
self.data_dir = config.data_dir
self.task_name = "{}_({},{})".format(
self.task, self.min_length, self.max_length)
self.data = None
self.coord = None
self.input_ops, self.target_ops = None, None
self.queue_ops, self.enqueue_ops = None, None
self.x, self.y, self.seq_length, self.mask = None, None, None, None
paths = self.download_google_drive_file()
if len(paths) != 0:
self._maybe_generate_and_save(except_list=paths.keys())
for name, path in paths.items():
self.read_zip_and_update_data(path, name)
else:
self._maybe_generate_and_save()
self._create_input_queue()
def _create_input_queue(self, queue_capacity_factor=16):
self.input_ops, self.target_ops = {}, {}
self.queue_ops, self.enqueue_ops = {}, {}
self.x, self.y, self.seq_length, self.mask = {}, {}, {}, {}
for name in self.data_num.keys():
self.input_ops[name] = tf.placeholder(tf.float32, shape=[None, None])
self.target_ops[name] = tf.placeholder(tf.int32, shape=[None])
min_after_dequeue = 1000
capacity = min_after_dequeue + 3 * self.batch_size
self.queue_ops[name] = tf.RandomShuffleQueue(
capacity=capacity,
min_after_dequeue=min_after_dequeue,
dtypes=[tf.float32, tf.int32],
shapes=[[self.max_length, 2,], [self.max_length]],
seed=self.random_seed,
name="random_queue_{}".format(name))
self.enqueue_ops[name] = \
self.queue_ops[name].enqueue([self.input_ops[name], self.target_ops[name]])
inputs, labels = self.queue_ops[name].dequeue()
seq_length = tf.shape(inputs)[0]
if self.use_terminal_symbol:
mask = tf.ones([seq_length + 1], dtype=tf.float32) # terminal symbol
else:
mask = tf.ones([seq_length], dtype=tf.float32)
self.x[name], self.y[name], self.seq_length[name], self.mask[name] = \
tf.train.batch(
[inputs, labels, seq_length, mask],
batch_size=self.batch_size,
capacity=capacity,
dynamic_pad=True,
name="batch_and_pad")
def run_input_queue(self, sess):
threads = []
self.coord = tf.train.Coordinator()
for name in self.data_num.keys():
def load_and_enqueue(sess, name, input_ops, target_ops, enqueue_ops, coord):
idx = 0
while not coord.should_stop():
feed_dict = {
input_ops[name]: self.data[name].x[idx],
target_ops[name]: self.data[name].y[idx],
}
sess.run(self.enqueue_ops[name], feed_dict=feed_dict)
idx = idx+1 if idx+1 <= len(self.data[name].x) - 1 else 0
args = (sess, name, self.input_ops, self.target_ops, self.enqueue_ops, self.coord)
t = threading.Thread(target=load_and_enqueue, args=args)
t.start()
threads.append(t)
tf.logging.info("Thread start for [{}]".format(name))
def stop_input_queue(self):
self.coord.request_stop()
self.coord.join(threads)
def _maybe_generate_and_save(self, except_list=[]):
self.data = {}
for name, num in self.data_num.items():
if name in except_list:
tf.logging.info("Skip creating {} because of given except_list {}".format(name, except_list))
continue
path = self.get_path(name)
if not os.path.exists(path):
tf.logging.info("Creating {} for [{}]".format(path, self.task))
x = np.zeros([num, self.max_length, 2], dtype=np.float32)
y = np.zeros([num, self.max_length], dtype=np.int32)
for idx in trange(num, desc="Create {} data".format(name)):
n_nodes = self.rng.randint(self.min_length, self.max_length+ 1)
nodes, res = generate_one_example(n_nodes, self.rng)
x[idx,:len(nodes)] = nodes
y[idx,:len(res)] = res
np.savez(path, x=x, y=y)
self.data[name] = TSP(x=x, y=y, name=name)
else:
tf.logging.info("Skip creating {} for [{}]".format(path, self.task))
tmp = np.load(path)
self.data[name] = TSP(x=tmp['x'], y=tmp['y'], name=name)
def get_path(self, name):
return os.path.join(
self.data_dir, "{}_{}={}.npz".format(
self.task_name, name, self.data_num[name]))
def download_google_drive_file(self):
paths = {}
for mode in ['train', 'test']:
candidates = []
candidates.append(
'{}{}_{}'.format(self.task, self.max_length, mode))
candidates.append(
'{}{}-{}_{}'.format(self.task, self.min_length, self.max_length, mode))
for key in candidates:
print(key)
for search_key in GOOGLE_DRIVE_IDS.keys():
if search_key.startswith(key):
path = os.path.join(self.data_dir, search_key)
tf.logging.info("Download dataset of the paper to {}".format(path))
if not os.path.exists(path):
download_file_from_google_drive(GOOGLE_DRIVE_IDS[search_key], path)
if path.endswith('zip'):
with zipfile.ZipFile(path, 'r') as z:
z.extractall(self.data_dir)
paths[mode] = path
tf.logging.info("Can't found dataset from the paper!")
return paths
def read_zip_and_update_data(self, path, name):
if path.endswith('zip'):
filenames = zipfile.ZipFile(path).namelist()
paths = [os.path.join(self.data_dir, filename) for filename in filenames]
else:
paths = [path]
x_list, y_list = read_paper_dataset(paths, self.max_length)
x = np.zeros([len(x_list), self.max_length, 2], dtype=np.float32)
y = np.zeros([len(y_list), self.max_length], dtype=np.int32)
for idx, (nodes, res) in enumerate(tqdm(zip(x_list, y_list))):
x[idx,:len(nodes)] = nodes
y[idx,:len(res)] = res
if self.data is None:
self.data = {}
tf.logging.info("Update [{}] data with {} used in the paper".format(name, path))
self.data[name] = TSP(x=x, y=y, name=name)