Repository: keon/pointer-networks Branch: master Commit: bca17beee594 Files: 9 Total size: 11.9 KB Directory structure: gitextract_f0mounp3/ ├── .gitignore ├── LICENSE ├── PointerLSTM.py ├── README.md ├── model_weight_100.hdf5 ├── requirement.txt ├── run.py ├── sort_data.py └── tsp_data.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Keon Kim Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: PointerLSTM.py ================================================ import keras.backend as K from keras.activations import tanh, softmax from keras.engine import InputSpec from keras.layers import LSTM import keras class Attention(keras.layers.Layer): """ Attention layer """ def __init__(self, hidden_dimensions, name='attention'): super(Attention, self).__init__(name=name, trainable=True) self.W1 = keras.layers.Dense(hidden_dimensions, use_bias=False) self.W2 = keras.layers.Dense(hidden_dimensions, use_bias=False) self.V = keras.layers.Dense(1, use_bias=False) def call(self, encoder_outputs, dec_output, mask=None): w1_e = self.W1(encoder_outputs) w2_d = self.W2(dec_output) tanh_output = tanh(w1_e + w2_d) v_dot_tanh = self.V(tanh_output) if mask is not None: v_dot_tanh += (mask * -1e9) attention_weights = softmax(v_dot_tanh, axis=1) att_shape = K.shape(attention_weights) return K.reshape(attention_weights, (att_shape[0], att_shape[1])) class Decoder(keras.layers.Layer): """ Decoder class for PointerLayer """ def __init__(self, hidden_dimensions): super(Decoder, self).__init__() self.lstm = keras.layers.LSTM( hidden_dimensions, return_sequences=False, return_state=True) def call(self, x, hidden_states): dec_output, state_h, state_c = self.lstm( x, initial_state=hidden_states) return dec_output, [state_h, state_c] def get_initial_state(self, inputs): return self.lstm.get_initial_state(inputs) def process_inputs(self, x_input, initial_states, constants): return self.lstm._process_inputs(x_input, initial_states, constants) class PointerLSTM(keras.layers.Layer): """ PointerLSTM """ def __init__(self, hidden_dimensions, name='pointer', **kwargs): super(PointerLSTM, self).__init__( hidden_dimensions, name=name, **kwargs) self.hidden_dimensions = hidden_dimensions self.attention = Attention(hidden_dimensions) self.decoder = Decoder(hidden_dimensions) def build(self, input_shape): super(PointerLSTM, self).build(input_shape) self.input_spec = [InputSpec(shape=input_shape)] def call(self, x, training=None, mask=None, states=None): """ :param Tensor x: Should be the output of the decoder :param Tensor states: last state of the decoder :param Tensor mask: The mask to apply :return: Pointers probabilities """ input_shape = self.input_spec[0].shape en_seq = x x_input = x[:, input_shape[1] - 1, :] x_input = K.repeat(x_input, input_shape[1]) if states: initial_states = states else: initial_states = self.decoder.get_initial_state(x_input) constants = [] preprocessed_input, _, constants = self.decoder.process_inputs( x_input, initial_states, constants) constants.append(en_seq) last_output, outputs, states = K.rnn(self.step, preprocessed_input, initial_states, go_backwards=self.decoder.lstm.go_backwards, constants=constants, input_length=input_shape[1]) return outputs def step(self, x_input, states): x_input = K.expand_dims(x_input,1) input_shape = self.input_spec[0].shape en_seq = states[-1] _, [h, c] = self.decoder(x_input, states[:-1]) dec_seq = K.repeat(h, input_shape[1]) probs = self.attention(dec_seq, en_seq) return probs, [h, c] def get_output_shape_for(self, input_shape): # output shape is not affected by the attention component return (input_shape[0], input_shape[1], input_shape[1]) def compute_output_shape(self, input_shape): return (input_shape[0], input_shape[1], input_shape[1]) ================================================ FILE: README.md ================================================ ## Code upgrade of [Pointer Networks](http://arxiv.org/pdf/1511.06391v4.pdf) to run on keras>=2.4.3 and tensorflow>=2.2.0 The original author code is at https://github.com/keon/pointer-networks.git. ================================================ FILE: requirement.txt ================================================ keras==2.4.3 tensorflow==2.2.0 ================================================ FILE: run.py ================================================ from keras.models import Model from keras.layers import LSTM, Input from keras.callbacks import LearningRateScheduler from keras.utils.np_utils import to_categorical from pointer import PointerLSTM import pickle import tsp_data as tsp import numpy as np import keras def scheduler(epoch): if epoch < nb_epochs/4: return learning_rate elif epoch < nb_epochs/2: return learning_rate*0.5 return learning_rate*0.1 print("preparing dataset...") t = tsp.Tsp() X, Y = t.next_batch(10000) x_test, y_test = t.next_batch(1000) YY = [] for y in Y: YY.append(to_categorical(y)) YY = np.asarray(YY) hidden_size = 128 seq_len = 10 nb_epochs = 10000 learning_rate = 0.1 print("building model...") main_input = Input(shape=(seq_len, 2), name='main_input') encoder,state_h, state_c = LSTM(hidden_size,return_sequences = True, name="encoder",return_state=True)(main_input) decoder = PointerLSTM(hidden_size, name="decoder")(encoder,states=[state_h, state_c]) model = Model(main_input, decoder) print(model.summary()) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(X, YY, epochs=nb_epochs, batch_size=64,) print(model.predict(x_test)) print('evaluate : ',model.evaluate(x_test,to_categorical(y_test))) print("------") print(to_categorical(y_test)) model.save_weights('model_weight_100.hdf5') ================================================ FILE: sort_data.py ================================================ from __future__ import absolute_import, division, print_function import numpy as np class DataGenerator(object): def next_batch(self, batch_size, N, train_mode=True): """Return the next `batch_size` examples from this data set.""" # A sequence of random numbers from [0, 1] encoder_batch = [] # Sorted sequence that we feed to encoder # In inference we feed an unordered sequence again decoder_batch = [] # Ordered sequence where one hot vector encodes # position in the input array target_batch = [] for _ in range(batch_size): encoder_batch.append(np.zeros([N, 1])) for _ in range(batch_size): decoder_batch.append(np.zeros([N, 1])) target_batch.append(np.zeros([N, N])) encoder_batch = np.asarray(encoder_batch) decoder_batch = np.asarray(decoder_batch) target_batch = np.asarray(target_batch) for b in range(batch_size): shuffle = np.random.permutation(N) sequence = np.sort(np.random.random(N)) shuffled_sequence = sequence[shuffle] for i in range(N): encoder_batch[b][i] = shuffled_sequence[i] if train_mode: decoder_batch[b][i] = sequence[i] else: decoder_batch[b][i] = shuffled_sequence[i] target_batch[b, i][shuffle[i]] = 1.0 # Points to the stop symbol # target_batch[b, N][0] = 1.0 return encoder_batch, decoder_batch, target_batch if __name__ == "__main__": seq_len = 3 batch_size = 3 dataset = DataGenerator() enc_input, dec_input, targets = dataset.next_batch(batch_size, seq_len) print("batch_size", batch_size, "seq_len", seq_len) print("-------------encoder input-------------") print(enc_input.shape) print(enc_input) print("-------------decoder input-------------") print(dec_input.shape) print(dec_input) print("------------- targets -------------") print(targets.shape) print(targets) ================================================ FILE: tsp_data.py ================================================ import math import numpy as np import random import itertools class Tsp: def next_batch(self, batch_size=1): X, Y = [], [] for b in range(batch_size): print("preparing dataset... %s/%s" % (b, batch_size)) points = self.generate_data() solved = self.solve_tsp_dynamic(points) X.append(points), Y.append(solved) return np.asarray(X), np.asarray(Y) def length(self, x, y): return (math.sqrt((x[0]-y[0])**2 + (x[1]-y[1])**2)) def solve_tsp_dynamic(self, points): # calc all lengths all_distances = [[self.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]) A = B res = min([(A[d][0] + all_distances[0][d[1]], A[d][1]) for d in iter(A)]) return res[1] def generate_data(self, N=10): radius = 1 rangeX = (0, 10) rangeY = (0, 10) qty = N deltas = set() for x in range(-radius, radius+1): for y in range(-radius, radius+1): if x*x + y*y <= radius*radius: deltas.add((x, y)) randPoints = [] excluded = set() i = 0 while i < qty: x = random.randrange(*rangeX) y = random.randrange(*rangeY) if (x, y) in excluded: continue randPoints.append((x, y)) i += 1 excluded.update((x+dx, y+dy) for (dx, dy) in deltas) return randPoints if __name__ == "__main__": p = Tsp() X, Y = p.next_batch(1) print(X) print(Y)