├── results
└── .gitkeep
├── tests
└── .gitkeep
├── environment.yml
├── utils
├── logger.py
├── word_encodings.py
├── image_manipulation.py
└── convnet14_cifar10_mnist_joint.py
├── layers
├── extracting.py
├── encoding.py
├── reading.py
└── writing.py
├── README.md
├── models
└── convnet14.py
├── image_association_task_lstm.py
├── data
├── babi_data.py
└── image_association_data.py
├── image_association_task.py
├── babi_task_single.py
└── LICENSE
/results/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/environment.yml:
--------------------------------------------------------------------------------
1 | name: H-Mem
2 |
3 | channels:
4 | - defaults
5 |
6 | dependencies:
7 | - python=3.7
8 | - tensorflow-gpu=2.1
9 |
--------------------------------------------------------------------------------
/utils/logger.py:
--------------------------------------------------------------------------------
1 | """CSV logger"""
2 |
3 | import csv
4 |
5 | from tensorflow.keras.callbacks import Callback
6 |
7 |
8 | class MyCSVLogger(Callback):
9 |
10 | def __init__(self, filename):
11 | self.filename = filename
12 |
13 | def on_test_begin(self, logs=None):
14 | self.csv_file = open(self.filename, "a")
15 |
16 | class CustomDialect(csv.excel):
17 | delimiter = ','
18 |
19 | self.fieldnames = ['error [%]']
20 | self.writer = csv.DictWriter(self.csv_file, self.fieldnames, dialect=CustomDialect)
21 | self.writer.writeheader()
22 |
23 | def on_test_batch_begin(self, batch, logs=None):
24 | pass
25 |
26 | def on_test_batch_end(self, batch, logs=None):
27 | logs = {'error [%]': 100.0 - logs['accuracy'] * 100.0}
28 | self.writer.writerow(logs)
29 | self.csv_file.flush()
30 |
31 | def on_test_end(self, logs=None):
32 | self.csv_file.close()
33 | self.writer = None
34 |
--------------------------------------------------------------------------------
/utils/word_encodings.py:
--------------------------------------------------------------------------------
1 | """Word encodings."""
2 |
3 | import numpy as np
4 |
5 |
6 | def position_encoding(sentence_size, embedding_size):
7 | """Position Encoding.
8 |
9 | Encodes the position of words within the sentence (implementation based on
10 | https://arxiv.org/pdf/1503.08895.pdf [1]).
11 |
12 | Arguments:
13 | sentence_size: int, the size of the sentence (number of words).
14 | embedding_size: int, the size of the word embedding.
15 |
16 | Returns:
17 | A encoding matrix represented by a Numpy array with shape `[sentence_size, embedding_size]`.
18 |
19 | """
20 | encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
21 | ls = sentence_size + 1
22 | le = embedding_size + 1
23 | for i in range(1, le):
24 | for j in range(1, ls):
25 | encoding[i - 1, j - 1] = (i - (embedding_size + 1) / 2) * (j - (sentence_size + 1) / 2)
26 | encoding = 1 + 4 * encoding / embedding_size / sentence_size
27 |
28 | # Make position encoding of time words identity to avoid modifying them.
29 | encoding[:, -1] = 1.0
30 |
31 | return np.transpose(encoding)
32 |
--------------------------------------------------------------------------------
/utils/image_manipulation.py:
--------------------------------------------------------------------------------
1 | """Image manipulations."""
2 |
3 | import numpy as np
4 |
5 |
6 | def merge(a, b):
7 | """Merge two images to one.
8 |
9 | The images are stacked column wise (left `a` and right `b`).
10 |
11 | Arguments:
12 | a: iterable, The images.
13 | b: iterable, The images.
14 |
15 | Returns:
16 | A Numpy array containing the merged images.
17 |
18 | """
19 | rows_a, cols_a, channels_a = a.shape
20 | rows_b, cols_b, channels_b = b.shape
21 |
22 | rows = max(rows_a, rows_b)
23 | cols = cols_a + cols_b
24 | channels = max(channels_a, channels_b)
25 |
26 | c = np.zeros(shape=(rows, cols, channels))
27 | c[:rows_a, :cols_a] = a
28 | c[:rows_b, cols_a:] = b
29 |
30 | return c
31 |
32 |
33 | def pad(x, pad_width):
34 | """Pad images in `x` with zeros.
35 |
36 | Arguments:
37 | x: iterable, The images to pad.
38 | pad_width: sequence, array_like, int, Number of values padded to the edges of each axis. ((before_1,
39 | after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before
40 | and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.
41 |
42 | Returns:
43 | A Numpy array containing the padded images.
44 |
45 | """
46 | y = []
47 | for item in x:
48 | y.append(np.pad(item, pad_width=pad_width))
49 |
50 | y = np.array(y)
51 |
52 | return y
53 |
54 |
55 | def expand_channels(x, num_channels=3):
56 | y = []
57 | for i, item in enumerate(x):
58 | rows, cols = item.shape
59 | c = np.zeros(shape=(rows, cols, num_channels))
60 | c[:, :, :] = item[:, :, np.newaxis]
61 | y.append(c)
62 |
63 | y = np.array(y)
64 |
65 | return y
66 |
--------------------------------------------------------------------------------
/layers/extracting.py:
--------------------------------------------------------------------------------
1 | """Extracting layer that computes key and value."""
2 |
3 | import tensorflow as tf
4 | from tensorflow.keras.layers import Dense, Layer
5 |
6 |
7 | class Extracting(Layer):
8 |
9 | def __init__(self,
10 | units,
11 | use_bias,
12 | activation,
13 | kernel_initializer,
14 | kernel_regularizer,
15 | **kwargs):
16 | super().__init__(**kwargs)
17 |
18 | self.units = units
19 | self.use_bias = use_bias
20 | self.activation = activation
21 | self.kernel_initializer = kernel_initializer
22 | self.kernel_regularizer = kernel_regularizer
23 |
24 | self.dense1 = Dense(units=self.units,
25 | use_bias=self.use_bias,
26 | activation=self.activation,
27 | kernel_initializer=self.kernel_initializer,
28 | kernel_regularizer=self.kernel_regularizer)
29 | self.dense2 = Dense(units=self.units,
30 | use_bias=self.use_bias,
31 | activation=self.activation,
32 | kernel_initializer=self.kernel_initializer,
33 | kernel_regularizer=self.kernel_regularizer)
34 |
35 | def build(self, input_shape):
36 | super().build(input_shape)
37 |
38 | def call(self, inputs, mask=None):
39 | if mask is not None:
40 | mask = tf.cast(mask, dtype=self.dtype)
41 | mask = tf.expand_dims(mask, axis=-1)
42 | else:
43 | mask = 1.0
44 |
45 | k = mask * self.dense1(inputs)
46 | v = mask * self.dense2(inputs)
47 |
48 | return tf.concat([k, v], axis=-1)
49 |
50 | def compute_mask(self, inputs, mask=None):
51 | return mask
52 |
--------------------------------------------------------------------------------
/utils/convnet14_cifar10_mnist_joint.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Model for classifying CIFAR10 and MNIST jointly."""
3 |
4 | import numpy as np
5 | import tensorflow as tf
6 |
7 | from models.convnet14 import ConvNet14
8 | from utils.image_manipulation import expand_channels, pad
9 |
10 | EPOCHS = 100
11 | BATCH_SIZE = 128
12 | PAD_WIDTH = ((2, 2), (2, 2), (0, 0))
13 |
14 | # Load the data.
15 | cifar10 = tf.keras.datasets.cifar10
16 | (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10) = cifar10.load_data()
17 |
18 | mnist = tf.keras.datasets.mnist
19 | (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = mnist.load_data()
20 | x_train_mnist = expand_channels(x_train_mnist, num_channels=3)
21 | x_test_mnist = expand_channels(x_test_mnist, num_channels=3)
22 | x_train_mnist = pad(x_train_mnist, PAD_WIDTH)
23 | x_test_mnist = pad(x_test_mnist, PAD_WIDTH)
24 |
25 | # Concatenate MNISt and CIFAR10
26 | x_train = np.concatenate((x_train_cifar10, x_train_mnist))
27 | y_train = np.concatenate((y_train_cifar10.flatten(), y_train_mnist+10))
28 | x_test = np.concatenate((x_test_cifar10, x_test_mnist))
29 | y_test = np.concatenate((y_test_cifar10.flatten(), y_test_mnist+10))
30 |
31 | idc = np.random.RandomState(seed=42).permutation(x_train.shape[0])
32 | x_train = x_train[idc]
33 | y_train = y_train[idc]
34 | idc = np.random.RandomState(seed=42).permutation(x_test.shape[0])
35 | x_test = x_test[idc]
36 | y_test = y_test[idc]
37 |
38 | input_shape = x_train.shape[1:]
39 |
40 | # Normalize pixel values to be between 0 and 1
41 | x_train, x_test = x_train / 255.0, x_test / 255.0
42 |
43 |
44 | def lr_scheduler(epoch):
45 | if epoch < 50:
46 | return 0.001
47 | else:
48 | return 0.001 * tf.math.exp(0.1 * (50 - epoch))
49 |
50 |
51 | # Build the model.
52 | model = ConvNet14(output_size=20)
53 |
54 | # Compile the model.
55 | model.compile(optimizer=tf.keras.optimizers.Adam(),
56 | loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
57 | metrics=['accuracy'])
58 |
59 | # Train and evaluate the model
60 | callback = tf.keras.callbacks.LearningRateScheduler(lr_scheduler)
61 | model.fit(x=x_train, y=y_train, epochs=EPOCHS, batch_size=BATCH_SIZE, validation_split=0.1,
62 | callbacks=[callback])
63 |
64 | model.evaluate(x=x_test, y=y_test, verbose=2)
65 |
66 | # Save the models weights.
67 | model.save_weights('saved_models/weights/ConvNet14-CIFAR10-MNIST/ConvNet14-CIFAR10-MNIST', save_format='tf')
68 |
69 | model.summary()
70 |
--------------------------------------------------------------------------------
/layers/encoding.py:
--------------------------------------------------------------------------------
1 | """Sentence encoding."""
2 |
3 | import tensorflow as tf
4 | from tensorflow.keras.constraints import Constraint
5 | from tensorflow.keras.layers import Layer
6 |
7 | from utils.word_encodings import position_encoding
8 |
9 |
10 | class Encoding(Layer):
11 |
12 | def __init__(self,
13 | encodings_type,
14 | encodings_constraint='mask_time_word',
15 | **kwargs):
16 | super().__init__(**kwargs)
17 |
18 | self.encodings_type = encodings_type.lower()
19 | self.encodings_constraint = encodings_constraint.lower()
20 |
21 | if self.encodings_type not in ('identity_encoding', 'position_encoding', 'learned_encoding'):
22 | raise ValueError('Could not interpret encodings type:', self.encodings_type)
23 |
24 | if self.encodings_constraint not in ('none', 'mask_time_word'):
25 | raise ValueError('Could not interpret encodings constraint:', self.encodings_type)
26 |
27 | self.constraint = self.MaskTimeWord() if self.encodings_constraint == 'mask_time_word' else None
28 |
29 | def build(self, input_shape):
30 | if self.encodings_type.lower() == 'identity_encoding':
31 | self.encoding = tf.ones((input_shape[-2], input_shape[-1]))
32 | if self.encodings_type.lower() == 'position_encoding':
33 | self.encoding = position_encoding(input_shape[-2], input_shape[-1])
34 | if self.encodings_type.lower() == 'learned_encoding':
35 | self.encoding = self.add_weight(shape=(input_shape[-2], input_shape[-1]), trainable=True,
36 | initializer=tf.initializers.Ones(),
37 | constraint=self.constraint,
38 | dtype=self.dtype, name='encoding')
39 |
40 | super().build(input_shape)
41 |
42 | def call(self, inputs, mask=None):
43 | mask = tf.cast(mask, dtype=self.dtype)
44 | mask = tf.expand_dims(mask, axis=-1)
45 |
46 | return tf.reduce_sum(mask * self.encoding * inputs, axis=-2)
47 |
48 | def compute_mask(self, inputs, mask=None):
49 | if mask is None:
50 | return None
51 |
52 | return tf.reduce_any(mask, axis=-1)
53 |
54 | def compute_output_shape(self, input_shape):
55 | return (input_shape[0], input_shape[-1])
56 |
57 | class MaskTimeWord(Constraint):
58 | """Make encoding of time words identity to avoid modifying them."""
59 |
60 | def __init__(self,
61 | **kwargs):
62 | super().__init__(**kwargs)
63 |
64 | def __call__(self, w):
65 | indices = [[w.shape[0]-1]]
66 | updates = tf.ones((1, w.shape[1]))
67 | new_w = tf.tensor_scatter_nd_update(w, indices, updates)
68 |
69 | return new_w
70 |
--------------------------------------------------------------------------------
/layers/reading.py:
--------------------------------------------------------------------------------
1 | """Reading layers that read from memory."""
2 |
3 | import tensorflow as tf
4 | import tensorflow.keras.backend as K
5 | from tensorflow.keras.layers import Dense, Layer
6 |
7 |
8 | class Reading(Layer):
9 |
10 | def __init__(self,
11 | units,
12 | use_bias,
13 | activation,
14 | kernel_initializer,
15 | kernel_regularizer,
16 | **kwargs):
17 | super().__init__(**kwargs)
18 |
19 | self.units = units
20 | self.use_bias = use_bias
21 | self.activation = activation
22 | self.kernel_initializer = kernel_initializer
23 | self.kernel_regularizer = kernel_regularizer
24 |
25 | self.dense = Dense(units=self.units,
26 | use_bias=self.use_bias,
27 | activation=self.activation,
28 | kernel_initializer=self.kernel_initializer,
29 | kernel_regularizer=self.kernel_regularizer)
30 |
31 | def build(self, input_shape):
32 | super().build(input_shape)
33 |
34 | def call(self, inputs, constants):
35 | memory_matrix = constants[0]
36 |
37 | k = self.dense(inputs)
38 |
39 | v = K.batch_dot(k, memory_matrix)
40 |
41 | return v
42 |
43 | def compute_mask(self, inputs, mask=None):
44 | return mask
45 |
46 |
47 | class ReadingCell(Layer):
48 |
49 | def __init__(self,
50 | units,
51 | use_bias,
52 | activation,
53 | kernel_initializer,
54 | kernel_regularizer,
55 | **kwargs):
56 | super().__init__(**kwargs)
57 |
58 | self.units = units
59 | self.use_bias = use_bias
60 | self.activation = activation
61 | self.kernel_initializer = kernel_initializer
62 | self.kernel_regularizer = kernel_regularizer
63 |
64 | self.dense = Dense(units=self.units,
65 | use_bias=self.use_bias,
66 | activation=self.activation,
67 | kernel_initializer=self.kernel_initializer,
68 | kernel_regularizer=self.kernel_regularizer)
69 |
70 | @property
71 | def state_size(self):
72 | return self.units
73 |
74 | def build(self, input_shape):
75 | super().build(input_shape)
76 |
77 | def call(self, inputs, states, constants):
78 | v = states[0]
79 | memory_matrix = constants[0]
80 |
81 | k = self.dense(tf.concat([inputs, v], axis=1))
82 |
83 | v = K.batch_dot(k, memory_matrix)
84 |
85 | return v, v
86 |
87 | def compute_mask(self, inputs, mask=None):
88 | return mask
89 |
90 | def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
91 | return tf.zeros((batch_size, self.units))
92 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://paperswithcode.com/sota/question-answering-on-babi?p=h-mem-harnessing-synaptic-plasticity-with)
2 |
3 | # H-Mem: Harnessing synaptic plasticity with Hebbian Memory Networks
4 | This is the code used in the paper "[H-Mem: Harnessing synaptic plasticity with Hebbian Memory
5 | Networks](https://www.biorxiv.org/content/10.1101/2020.07.01.180372v2)" for training H-Mem on a single-shot
6 | image association task and on the bAbI question-answering tasks.
7 |
8 | 
9 |
10 | ## Setup
11 | You need [TensorFlow](https://www.tensorflow.org/) to run this code. We tested it on TensorFlow version 2.1.
12 | Additional dependencies are listed in [environment.yml](environment.yml). If you use
13 | [Conda](https://docs.conda.io/en/latest/), run
14 |
15 | ```bash
16 | conda env create --file=environment.yml
17 | ```
18 |
19 | to install the required packages and their dependencies.
20 |
21 | ## Usage
22 |
23 | ### Single-shot associations with H-Mem
24 | To start training on the single-shot image association task, run
25 |
26 | ```bash
27 | python image_association_task.py
28 | ```
29 |
30 | Set the command line argument `--delay` to set the between-image delay (in the paper we used delays ranging from 0 to 40). Run the following command
31 |
32 | ```bash
33 | python image_association_task_lstm.py
34 | ```
35 |
36 | to start training the LSTM model on this task (the default value for the between-image delay is 0; you can change it with the command line argument `--delay`).
37 |
38 | ### Question answering with H-Mem
39 | Run the following command
40 |
41 | ```bash
42 | python babi_task_single.py
43 | ```
44 |
45 | to start training on bAbI task 1 in the 10k training examples setting. Set the command line argument `--task_id` to train on other tasks. You can try different model configurations by changing various command line arguments. For example,
46 |
47 | ```bash
48 | python babi_task_single.py --task_id=4 --memory_size=20 --epochs=50 --logging=1
49 | ```
50 |
51 | will train the model with an associative memory of size 20 on task 4 for 50 epochs. The results will be stored in `results/`.
52 |
53 | ### Memory-dependent memorization
54 | In our extended model we have added an 'read-before-write' step. This model will be used if the
55 | command line argument `--read_before_write` is set to `1`. Run the following command
56 |
57 | ```bash
58 | python babi_task_single.py --task_id=16 --epochs=250 --read_before_write=1
59 | ```
60 |
61 | to start training on bAbI task 16 in the 10k training examples setting (note that we trained the extended
62 | model for 250 epochs---instead of 100 epochs). You should get an accuracy of about 100% on this task. Compare
63 | to the original model, which does not solve task 16, by running the following command
64 |
65 | ```bash
66 | python babi_task_single.py --task_id=16 --epochs=250
67 | ```
68 |
69 | ## References
70 | * Limbacher, T., & Legenstein, R. (2020). H-Mem: Harnessing synaptic plasticity with Hebbian Memory Networks. Advances in Neural Information Processing Systems, 33.
71 | https://www.biorxiv.org/content/10.1101/2020.07.01.180372v2
72 |
--------------------------------------------------------------------------------
/models/convnet14.py:
--------------------------------------------------------------------------------
1 | """Convolutional network with 14 weight layers."""
2 |
3 | import tensorflow as tf
4 | from tensorflow.keras.layers import BatchNormalization, Conv2D, Dense, Dropout, Flatten, MaxPool2D
5 | from tensorflow.keras.models import Sequential
6 |
7 | BatchNormalization._USE_V2_BEHAVIOR = False
8 |
9 |
10 | class ConvNet14(Sequential):
11 |
12 | def __init__(self,
13 | output_size=10,
14 | include_top=True,
15 | **kwargs):
16 | super().__init__(**kwargs)
17 |
18 | self.output_size = output_size
19 | self.include_top = include_top
20 |
21 | weight_decay = 1e-3
22 | self.kernel_regularizer = tf.keras.regularizers.l2(weight_decay)
23 |
24 | self.add(Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_uniform',
25 | kernel_regularizer=self.kernel_regularizer, padding='same'))
26 | self.add(BatchNormalization())
27 | self.add(Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_uniform',
28 | kernel_regularizer=self.kernel_regularizer, padding='same'))
29 | self.add(BatchNormalization())
30 | self.add(MaxPool2D((2, 2)))
31 | self.add(Dropout(0.1))
32 |
33 | self.add(Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_uniform',
34 | kernel_regularizer=self.kernel_regularizer, padding='same'))
35 | self.add(BatchNormalization())
36 | self.add(Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_uniform',
37 | kernel_regularizer=self.kernel_regularizer, padding='same'))
38 | self.add(BatchNormalization())
39 | self.add(MaxPool2D((2, 2)))
40 | self.add(Dropout(0.1))
41 |
42 | self.add(Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_uniform',
43 | kernel_regularizer=self.kernel_regularizer, padding='same'))
44 | self.add(BatchNormalization())
45 | self.add(Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_uniform',
46 | kernel_regularizer=self.kernel_regularizer, padding='same'))
47 | self.add(BatchNormalization())
48 | self.add(MaxPool2D((2, 2)))
49 | self.add(Dropout(0.2))
50 |
51 | self.add(Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_uniform',
52 | kernel_regularizer=self.kernel_regularizer, padding='same'))
53 | self.add(BatchNormalization())
54 | self.add(Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_uniform',
55 | kernel_regularizer=self.kernel_regularizer, padding='same'))
56 | self.add(BatchNormalization())
57 | self.add(MaxPool2D((2, 2)))
58 | self.add(Dropout(0.3))
59 |
60 | self.add(Conv2D(512, (3, 3), activation='elu', kernel_initializer='he_uniform',
61 | kernel_regularizer=self.kernel_regularizer, padding='same'))
62 | self.add(BatchNormalization())
63 | self.add(Conv2D(512, (3, 3), activation='elu', kernel_initializer='he_uniform',
64 | kernel_regularizer=self.kernel_regularizer, padding='same'))
65 | self.add(BatchNormalization())
66 | self.add(MaxPool2D((2, 2)))
67 | self.add(Dropout(0.3))
68 | if self.include_top:
69 | self.add(Flatten())
70 | self.add(Dense(512, activation='elu', kernel_initializer='he_uniform'))
71 | self.add(BatchNormalization())
72 | self.add(Dense(256, activation='elu', kernel_initializer='he_uniform'))
73 | self.add(BatchNormalization())
74 | self.add(Dense(128, activation='elu', kernel_initializer='he_uniform'))
75 | self.add(BatchNormalization())
76 | self.add(Dropout(0.4))
77 | self.add(Dense(self.output_size))
78 |
--------------------------------------------------------------------------------
/layers/writing.py:
--------------------------------------------------------------------------------
1 | """Writing layers that write to memory."""
2 |
3 | import tensorflow as tf
4 | from tensorflow.keras.layers import Layer
5 | import tensorflow.keras.backend as K
6 |
7 |
8 | class Writing(Layer):
9 |
10 | def __init__(self,
11 | units,
12 | gamma,
13 | learn_gamma=False,
14 | **kwargs):
15 | super().__init__(**kwargs)
16 |
17 | self.units = units
18 | self._gamma = gamma
19 | self.learn_gamma = learn_gamma
20 |
21 | def build(self, input_shape):
22 | self.gamma = self.add_weight(shape=(1,), trainable=self.learn_gamma,
23 | initializer=tf.keras.initializers.Constant(self._gamma),
24 | dtype=self.dtype, name='gamma')
25 |
26 | super().build(input_shape)
27 |
28 | def call(self, inputs, mask=None):
29 | k, v = tf.split(inputs, 2, axis=-1)
30 |
31 | k = tf.expand_dims(k, 2)
32 | v = tf.expand_dims(v, 1)
33 |
34 | hebb = self.gamma * k * v
35 |
36 | memory_matrix = hebb
37 |
38 | return memory_matrix
39 |
40 | def compute_mask(self, inputs, mask=None):
41 | return mask
42 |
43 |
44 | class WritingCell(Layer):
45 |
46 | def __init__(self,
47 | units,
48 | gamma_pos,
49 | gamma_neg,
50 | w_assoc_max,
51 | use_bias=False,
52 | read_before_write=False,
53 | kernel_initializer=None,
54 | kernel_regularizer=None,
55 | learn_gamma_pos=False,
56 | learn_gamma_neg=False,
57 | **kwargs):
58 | super().__init__(**kwargs)
59 |
60 | self.units = units
61 | self.w_max = w_assoc_max
62 | self._gamma_pos = gamma_pos
63 | self._gamma_neg = gamma_neg
64 | self.use_bias = use_bias
65 | self.read_before_write = read_before_write
66 | self.kernel_initializer = kernel_initializer
67 | self.kernel_regularizer = kernel_regularizer
68 | self.learn_gamma_pos = learn_gamma_pos
69 | self.learn_gamma_neg = learn_gamma_neg
70 |
71 | if self.read_before_write:
72 | self.dense = tf.keras.layers.Dense(units=self.units,
73 | use_bias=self.use_bias,
74 | kernel_initializer=self.kernel_initializer,
75 | kernel_regularizer=self.kernel_regularizer)
76 |
77 | self.ln1 = tf.keras.layers.LayerNormalization()
78 | self.ln2 = tf.keras.layers.LayerNormalization()
79 |
80 | @property
81 | def state_size(self):
82 | return tf.TensorShape((self.units, self.units))
83 |
84 | def build(self, input_shape):
85 | self.gamma_pos = self.add_weight(shape=(1,), trainable=self.learn_gamma_pos,
86 | initializer=tf.keras.initializers.Constant(self._gamma_pos),
87 | dtype=self.dtype, name='gamma_pos')
88 | self.gamma_neg = self.add_weight(shape=(1,), trainable=self.learn_gamma_neg,
89 | initializer=tf.keras.initializers.Constant(self._gamma_neg),
90 | dtype=self.dtype, name='gamma_neg')
91 |
92 | super().build(input_shape)
93 |
94 | def call(self, inputs, states, mask=None):
95 | memory_matrix = states[0]
96 | k, v = tf.split(inputs, 2, axis=-1)
97 |
98 | if self.read_before_write:
99 | k = self.ln1(k)
100 | v_h = K.batch_dot(k, memory_matrix)
101 |
102 | v = self.dense(tf.concat([v, v_h], axis=1))
103 | v = self.ln2(v)
104 |
105 | k = tf.expand_dims(k, 2)
106 | v = tf.expand_dims(v, 1)
107 |
108 | hebb = self.gamma_pos * (self.w_max - memory_matrix) * k * v - self.gamma_neg * memory_matrix * k**2
109 |
110 | memory_matrix = hebb + memory_matrix
111 |
112 | return memory_matrix, memory_matrix
113 |
114 | def compute_mask(self, inputs, mask=None):
115 | return mask
116 |
117 | def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
118 | return tf.zeros((batch_size, self.units, self.units))
119 |
--------------------------------------------------------------------------------
/image_association_task_lstm.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Runs an LSTM on a single-shot image association task."""
3 |
4 | import argparse
5 |
6 | import numpy as np
7 | import tensorflow as tf
8 | from tensorflow.keras.layers import TimeDistributed
9 |
10 | from data.image_association_data import load_data
11 | from models.convnet14 import ConvNet14 as ConvNet
12 |
13 | strategy = tf.distribute.MirroredStrategy()
14 |
15 | parser = argparse.ArgumentParser()
16 | parser.add_argument('--delay', type=int, default=0)
17 | parser.add_argument('--timesteps', type=int, default=3)
18 | parser.add_argument('--delay_padding', type=str, default='random', help='`zeros` or `random`')
19 |
20 | parser.add_argument('--epochs', type=int, default=100)
21 | parser.add_argument('--batch_size_per_replica', type=int, default=32)
22 | parser.add_argument('--max_grad_norm', type=float, default=10.0)
23 | parser.add_argument('--learning_rate', type=float, default=0.001)
24 | parser.add_argument('--validation_split', type=float, default=0.1)
25 |
26 | parser.add_argument('--retrain_convnet', type=int, default=0)
27 | parser.add_argument('--use_pretrained_convnet', type=int, default=0)
28 |
29 | parser.add_argument('--hidden_size', type=int, default=200)
30 | parser.add_argument('--dense_size', type=int, default=128)
31 | parser.add_argument('--gamma_pos', type=float, default=0.01)
32 | parser.add_argument('--gamma_neg', type=float, default=0.01)
33 | parser.add_argument('--w_assoc_max', type=float, default=1.0)
34 |
35 | parser.add_argument('--verbose', type=int, default=1)
36 | args = parser.parse_args()
37 |
38 | batch_size = args.batch_size_per_replica * strategy.num_replicas_in_sync
39 |
40 | # Load the data.
41 | (x_train, y_train), (x_test, y_test) = load_data(timesteps=args.timesteps, merge=True,
42 | data_dir='data/image_association_task/')
43 |
44 | num_train = y_train.size - int(args.validation_split * y_train.size)
45 | num_val = int(args.validation_split * y_train.size)
46 | num_test = y_test.size
47 |
48 | x_val = [x_train[0][-num_val:], x_train[1][-num_val:]]
49 | y_val = y_train[-num_val:]
50 |
51 | x_train = [x_train[0][:num_train], x_train[1][:num_train]]
52 | y_train = y_train[:num_train]
53 |
54 | timesteps_with_delay = args.timesteps * (args.delay + 1)
55 |
56 | input_shape = (timesteps_with_delay+1, ) + x_train[0].shape[2:]
57 |
58 |
59 | # Create the datasets.
60 | def dataset_generator(x, y, seed):
61 | rng = np.random.RandomState(seed=seed)
62 | for a, b, y in zip(x[0], x[1], y):
63 | size = (timesteps_with_delay, ) + a.shape[1:-1] + (1,)
64 | if args.delay_padding == 'random':
65 | aa = rng.uniform(size=size).repeat(a.shape[-1], axis=3)
66 | elif args.delay_padding == 'zeros':
67 | aa = np.zeros(shape=size).repeat(a.shape[-1], axis=3)
68 | aa[::args.delay+1, :] = a
69 | inputs = np.concatenate([aa, b[np.newaxis, :, :, :]])
70 |
71 | yield {'inputs': inputs}, y
72 |
73 |
74 | output_types = ({'inputs': 'float32'}, 'uint8')
75 | output_shapes = ({'inputs': [None, None, None, None]}, [])
76 | train_dataset = tf.data.Dataset.from_generator(generator=lambda: dataset_generator(x_train, y_train, 42),
77 | output_types=output_types,
78 | output_shapes=output_shapes)
79 | val_dataset = tf.data.Dataset.from_generator(generator=lambda: dataset_generator(x_val, y_val, 43),
80 | output_types=output_types,
81 | output_shapes=output_shapes)
82 | test_dataset = tf.data.Dataset.from_generator(generator=lambda: dataset_generator(x_test, y_test, 44),
83 | output_types=output_types,
84 | output_shapes=output_shapes)
85 |
86 | train_dataset = train_dataset.cache().repeat(args.epochs * batch_size).shuffle(10000).batch(batch_size)
87 | val_dataset = val_dataset.batch(batch_size)
88 | test_dataset = test_dataset.batch(batch_size)
89 |
90 | # Load pretrained model.
91 | conv_net = ConvNet(include_top=False)
92 | if args.use_pretrained_convnet:
93 | conv_net.load_weights('saved_models/weights/ConvNet14-CIFAR10-MNIST/ConvNet14-CIFAR10-MNIST')
94 | conv_net.trainable = bool(args.retrain_convnet)
95 |
96 | with strategy.scope():
97 | # Build the model.
98 | inputs = tf.keras.layers.Input(input_shape, name='inputs')
99 |
100 | features = TimeDistributed(conv_net, name='conv')(inputs)
101 | features = TimeDistributed(tf.keras.layers.Flatten(), name='flatten')(features)
102 | features = TimeDistributed(tf.keras.layers.Dense(args.dense_size,
103 | use_bias=False,
104 | activation='relu',
105 | kernel_initializer='he_uniform',
106 | kernel_regularizer=tf.keras.regularizers.l2(1e-3)),
107 | name='dense')(features)
108 | features = TimeDistributed(tf.keras.layers.BatchNormalization(), name='batch_norm')(features)
109 | features = TimeDistributed(tf.keras.layers.Dropout(0.3), name='dropout')(features)
110 |
111 | states = tf.keras.layers.LSTM(args.hidden_size, name='states')(features)
112 |
113 | outputs = tf.keras.layers.Dense(10, kernel_initializer='he_uniform', use_bias=False)(states)
114 |
115 | model = tf.keras.Model(inputs=inputs, outputs=outputs)
116 |
117 | # Compile the model.
118 | optimizer_kwargs = {'clipnorm': args.max_grad_norm} if args.max_grad_norm else {}
119 | model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=args.learning_rate, **optimizer_kwargs),
120 | loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
121 | metrics=['accuracy'])
122 |
123 | model.summary()
124 |
125 |
126 | # Train and evaluate.
127 | def lr_scheduler(epoch):
128 | if epoch < 50:
129 | return 0.001
130 | else:
131 | return 0.001 * tf.math.exp(0.1 * (50 - epoch))
132 |
133 |
134 | callback = tf.keras.callbacks.LearningRateScheduler(lr_scheduler)
135 | model.fit(train_dataset,
136 | epochs=args.epochs,
137 | steps_per_epoch=np.ceil(num_train/batch_size),
138 | validation_data=val_dataset if num_val > 0 else None,
139 | validation_steps=np.ceil(num_val/batch_size),
140 | callbacks=[callback],
141 | verbose=args.verbose)
142 |
143 | model.evaluate(test_dataset, steps=np.ceil(num_test/batch_size), verbose=2)
144 |
--------------------------------------------------------------------------------
/data/babi_data.py:
--------------------------------------------------------------------------------
1 | """Utilities for downloading and parsing bAbI task data.
2 |
3 | Modified from https://github.com/domluna/memn2n/blob/master/data_utils.py.
4 |
5 | """
6 |
7 | import os
8 | import re
9 | import shutil
10 | import urllib.request
11 |
12 | import numpy as np
13 |
14 | tasks = {
15 | 1: 'single_supporting_fact',
16 | 2: 'two_supporting_facts',
17 | 3: 'three_supporting_facts',
18 | 4: 'two_arg_relations',
19 | 5: 'three_arg_relations',
20 | 6: 'yes_no_questions',
21 | 7: 'counting',
22 | 8: 'lists_sets',
23 | 9: 'simple_negation',
24 | 10: 'indefinite_knowledge',
25 | 11: 'basic_coreference',
26 | 12: 'conjunction',
27 | 13: 'compound_coreference',
28 | 14: 'time_reasoning',
29 | 15: 'basic_deduction',
30 | 16: 'basic_induction',
31 | 17: 'positional_reasoning',
32 | 18: 'size_reasoning',
33 | 19: 'path_finding',
34 | 20: 'agents_motivations'
35 | }
36 |
37 |
38 | def download(extract=True):
39 | """Downloads the data set.
40 |
41 | Arguments:
42 | extract: boolean, whether to extract the downloaded archive (default=`True`).
43 |
44 | Returns:
45 | data_dir: string, the data directory.
46 |
47 | """
48 | url = 'https://s3.amazonaws.com/text-datasets/'
49 | file_name = 'babi_tasks_1-20_v1-2.tar.gz'
50 | data_dir = 'data/'
51 | file_path = data_dir + file_name
52 |
53 | if not os.path.exists(file_path):
54 | print('Downloading ' + url + file_name + '...')
55 | print('-')
56 | with urllib.request.urlopen(url + file_name) as response, open(file_path, 'wb') as out_file:
57 | shutil.copyfileobj(response, out_file)
58 | shutil.unpack_archive(file_path, data_dir)
59 | shutil.move(data_dir + 'tasks_1-20_v1-2', data_dir + 'babi_tasks_1-20_v1-2')
60 |
61 | return data_dir + 'babi_tasks_1-20_v1-2'
62 |
63 |
64 | def load_task(data_dir, task_id, training_set_size='1k', only_supporting=False):
65 | """Loads the nth task. There are 20 tasks in total.
66 |
67 | Arguments:
68 | data_dir: string, the data directory.
69 | task_id: int, the ID of the task (valid values are in `range(1, 21)`).
70 | training_set_size: string, the size of the training set to load (`1k` or `10k`, default=`1k`).
71 | only_supporting: boolean, if `True` only supporting facts are loaded (default=`False`).
72 |
73 | Returns:
74 | A Python tuple containing the training and testing data for the task.
75 |
76 | """
77 | assert task_id > 0 and task_id < 21
78 |
79 | data_dir = data_dir + '/en/' if training_set_size == '1k' else data_dir + '/en-10k/'
80 | files = os.listdir(data_dir)
81 | files = [os.path.join(data_dir, f) for f in files]
82 | s = 'qa{}_'.format(task_id)
83 | train_file = [f for f in files if s in f and 'train' in f][0]
84 | test_file = [f for f in files if s in f and 'test' in f][0]
85 | train_data = _get_stories(train_file, only_supporting)
86 | test_data = _get_stories(test_file, only_supporting)
87 |
88 | return train_data, test_data
89 |
90 |
91 | def vectorize_data(data, word_idx, max_num_sentences, sentence_size, query_size):
92 | """Vectorize stories, queries and answers.
93 |
94 | If a sentence length < `sentence_size`, the sentence will be padded with `0`s. If a story length <
95 | `max_num_sentences`, the story will be padded with empty sentences. Empty sentences are 1-D arrays of
96 | length `sentence_size` filled with `0`s. The answer array is returned as a one-hot encoding.
97 |
98 | Arguments:
99 | data: iterable, containing stories, queries and answers.
100 | word_idx: dict, mapping words to unique integers.
101 | max_num_sentences: int, the maximum number of sentences to extract.
102 | sentence_size: int, the maximum number of words in a sentence.
103 | query_size: int, the maximum number of words in a query.
104 |
105 | Returns:
106 | A Python tuple containing vectorized stories, queries, and answers.
107 |
108 | """
109 | S = []
110 | Q = []
111 | A = []
112 | for story, query, answer in data:
113 | if len(story) > max_num_sentences:
114 | continue
115 |
116 | ss = []
117 | for i, sentence in enumerate(story, 1):
118 | # Pad to sentence_size, i.e., add nil words, and add story.
119 | ls = max(0, sentence_size - len(sentence))
120 | ss.append([word_idx[w] for w in sentence] + [0] * ls)
121 |
122 | # Make the last word of each sentence the time 'word' which corresponds to vector of lookup table.
123 | for i in range(len(ss)):
124 | ss[i][-1] = len(word_idx) - max_num_sentences - i + len(ss)
125 |
126 | # Pad stories to max_num_sentences (i.e., add empty stories).
127 | ls = max(0, max_num_sentences - len(ss))
128 | for _ in range(ls):
129 | ss.append([0] * sentence_size)
130 |
131 | # Pad queries to query_size (i.e., add nil words).
132 | lq = max(0, query_size - len(query))
133 | q = [word_idx[w] for w in query] + [0] * lq
134 |
135 | y = np.zeros(len(word_idx) + 1) # 0 is reserved for nil word.
136 | for a in answer:
137 | y[word_idx[a]] = 1
138 |
139 | S.append(ss)
140 | Q.append(q)
141 | A.append(y)
142 |
143 | return np.array(S), np.array(Q), np.array(A)
144 |
145 |
146 | def _get_stories(f, only_supporting=False):
147 | """Given a file name, read the file, retrieve the stories, and then convert the sentences into a single
148 | story.
149 |
150 | If only_supporting is true, only the sentences that support the answer are kept.
151 |
152 | Arguments:
153 | f: string, the file name.
154 | only_supporting: boolean, if `True` only supporting facts are loaded (default=`False`).
155 |
156 | Returns:
157 | A list of Python tuples containing stories, queries, and answers.
158 |
159 | """
160 | with open(f) as f:
161 | data = _parse_stories(f.readlines(), only_supporting=only_supporting)
162 |
163 | return data
164 |
165 |
166 | def _parse_stories(lines, only_supporting=False):
167 | """Parse stories provided in the bAbI tasks format.
168 |
169 | If only_supporting is true, only the sentences that support the answer are kept.
170 |
171 | Arguments:
172 | lines: iterable, containing the sentences of a full story (story, query, and answer).
173 | only_supporting: boolean, if `True` only supporting facts are loaded (default=`False`).
174 |
175 | Returns:
176 | A Python list containing the parsed stories.
177 |
178 | """
179 | data = []
180 | story = []
181 | for line in lines:
182 | line = str.lower(line)
183 | nid, line = line.split(' ', 1)
184 | nid = int(nid)
185 | if nid == 1:
186 | story = []
187 | if '\t' in line: # Question
188 | q, a, supporting = line.split('\t')
189 | q = _tokenize(q)
190 | a = [a] # Answer is one vocab word even ie it's actually multiple words.
191 | substory = None
192 |
193 | # Remove question marks
194 | if q[-1] == '?':
195 | q = q[:-1]
196 |
197 | if only_supporting:
198 | # Only select the related substory.
199 | supporting = map(int, supporting.split())
200 | substory = [story[i - 1] for i in supporting]
201 | else:
202 | # Provide all the substories.
203 | substory = [x for x in story if x]
204 |
205 | data.append((substory, q, a))
206 | story.append('')
207 | else: # Regular sentence
208 | sent = _tokenize(line)
209 | # Remove periods
210 | if sent[-1] == '.':
211 | sent = sent[:-1]
212 | story.append(sent)
213 |
214 | return data
215 |
216 |
217 | def _tokenize(sent):
218 | """Return the tokens of a sentence including punctuation.
219 |
220 | Arguments:
221 | sent: iterable, containing the sentence.
222 |
223 | Returns:
224 | A Python list containing the tokens in the sentence.
225 |
226 | Examples:
227 |
228 | ```python
229 | tokenize('Bob dropped the apple. Where is the apple?')
230 |
231 | ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple', '?']
232 | ```
233 |
234 | """
235 | return [x.strip() for x in re.split(r'(\W+)+?', sent) if x.strip()]
236 |
--------------------------------------------------------------------------------
/image_association_task.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Runs H-Mem on a single-shot image association task."""
3 |
4 | import argparse
5 | import random
6 |
7 | import numpy as np
8 | import tensorflow as tf
9 | from tensorflow.keras.layers import TimeDistributed
10 | from tensorflow.keras import Model
11 |
12 | from data.image_association_data import load_data
13 | from layers.extracting import Extracting
14 | from layers.reading import Reading
15 | from layers.writing import WritingCell
16 | from models.convnet14 import ConvNet14 as ConvNet
17 |
18 | strategy = tf.distribute.MirroredStrategy()
19 |
20 | parser = argparse.ArgumentParser()
21 | parser.add_argument('--delay', type=int, default=0)
22 | parser.add_argument('--timesteps', type=int, default=3)
23 | parser.add_argument('--delay_padding', type=str, default='random', help='`zeros` or `random`')
24 |
25 | parser.add_argument('--epochs', type=int, default=100)
26 | parser.add_argument('--learning_rate', type=float, default=0.001)
27 | parser.add_argument('--batch_size_per_replica', type=int, default=32)
28 | parser.add_argument('--random_state', type=int, default=None)
29 | parser.add_argument('--max_grad_norm', type=float, default=10.0)
30 | parser.add_argument('--validation_split', type=float, default=0.1)
31 |
32 | parser.add_argument('--retrain_convnet', type=int, default=0)
33 | parser.add_argument('--use_pretrained_convnet', type=int, default=0)
34 |
35 | parser.add_argument('--memory_size', type=int, default=200)
36 | parser.add_argument('--dense_size', type=int, default=128)
37 | parser.add_argument('--gamma_pos', type=float, default=0.01)
38 | parser.add_argument('--gamma_neg', type=float, default=0.01)
39 | parser.add_argument('--w_assoc_max', type=float, default=1.0)
40 |
41 | parser.add_argument('--verbose', type=int, default=1)
42 | args = parser.parse_args()
43 |
44 | batch_size = args.batch_size_per_replica * strategy.num_replicas_in_sync
45 |
46 | # Set random seeds.
47 | np.random.seed(args.random_state)
48 | random.seed(args.random_state)
49 | tf.random.set_seed(args.random_state)
50 |
51 | # Load the data.
52 | (x_train, y_train), (x_test, y_test) = load_data(timesteps=args.timesteps, merge=True,
53 | data_dir='data/image_association_task/')
54 |
55 | num_train = y_train.size - int(args.validation_split * y_train.size)
56 | num_val = int(args.validation_split * y_train.size)
57 | num_test = y_test.size
58 |
59 | x_val = [x_train[0][-num_val:], x_train[1][-num_val:]]
60 | y_val = y_train[-num_val:]
61 |
62 | x_train = [x_train[0][:num_train], x_train[1][:num_train]]
63 | y_train = y_train[:num_train]
64 |
65 | timesteps_with_delay = args.timesteps * (args.delay + 1)
66 |
67 | input_a_shape = (timesteps_with_delay, ) + x_train[0].shape[2:]
68 | input_b_shape = x_train[1].shape[1:]
69 |
70 |
71 | # Create the datasets.
72 | def dataset_generator(x, y, seed):
73 | rng = np.random.RandomState(seed=seed)
74 | for a, b, y in zip(x[0], x[1], y):
75 | size = (timesteps_with_delay, ) + a.shape[1:-1] + (1,)
76 | if args.delay_padding == 'random':
77 | aa = rng.uniform(size=size).repeat(a.shape[-1], axis=3)
78 | elif args.delay_padding == 'zeros':
79 | aa = np.zeros(shape=size).repeat(a.shape[-1], axis=3)
80 | aa[::args.delay+1, :] = a
81 |
82 | yield {'input_a': aa, 'input_b': b}, y
83 |
84 |
85 | output_types = ({'input_a': 'float32', 'input_b': 'float32'}, 'uint8')
86 | output_shapes = ({'input_a': [None, None, None, None], 'input_b': [None, None, None]}, [])
87 | train_dataset = tf.data.Dataset.from_generator(generator=lambda: dataset_generator(x_train, y_train, 42),
88 | output_types=output_types,
89 | output_shapes=output_shapes)
90 | val_dataset = tf.data.Dataset.from_generator(generator=lambda: dataset_generator(x_val, y_val, 43),
91 | output_types=output_types,
92 | output_shapes=output_shapes)
93 | test_dataset = tf.data.Dataset.from_generator(generator=lambda: dataset_generator(x_test, y_test, 44),
94 | output_types=output_types,
95 | output_shapes=output_shapes)
96 |
97 | train_dataset = train_dataset.cache().repeat(args.epochs * batch_size).shuffle(10000).batch(batch_size)
98 | val_dataset = val_dataset.batch(batch_size)
99 | test_dataset = test_dataset.batch(batch_size)
100 |
101 | # Load pretrained model.
102 | conv_net = ConvNet(include_top=False, name='conv_b')
103 | if args.use_pretrained_convnet:
104 | conv_net.load_weights('saved_models/weights/ConvNet14-CIFAR10-MNIST/ConvNet14-CIFAR10-MNIST')
105 | conv_net.trainable = bool(args.retrain_convnet)
106 |
107 | with strategy.scope():
108 | # Build the model.
109 | input_a = tf.keras.layers.Input(input_a_shape, name='input_a')
110 | input_b = tf.keras.layers.Input(input_b_shape, name='input_b')
111 |
112 | features_a = TimeDistributed(conv_net, name='conv_a')(input_a)
113 | features_a = TimeDistributed(tf.keras.layers.Flatten(), name='flatten_a')(features_a)
114 | features_a = TimeDistributed(tf.keras.layers.Dense(args.dense_size,
115 | use_bias=False,
116 | activation='relu',
117 | kernel_initializer='he_uniform',
118 | kernel_regularizer=tf.keras.regularizers.l2(1e-3)),
119 | name='dense_a')(features_a)
120 | features_a = TimeDistributed(tf.keras.layers.BatchNormalization(), name='batch_norm_a')(features_a)
121 | features_a = TimeDistributed(tf.keras.layers.Dropout(0.3), name='dropout_a')(features_a)
122 |
123 | features_b = conv_net(input_b)
124 | features_b = tf.keras.layers.Flatten(name='flatten_b')(features_b)
125 | features_b = tf.keras.layers.Dense(args.dense_size,
126 | use_bias=False,
127 | activation='relu',
128 | kernel_initializer='he_uniform',
129 | kernel_regularizer=tf.keras.regularizers.l2(1e-3),
130 | name='dense_b')(features_b)
131 | features_b = tf.keras.layers.BatchNormalization(name='batch_norm_b')(features_b)
132 | features_b = tf.keras.layers.Dropout(0.3, name='dropout_b')(features_b)
133 |
134 | entities = Extracting(units=args.memory_size,
135 | use_bias=False,
136 | activation='relu',
137 | kernel_initializer='he_uniform',
138 | kernel_regularizer=tf.keras.regularizers.l2(1e-3),
139 | name='entity_extracting')(features_a)
140 |
141 | memory_matrix = tf.keras.layers.RNN(WritingCell(units=args.memory_size,
142 | gamma_pos=args.gamma_pos,
143 | gamma_neg=args.gamma_neg,
144 | w_assoc_max=args.w_assoc_max,
145 | learn_gamma_pos=False,
146 | learn_gamma_neg=False),
147 | name='entity_writing')(entities)
148 |
149 | queried_value = Reading(units=args.memory_size,
150 | use_bias=False,
151 | activation='relu',
152 | kernel_initializer='he_uniform',
153 | kernel_regularizer=tf.keras.regularizers.l2(1e-3),
154 | name='entity_reading')(features_b, constants=[memory_matrix])
155 |
156 | outputs = tf.keras.layers.Dense(10,
157 | use_bias=False,
158 | kernel_initializer='he_uniform',
159 | name='output')(queried_value)
160 |
161 | model = Model(inputs=[input_a, input_b], outputs=outputs)
162 |
163 | # Compile the model.
164 | optimizer_kwargs = {'clipnorm': args.max_grad_norm} if args.max_grad_norm else {}
165 | model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=args.learning_rate, **optimizer_kwargs),
166 | loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
167 | metrics=['accuracy'])
168 |
169 | model.summary()
170 |
171 |
172 | # Train and evaluate.
173 | def lr_scheduler(epoch):
174 | if epoch < 50:
175 | return 0.001
176 | else:
177 | return 0.001 * tf.math.exp(0.1 * (50 - epoch))
178 |
179 |
180 | callback = tf.keras.callbacks.LearningRateScheduler(lr_scheduler)
181 | model.fit(train_dataset,
182 | epochs=args.epochs,
183 | steps_per_epoch=np.ceil(num_train/batch_size),
184 | validation_data=val_dataset if num_val > 0 else None,
185 | validation_steps=np.ceil(num_val/batch_size),
186 | callbacks=[callback],
187 | verbose=args.verbose)
188 |
189 | model.evaluate(test_dataset, steps=np.ceil(num_test/batch_size), verbose=2)
190 |
--------------------------------------------------------------------------------
/data/image_association_data.py:
--------------------------------------------------------------------------------
1 | """Creates the data for the image association tasks."""
2 |
3 | import os
4 | import pathlib
5 |
6 | import numpy as np
7 | import tensorflow as tf
8 |
9 | from utils import image_manipulation
10 |
11 |
12 | def load_data(timesteps, pad_equal=False, merge=False, data_dir='data', seed=42):
13 | pad_equal = True if merge else pad_equal
14 |
15 | if not os.path.exists(data_dir):
16 | os.makedirs(data_dir)
17 |
18 | suffix = '_{0}{1}.npy'.format(timesteps, '_merged' if merge else '')
19 |
20 | x_train_files = []
21 | x_test_files = []
22 | if merge:
23 | for i in ['_a', '_b']:
24 | x_train_files.append(pathlib.Path(data_dir, 'x_train' + i + suffix))
25 | x_test_files.append(pathlib.Path(data_dir, 'x_test' + i + suffix))
26 | else:
27 | for i in ['_a', '_b', '_c']:
28 | x_train_files.append(pathlib.Path(data_dir, 'x_train' + i + suffix))
29 | x_test_files.append(pathlib.Path(data_dir, 'x_test' + i + suffix))
30 |
31 | y_train_file = pathlib.Path(data_dir, 'y_train' + suffix)
32 | y_test_file = pathlib.Path(data_dir, 'y_test' + suffix)
33 |
34 | cifar10_train, cifar10_test = _get_cifar10_dataset()
35 | mnist_train, mnist_test = _get_mnist_dataset(num_channels=1)
36 |
37 | if not all([f.is_file() for f in x_train_files]) or not y_train_file.is_file():
38 | x_train, y_train = _combine_data(cifar10_train, mnist_train, pad_equal)
39 | x_train, y_train = _create_dataset(x_train, y_train, timesteps, merge, seed)
40 |
41 | for i in range(len(x_train_files)):
42 | np.save(x_train_files[i], x_train[i])
43 | np.save(y_train_file, y_train)
44 |
45 | x_train = []
46 | for i in range(len(x_train_files)):
47 | x_train.append(np.load(x_train_files[i], mmap_mode=None)[:12500])
48 | y_train = np.load(y_train_file, mmap_mode=None)[:12500]
49 |
50 | if not all([f.is_file() for f in x_test_files]) or not y_test_file.is_file():
51 | x_test, y_test = _combine_data(cifar10_test, mnist_test, pad_equal)
52 | x_test, y_test = _create_dataset(x_test, y_test, timesteps, merge, seed)
53 |
54 | for i in range(len(x_test_files)):
55 | np.save(x_test_files[i], x_test[i])
56 | np.save(y_test_file, y_test)
57 |
58 | x_test = []
59 | for i in range(len(x_test_files)):
60 | x_test.append(np.load(x_test_files[i], mmap_mode=None)[:2230])
61 | y_test = np.load(y_test_file, mmap_mode=None)[:2230]
62 |
63 | return (x_train, y_train), (x_test, y_test)
64 |
65 |
66 | def _create_dataset(features, labels, timesteps, merge, seed):
67 | features_a, features_b = features
68 |
69 | num_classes = np.unique(labels).size
70 | shape_a = features_a.shape[1:]
71 | shape_b = features_b.shape[1:]
72 |
73 | features_a = np.reshape(features_a, (-1, num_classes) + shape_a, order='F')
74 | features_b = np.reshape(features_b, (-1, num_classes) + shape_b, order='F')
75 | labels = np.reshape(labels, (-1, num_classes), order='F')
76 |
77 | a1, a2 = np.split(features_a, (timesteps * len(features_a) // (timesteps+1), ))
78 | b1, b2 = np.split(features_b, (timesteps * len(features_b) // (timesteps+1), ))
79 | y1, y2 = np.split(labels, (timesteps * len(labels) // (timesteps+1), ))
80 |
81 | a1 = np.reshape(a1, (-1, timesteps) + shape_a)
82 | a2 = np.reshape(a2, (-1, ) + shape_a)
83 | b1 = np.reshape(b1, (-1, timesteps) + shape_b)
84 | y1 = np.reshape(y1, (-1, timesteps))
85 | y2 = np.reshape(y2, (-1, ))
86 |
87 | a1 = a1[:len(a1) // num_classes * num_classes]
88 | b1 = b1[:len(a1) // num_classes * num_classes]
89 | y1 = y1[:len(a1) // num_classes * num_classes]
90 |
91 | cols = []
92 | for i in range(y1.shape[1]):
93 | cols.append(np.unique(y1[:, i]))
94 | unique_cols = np.unique(cols, axis=0)
95 |
96 | x_a = a1
97 | x_b = b1
98 |
99 | # Targets are always the first `len(a1) // len(unique_cols)` elements in each timestep. We shuffle it
100 | # afterwards.
101 | y = -1 * np.ones(y1.shape[0], dtype=y1.dtype)
102 | x_c = np.zeros((a1.shape[0], ) + a2.shape[1:])
103 | target_mask = np.zeros(y1.shape, dtype=y1.dtype)
104 | for j, col in enumerate(unique_cols):
105 | for i in col:
106 | idc = np.nonzero(y1[:, j] == i)[0][:a1.shape[0] // num_classes]
107 | y[idc + j * a1.shape[0] // len(unique_cols)] = i
108 |
109 | target_mask[idc + j * a1.shape[0] // len(unique_cols), j] = 1
110 |
111 | idc2 = np.nonzero(y2 == i)[0][:a1.shape[0] // num_classes]
112 | x_c[idc + j * a1.shape[0] // len(unique_cols)] = a2[idc2]
113 |
114 | rows = np.split(np.indices(y1.shape)[0],
115 | np.arange(num_classes // timesteps, len(y1), num_classes // timesteps))
116 | cols = np.split(np.indices(y1.shape)[1],
117 | np.arange(num_classes // timesteps, len(y1), num_classes // timesteps))
118 |
119 | def shuffle_cols(cols, seed):
120 | return np.array([np.random.RandomState(seed=seed).permutation(c) for c in cols])
121 |
122 | def shuffle_rows(rows, seed):
123 | y = rows.shape[1]
124 | tmp = rows
125 | for i in range(y):
126 | tmp[:, i] = np.random.RandomState(seed=seed+i).permutation(rows[:, i])
127 |
128 | return tmp
129 |
130 | row_list_a, row_list_b = [], []
131 | col_list_a, col_list_b = [], []
132 | for i, (r, c) in enumerate(zip(rows, cols)):
133 | row_list_a.append(shuffle_rows(r, seed=seed*(i+1)))
134 | col_list_a.append(shuffle_cols(c, seed=seed*(i+2)))
135 |
136 | row_list_b.append(shuffle_rows(r, seed=seed*(i+3)))
137 | col_list_b.append(shuffle_cols(c, seed=seed*(i+4)))
138 |
139 | rows_a = np.concatenate(row_list_a)
140 | cols_a = np.concatenate(col_list_a)
141 |
142 | rows_b = np.concatenate(row_list_b)
143 | cols_b = np.concatenate(col_list_b)
144 |
145 | x_a = x_a[rows_a, cols_a]
146 | y_a = y1[rows_a, cols_a]
147 | if timesteps > 1:
148 | x_b = x_b[rows_b, cols_b]
149 | y_b = y1[rows_b, cols_b]
150 | else:
151 | y_b = y1
152 | x_c = np.stack([x_c] * timesteps, axis=1)
153 | x_c = x_c[rows_a, cols_a]
154 |
155 | target_mask = target_mask[rows_a, cols_a]
156 | x_c = x_c[np.nonzero(target_mask == 1)]
157 | y = y_b[np.nonzero(target_mask == 1)]
158 |
159 | idc = np.random.RandomState(seed=seed+10).permutation(y.shape[0])
160 | x_a = x_a[idc]
161 | x_b = x_b[idc]
162 | x_c = x_c[idc]
163 | y_a = y_a[idc]
164 | y_b = y_b[idc]
165 | y = y[idc]
166 |
167 | if merge:
168 | x_ab = []
169 | for a, b in zip(x_a.reshape((-1,) + x_a.shape[2:]), x_b.reshape((-1,) + x_b.shape[2:])):
170 | x_ab.append(image_manipulation.merge(a, b))
171 |
172 | x_ab = np.array(x_ab).reshape((-1, timesteps) + x_ab[0].shape)
173 |
174 | pad_width = ((0, 0), (0, x_c.shape[2]), (0, 0))
175 | x_c = image_manipulation.pad(x_c, pad_width=pad_width)
176 |
177 | return (x_ab, x_c), y
178 | else:
179 | return (x_a, x_b, x_c), y
180 |
181 |
182 | def _combine_data(a, b, pad):
183 | features_a, labels_a = a
184 | features_b, labels_b = b
185 |
186 | labels_a = labels_a.flatten()
187 | labels_b = labels_b.flatten()
188 |
189 | num_classes_a = np.unique(labels_a).size
190 | num_classes_b = np.unique(labels_b).size
191 | min_num_examples_a = min(np.unique(labels_a, return_counts=True)[1])
192 | min_num_examples_b = min(np.unique(labels_b, return_counts=True)[1])
193 |
194 | assert num_classes_a == num_classes_b
195 |
196 | pad_width_dim1_a = pad_width_dim1_b = pad_width_dim2_a = pad_width_dim2_b = 0
197 | if pad:
198 | if features_a.shape[1] > features_b.shape[1]:
199 | pad_width_dim1_b = (features_a.shape[1] - features_b.shape[1]) // 2
200 | if features_a.shape[1] < features_b.shape[1]:
201 | pad_width_dim1_a = (features_b.shape[1] - features_a.shape[1]) // 2
202 | if features_a.shape[2] > features_b.shape[2]:
203 | pad_width_dim2_b = (features_a.shape[2] - features_b.shape[2]) // 2
204 | if features_a.shape[2] < features_b.shape[2]:
205 | pad_width_dim2_a = (features_b.shape[2] - features_a.shape[2]) // 2
206 |
207 | x_a = []
208 | x_b = []
209 | y = []
210 | for i in range(num_classes_a):
211 | idc_a = np.where(labels_a == i)[0]
212 | idc_b = np.where(labels_b == i)[0]
213 | num = min(idc_a.size, idc_b.size, min_num_examples_a, min_num_examples_b)
214 | x_a.append(features_a[idc_a[:num]])
215 | x_b.append(features_b[idc_b[:num]])
216 | y.append(labels_a[idc_a[:num]])
217 |
218 | x_a = np.concatenate(x_a)
219 | x_b = np.concatenate(x_b)
220 | y = np.concatenate(y)
221 |
222 | pad_width_a = ((pad_width_dim1_a, pad_width_dim1_a), (pad_width_dim2_a, pad_width_dim2_a), (0, 0))
223 | pad_width_b = ((pad_width_dim1_b, pad_width_dim1_b), (pad_width_dim2_b, pad_width_dim2_b), (0, 0))
224 | x_a = image_manipulation.pad(x_a, pad_width=pad_width_a)
225 | x_b = image_manipulation.pad(x_b, pad_width=pad_width_b)
226 |
227 | return (x_a, x_b), y
228 |
229 |
230 | def _get_mnist_dataset(num_channels=1, pad_width=((0, 0), (0, 0), (0, 0))):
231 | mnist = tf.keras.datasets.mnist
232 | (x_train, y_train), (x_test, y_test) = mnist.load_data()
233 | x_train, x_test = x_train / 255.0, x_test / 255.0
234 | if num_channels == 1:
235 | x_train = x_train[..., tf.newaxis]
236 | x_test = x_test[..., tf.newaxis]
237 | else:
238 | x_train = image_manipulation.expand_channels(x_train, num_channels=num_channels)
239 | x_test = image_manipulation.expand_channels(x_test, num_channels=num_channels)
240 |
241 | x_train = image_manipulation.pad(x_train, pad_width)
242 | x_test = image_manipulation.pad(x_test, pad_width)
243 |
244 | return (x_train, y_train), (x_test, y_test)
245 |
246 |
247 | def _get_cifar10_dataset():
248 | cifar10 = tf.keras.datasets.cifar10
249 | (x_train, y_train), (x_test, y_test) = cifar10.load_data()
250 | x_train, x_test = x_train / 255.0, x_test / 255.0
251 |
252 | return (x_train, y_train.flatten()), (x_test, y_test.flatten())
253 |
--------------------------------------------------------------------------------
/babi_task_single.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Runs H-Mem on a single bAbI task."""
3 |
4 | import argparse
5 | import os
6 | import random
7 | from functools import reduce
8 | from itertools import chain
9 |
10 | import numpy as np
11 | import tensorflow as tf
12 | from data.babi_data import download, load_task, tasks, vectorize_data
13 | from layers.encoding import Encoding
14 | from layers.extracting import Extracting
15 | from layers.reading import ReadingCell
16 | from layers.writing import WritingCell
17 | from tensorflow.keras import Model
18 | from tensorflow.keras.layers import TimeDistributed
19 | from utils.logger import MyCSVLogger
20 |
21 | strategy = tf.distribute.MirroredStrategy()
22 |
23 | parser = argparse.ArgumentParser()
24 | parser.add_argument('--task_id', type=int, default=1)
25 | parser.add_argument('--max_num_sentences', type=int, default=-1)
26 | parser.add_argument('--training_set_size', type=str, default='10k', help='`1k` or `10k`')
27 |
28 | parser.add_argument('--epochs', type=int, default=100)
29 | parser.add_argument('--learning_rate', type=float, default=0.003)
30 | parser.add_argument('--batch_size_per_replica', type=int, default=128)
31 | parser.add_argument('--random_state', type=int, default=None)
32 | parser.add_argument('--max_grad_norm', type=float, default=20.0)
33 | parser.add_argument('--validation_split', type=float, default=0.1)
34 |
35 | parser.add_argument('--hops', type=int, default=3)
36 | parser.add_argument('--memory_size', type=int, default=100)
37 | parser.add_argument('--embeddings_size', type=int, default=80)
38 | parser.add_argument('--read_before_write', type=int, default=0)
39 | parser.add_argument('--gamma_pos', type=float, default=0.01)
40 | parser.add_argument('--gamma_neg', type=float, default=0.01)
41 | parser.add_argument('--w_assoc_max', type=float, default=1.0)
42 | parser.add_argument('--encodings_type', type=str, default='learned_encoding',
43 | help='`identity_encoding`, `position_encoding` or `learned_encoding`')
44 |
45 | parser.add_argument('--verbose', type=int, default=1)
46 | parser.add_argument('--logging', type=int, default=0)
47 | args = parser.parse_args()
48 |
49 | batch_size = args.batch_size_per_replica * strategy.num_replicas_in_sync
50 |
51 | # Set random seeds.
52 | np.random.seed(args.random_state)
53 | random.seed(args.random_state)
54 | tf.random.set_seed(args.random_state)
55 |
56 | if args.logging:
57 | logdir = 'results/'
58 |
59 | if not os.path.exists(logdir):
60 | os.makedirs(logdir)
61 |
62 | # Download bAbI data set.
63 | data_dir = download()
64 |
65 | if args.verbose:
66 | print('Extracting stories for the challenge: {0}, {1}'.format(args.task_id, tasks[args.task_id]))
67 |
68 | # Load the data.
69 | train, test = load_task(data_dir, args.task_id, args.training_set_size)
70 | data = train + test
71 |
72 | vocab = sorted(reduce(lambda x, y: x | y, (set(list(chain.from_iterable(s)) + q + a) for s, q, a in data)))
73 | word_idx = dict((c, i + 1) for i, c in enumerate(vocab))
74 |
75 | max_story_size = max(map(len, (s for s, _, _ in data)))
76 |
77 | max_num_sentences = max_story_size if args.max_num_sentences == -1 else min(args.max_num_sentences,
78 | max_story_size)
79 |
80 | out_size = len(word_idx) + 1 # +1 for nil word.
81 |
82 | # Add time words/indexes
83 | for i in range(max_num_sentences):
84 | word_idx['time{}'.format(i+1)] = 'time{}'.format(i+1)
85 |
86 | vocab_size = len(word_idx) + 1 # +1 for nil word.
87 | mean_story_size = int(np.mean([len(s) for s, _, _ in data]))
88 | max_sentence_size = max(map(len, chain.from_iterable(s for s, _, _ in data))) + 1 # +1 for time word.
89 | max_query_size = max(map(len, (q for _, q, _ in data)))
90 |
91 | if args.verbose:
92 | print('-')
93 | print('Vocab size:', vocab_size, 'unique words (including "nil" word and "time" words)')
94 | print('Story max length:', max_story_size, 'sentences')
95 | print('Story mean length:', mean_story_size, 'sentences')
96 | print('Story max length:', max_sentence_size, 'words (including "time" word)')
97 | print('Query max length:', max_query_size, 'words')
98 | print('-')
99 | print('Here\'s what a "story" tuple looks like (story, query, answer):')
100 | print(data[0])
101 | print('-')
102 | print('Vectorizing the stories...')
103 |
104 | # Vectorize the data.
105 | max_words = max(max_sentence_size, max_query_size)
106 | trainS, trainQ, trainA = vectorize_data(train, word_idx, max_num_sentences, max_words, max_words)
107 | testS, testQ, testA = vectorize_data(test, word_idx, max_num_sentences, max_words, max_words)
108 |
109 | trainQ = np.repeat(np.expand_dims(trainQ, axis=1), args.hops, axis=1)
110 | testQ = np.repeat(np.expand_dims(testQ, axis=1), args.hops, axis=1)
111 |
112 | story_shape = trainS.shape[1:]
113 | query_shape = trainQ.shape[1:]
114 |
115 | x_train = [trainS, trainQ]
116 | y_train = np.argmax(trainA, axis=1)
117 |
118 | x_test = [testS, testQ]
119 | y_test = np.argmax(testA, axis=1)
120 |
121 | if args.verbose:
122 | print('-')
123 | print('Stories: integer tensor of shape (samples, max_length, max_words): {0}'.format(trainS.shape))
124 | print('Here\'s what a vectorized story looks like (sentence, word):')
125 | print(trainS[0])
126 | print('-')
127 | print('Queries: integer tensor of shape (samples, length): {0}'.format(trainQ.shape))
128 | print('Here\'s what a vectorized query looks like:')
129 | print(trainQ[0])
130 | print('-')
131 | print('Answers: binary tensor of shape (samples, vocab_size): {0}'.format(trainA.shape))
132 | print('Here\'s what a vectorized answer looks like:')
133 | print(trainA[0])
134 | print('-')
135 | print('Training...')
136 |
137 | with strategy.scope():
138 | # Build the model.
139 | story_input = tf.keras.layers.Input(story_shape, name='story_input')
140 | query_input = tf.keras.layers.Input(query_shape, name='query_input')
141 |
142 | embedding = tf.keras.layers.Embedding(input_dim=vocab_size,
143 | output_dim=args.embeddings_size,
144 | embeddings_initializer='he_uniform',
145 | embeddings_regularizer=None,
146 | mask_zero=True,
147 | name='embedding')
148 | story_embedded = TimeDistributed(embedding, name='story_embedding')(story_input)
149 | query_embedded = TimeDistributed(embedding, name='query_embedding')(query_input)
150 |
151 | encoding = Encoding(args.encodings_type, name='encoding')
152 | story_encoded = TimeDistributed(encoding, name='story_encoding')(story_embedded)
153 | query_encoded = TimeDistributed(encoding, name='query_encoding')(query_embedded)
154 |
155 | story_encoded = tf.keras.layers.BatchNormalization(name='batch_norm_story')(story_encoded)
156 | query_encoded = tf.keras.layers.BatchNormalization(name='batch_norm_query')(query_encoded)
157 |
158 | entities = Extracting(units=args.memory_size,
159 | use_bias=False,
160 | activation='relu',
161 | kernel_initializer='he_uniform',
162 | kernel_regularizer=tf.keras.regularizers.l2(1e-3),
163 | name='entity_extracting')(story_encoded)
164 |
165 | memory_matrix = tf.keras.layers.RNN(WritingCell(units=args.memory_size,
166 | read_before_write=args.read_before_write,
167 | use_bias=False,
168 | gamma_pos=args.gamma_pos,
169 | gamma_neg=args.gamma_neg,
170 | w_assoc_max=args.w_assoc_max,
171 | kernel_initializer='he_uniform',
172 | kernel_regularizer=tf.keras.regularizers.l2(1e-3)),
173 | name='entity_writing')(entities)
174 |
175 | queried_value = tf.keras.layers.RNN(ReadingCell(units=args.memory_size,
176 | use_bias=False,
177 | activation='relu',
178 | kernel_initializer='he_uniform',
179 | kernel_regularizer=tf.keras.regularizers.l2(1e-3)),
180 | name='entity_reading')(query_encoded, constants=[memory_matrix])
181 |
182 | outputs = tf.keras.layers.Dense(vocab_size,
183 | use_bias=False,
184 | kernel_initializer='he_uniform',
185 | name='output')(queried_value)
186 |
187 | model = Model(inputs=[story_input, query_input], outputs=outputs)
188 |
189 | # Compile the model.
190 | optimizer_kwargs = {'clipnorm': args.max_grad_norm} if args.max_grad_norm else {}
191 | model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=args.learning_rate, **optimizer_kwargs),
192 | loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
193 | metrics=['accuracy'])
194 |
195 | model.summary()
196 |
197 |
198 | # Train and evaluate.
199 | def lr_scheduler(epoch):
200 | if args.read_before_write:
201 | if epoch < 150:
202 | return args.learning_rate
203 | else:
204 | return args.learning_rate * tf.math.exp(0.01 * (150 - epoch))
205 | else:
206 | return args.learning_rate * 0.85**tf.math.floor(epoch / 20)
207 |
208 |
209 | callbacks = []
210 | callbacks.append(tf.keras.callbacks.LearningRateScheduler(lr_scheduler, verbose=0))
211 | if args.logging:
212 | callbacks.append(tf.keras.callbacks.CSVLogger(os.path.join(logdir, '{0}_{1}_{2}_{3}-{4}.log'.format(
213 | args.task_id, args.training_set_size, args.encodings_type, args.hops, args.random_state))))
214 |
215 | model.fit(x=x_train, y=y_train, epochs=args.epochs, validation_split=args.validation_split,
216 | batch_size=batch_size, callbacks=callbacks, verbose=args.verbose)
217 |
218 | callbacks = []
219 | if args.logging:
220 | callbacks.append(MyCSVLogger(os.path.join(logdir, '{0}_{1}_{2}_{3}-{4}.log'.format(
221 | args.task_id, args.training_set_size, args.encodings_type, args.hops, args.random_state))))
222 |
223 | model.evaluate(x=x_test, y=y_test, callbacks=callbacks, verbose=2)
224 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------