forked from google-deepmind/learning-to-learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problems.py
278 lines (220 loc) · 8.65 KB
/
problems.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Learning 2 Learn problems."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tarfile
import sys
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets import mnist as mnist_dataset
import nn
_nn_initializers = {
"w": tf.random_normal_initializer(mean=0, stddev=0.01),
"b": tf.random_normal_initializer(mean=0, stddev=0.01),
}
def simple():
"""Simple problem: f(x) = x^2."""
def build():
"""Builds loss graph."""
x = tf.get_variable(
"x",
shape=[],
dtype=tf.float32,
initializer=tf.ones_initializer())
return tf.square(x, name="x_squared")
return build
def simple_multi_optimizer(num_dims=2):
"""Multidimensional simple problem."""
def get_coordinate(i):
return tf.get_variable("x_{}".format(i),
shape=[],
dtype=tf.float32,
initializer=tf.ones_initializer())
def build():
coordinates = [get_coordinate(i) for i in xrange(num_dims)]
x = tf.concat([tf.expand_dims(c, 0) for c in coordinates], 0)
return tf.reduce_sum(tf.square(x, name="x_squared"))
return build
def quadratic(batch_size=128, num_dims=10, stddev=0.01, dtype=tf.float32):
"""Quadratic problem: f(x) = ||Wx - y||."""
def build():
"""Builds loss graph."""
# Trainable variable.
x = tf.get_variable(
"x",
shape=[batch_size, num_dims],
dtype=dtype,
initializer=tf.random_normal_initializer(stddev=stddev))
# Non-trainable variables.
w = tf.get_variable("w",
shape=[batch_size, num_dims, num_dims],
dtype=dtype,
initializer=tf.random_uniform_initializer(),
trainable=False)
y = tf.get_variable("y",
shape=[batch_size, num_dims],
dtype=dtype,
initializer=tf.random_uniform_initializer(),
trainable=False)
product = tf.squeeze(tf.matmul(w, tf.expand_dims(x, -1)))
return tf.reduce_mean(tf.reduce_sum((product - y) ** 2, 1))
return build
def ensemble(problems, weights=None):
"""Ensemble of problems.
Args:
problems: List of problems. Each problem is specified by a dict containing
the keys 'name' and 'options'.
weights: Optional list of weights for each problem.
Returns:
Sum of (weighted) losses.
Raises:
ValueError: If weights has an incorrect length.
"""
if weights and len(weights) != len(problems):
raise ValueError("len(weights) != len(problems)")
build_fns = [getattr(sys.modules[__name__], p["name"])(**p["options"])
for p in problems]
def build():
loss = 0
for i, build_fn in enumerate(build_fns):
with tf.variable_scope("problem_{}".format(i)):
loss_p = build_fn()
if weights:
loss_p *= weights[i]
loss += loss_p
return loss
return build
def _xent_loss(output, labels):
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=output,
labels=labels)
return tf.reduce_mean(loss)
def mnist(layers, # pylint: disable=invalid-name
activation="sigmoid",
batch_size=128,
mode="train"):
"""Mnist classification with a multi-layer perceptron."""
if activation == "sigmoid":
activation_op = tf.sigmoid
elif activation == "relu":
activation_op = tf.nn.relu
else:
raise ValueError("{} activation not supported".format(activation))
# Data.
data = mnist_dataset.load_mnist()
data = getattr(data, mode)
images = tf.constant(data.images, dtype=tf.float32, name="MNIST_images")
images = tf.reshape(images, [-1, 28, 28, 1])
labels = tf.constant(data.labels, dtype=tf.int64, name="MNIST_labels")
# Network.
mlp = nn.MLP(list(layers) + [10],
activation=activation_op,
initializers=_nn_initializers)
network = nn.Sequential([nn.BatchFlatten(), mlp])
def build():
indices = tf.random_uniform([batch_size], 0, data.num_examples, tf.int64)
batch_images = tf.gather(images, indices)
batch_labels = tf.gather(labels, indices)
output = network(batch_images)
return _xent_loss(output, batch_labels)
return build
CIFAR10_URL = "http://www.cs.toronto.edu/~kriz"
CIFAR10_FILE = "cifar-10-binary.tar.gz"
CIFAR10_FOLDER = "cifar-10-batches-bin"
def _maybe_download_cifar10(path):
"""Download and extract the tarball from Alex's website."""
if not os.path.exists(path):
os.makedirs(path)
filepath = os.path.join(path, CIFAR10_FILE)
if not os.path.exists(filepath):
print("Downloading CIFAR10 dataset to {}".format(filepath))
url = os.path.join(CIFAR10_URL, CIFAR10_FILE)
filepath, _ = urllib.request.urlretrieve(url, filepath)
statinfo = os.stat(filepath)
print("Successfully downloaded {} bytes".format(statinfo.st_size))
tarfile.open(filepath, "r:gz").extractall(path)
def cifar10(path, # pylint: disable=invalid-name
conv_channels=None,
linear_layers=None,
batch_norm=True,
batch_size=128,
num_threads=4,
min_queue_examples=1000,
mode="train"):
"""Cifar10 classification with a convolutional network."""
# Data.
_maybe_download_cifar10(path)
# Read images and labels from disk.
if mode == "train":
filenames = [os.path.join(path,
CIFAR10_FOLDER,
"data_batch_{}.bin".format(i))
for i in xrange(1, 6)]
elif mode == "test":
filenames = [os.path.join(path, "test_batch.bin")]
else:
raise ValueError("Mode {} not recognised".format(mode))
depth = 3
height = 32
width = 32
label_bytes = 1
image_bytes = depth * height * width
record_bytes = label_bytes + image_bytes
reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
_, record = reader.read(tf.train.string_input_producer(filenames))
record_bytes = tf.decode_raw(record, tf.uint8)
label = tf.cast(tf.slice(record_bytes, [0], [label_bytes]), tf.int32)
raw_image = tf.slice(record_bytes, [label_bytes], [image_bytes])
image = tf.cast(tf.reshape(raw_image, [depth, height, width]), tf.float32)
# height x width x depth.
image = tf.transpose(image, [1, 2, 0])
image = tf.div(image, 255)
queue = tf.RandomShuffleQueue(capacity=min_queue_examples + 3 * batch_size,
min_after_dequeue=min_queue_examples,
dtypes=[tf.float32, tf.int32],
shapes=[image.get_shape(), label.get_shape()])
enqueue_ops = [queue.enqueue([image, label]) for _ in xrange(num_threads)]
tf.train.add_queue_runner(tf.train.QueueRunner(queue, enqueue_ops))
# Network.
def _conv_activation(x): # pylint: disable=invalid-name
return tf.nn.max_pool(tf.nn.relu(x),
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding="SAME")
conv = nn.ConvNet2D(output_channels=conv_channels,
kernel_shapes=[5],
strides=[1],
paddings=[nn.SAME],
activation=_conv_activation,
activate_final=True,
initializers=_nn_initializers,
use_batch_norm=batch_norm)
if batch_norm:
linear_activation = lambda x: tf.nn.relu(nn.BatchNorm()(x))
else:
linear_activation = tf.nn.relu
mlp = nn.MLP(list(linear_layers) + [10],
activation=linear_activation,
initializers=_nn_initializers)
network = nn.Sequential([conv, nn.BatchFlatten(), mlp])
def build():
image_batch, label_batch = queue.dequeue_many(batch_size)
label_batch = tf.reshape(label_batch, [batch_size])
output = network(image_batch)
return _xent_loss(output, label_batch)
return build