Source

gumby / src / gumby / adapter / movie.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# (C) Copyright 2007 Olivier Grisel
# Author: Olivier Grisel <olivier.grisel@ensta.org>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#
# $Id$
"""Use a sequence of PIL Image instances as Brain input"""

from PIL import Image
from itertools import cycle
from itertools import izip
from numpy import array
from numpy import cumsum
from numpy import maximum
from numpy import float32
import cPickle as pickle
import os
import shutil
import tempfile

from gumby.brain import Brain
from gumby.plotting import make_plot
from gumby.plotting import save_plot


def get_image_dimensions(img):
    """Utility function to compute the brain dimension to use given the mode"""
    if len(img.getbands()) == 3:
        return img.size + (3,)
    else:
        return img.size


class Movie(object):
    """A sequence of images with semantic description"""

    avi_cmd_pattern = ("mencoder 'mf://%s/*.png' -mf type=png:fps=%0.2f "
                       "-ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o %s")

    gif_cmd_pattern = "convert -delay %d %s/*.png %s"

    avi_play_cmd_pattern = "vlc %s"

    def __init__(self, images, fps, descriptions=(),  name="movie"):
        # sequence of a PIL image objects
        self._images = images

        # sequence of semantic descriptions of the previous images
        self._descriptions = descriptions

        self.fps = fps
        self.name = name

    #
    # pickling support
    #

    def __getstate__(self):
        """Override gestate to make the movie picklable"""
        dict_ = self.__dict__.copy()


        dict_['_images'] = [(img.mode, img.size, img.tostring())
                            for img in dict_['_images']]
        return dict_

    def __setstate__(self, dict_):
        """Override setstate to load pickled movies"""
        dict_['_images'] = [Image.fromstring(m, s, d)
                            for m, s, d in dict_['_images']]
        self.__dict__.update(dict_)

        # compat with old definition
        if not hasattr(self, 'fps'):
            self.fps = self._fps

    def save(self, filename=None, directory=None):
        """Save the complete movie instance as a pickle"""
        filename = filename or self.name + '.pickle'
        if directory:
            filename = os.path.join(directory, filename)
        pickle.dump(self, file(filename, 'w'), -1)

    #
    # sequence / iterator interface
    #

    def __len__(self):
        return len(self._images)

    def __iter__(self):
        return izip(self._images, self._descriptions)

    def __getitem__(self, index):
        return self._images[index]

    #
    # Brain interoperability
    #

    def get_dimensions(self):
        """Return the 2D dimensions of the first frame + 3 if in RGB"""
        return get_image_dimensions(self._images[0])

    #
    # Image / movies export / preview
    #

    def save_as_img_sequence(self, directory, format='png'):
        filenames = []
        for i, img in enumerate(self._images):
            filename = os.path.join(directory, self.name + '_%04d.%s' % (
                i, format))
            img.save(filename)
            filenames.append(filename)
        return filenames

    def save_as_avi_movie(self, filename=""):
        filename = filename or self.name + '.avi'
        directory = tempfile.mkdtemp()
        self.save_as_img_sequence(directory)
        cmd = self.avi_cmd_pattern % (directory, self.fps, filename)
        os.system(cmd)
        shutil.rmtree(directory)

    def save_as_animated_gif(self, filename):
        filename = filename or self.name + '.gif'
        directory = tempfile.mkdtemp()
        self.save_as_img_sequence(directory)
        os.system(self.gif_cmd_pattern % (
            1 / self.fps * 100, directory, filename))
        shutil.rmtree(directory)

    #
    # Basic playback for inline debugging
    #

    def play(self):
        _, filename = tempfile.mkstemp()
        self.save_as_avi_movie(filename)
        cmd = self.avi_play_cmd_pattern % filename
        os.system(cmd)
        os.remove(filename)


class StereoMovie(object):
    """Use two cameras to shoot two streams of images for the same scene"""
    # TODO
    pass


def load_movie(filename):
    """Load a saved movie pickle"""
    return pickle.load(file(filename, 'r'))


def movavg(s, n, dtype=float32):
    """Return an n period moving average for the time series s

    s is a list ordered from oldest (index 0) to most recent (index -1)
    n is an integer
    """
    s = array(s, dtype=dtype)
    c = cumsum(s)
    return (c[n-1:] - c[:-n+1]) / float(n)


class MovieAdapter(object):
    """Adapter to make a brain able to watch Coca-Cola(tm) ads on TV

    This implements the ``next`` method of the python generator interface to
    inject and predict the next movie frame.
    """

    record = True

    dtype = float32

    def __init__(self, movies, brain=None, named_nodes=None, dimensions=None,
                 record=True):

        # TODO: make it possible to adapt the movie size to the brain dimensions
        if isinstance(movies, Movie):
            self._movies = [movies]
        else:
            self._movies = list(movies)
            for movie in self._movies:
                assert isinstance(movie, Movie)

        first_movie = self._movies[0]
        self.dimensions = dimensions or first_movie.get_dimensions()

        # TODO: replace Brain by any IPredictor
        if brain is None:
            # build a single layer brain with dimensions mathcing the movie's
            self.brain = Brain()
            self.brain.add_layer(dimensions=self.dimensions)
        else:
            # check input dimensions compatibility here
            self.brain = brain

        self.mode = len(self.dimensions) == 3 and 'RGB' or 'L'
        self.record = record
        self._recorded_frames = dict()
        self._recorded_mse = dict()
        self._recorded_identity_mse = dict()
        self._training_set = None

        # initialize the frame generator and ensure the brain has no previous
        # historical data
        self.reset()

    def img_to_array(self, image):
        """Convert a PIL Image into a numpy array suitable as brain input"""
        if image.mode != self.mode:
            image = image.convert(mode=self.mode)
        if image.size != self.dimensions[:2]:
            image = image.resize(self.dimensions[:2], Image.ANTIALIAS)

        w, h = self.dimensions[:2]
        data = array(image.getdata(), dtype=self.dtype)
        rescaled_data = data / 128. - 1
        return rescaled_data.reshape(h, w).transpose()

    def array_to_img(self, data, reference_image):
        """Convert brain ouput to an Image with the same format as the input"""

        rescaled = ((data + 1.) * 128).clip(0, 255)

        image = Image.new(self.mode, (rescaled.shape[0], rescaled.shape[1]))
        image.putdata(list(rescaled.transpose().flat))
        if image.size != reference_image.size:
            image = image.resize(reference_image.size, Image.NEAREST)
        return image

    def build_frame_generator(self):
        """Python generator to iteratively transcode img to brain I/O"""
        for movie in self._movies:
            for frame, description in movie:
                # XXX: handle named_nodes
                input = self.img_to_array(frame)
                output = self.brain.predict([input])
                if self.record:
                    self.record_current_state(current_input=input)
                # TODO: the [0] assumes we only use a single layer
                yield self.array_to_img(output[0], frame)

    def record_current_state(self, current_input=None):
        """"Add the current state of to the record history"""
        first_frame, _ = iter(self._movies[0]).next()
        for l in self.brain:
            recorded_frames = self._recorded_frames.setdefault(l, [])
            recorded_frames.append(
                self.array_to_img(l.get_prediction(), first_frame))
            recorded_mse = self._recorded_mse.setdefault(l, [])
            recorded_mse.append(l.get_squared_prediction_error())

            # recorded the mean squared error of the identity function as a
            # a reference for predictive accuracy
            if current_input is not None:
                identity_mse = self._recorded_identity_mse.setdefault(l, [])
                if self._previous_input is None:
                    identity_mse.append(
                        ((current_input - current_input.mean()) ** 2).mean())
                else:
                    identity_mse.append(
                        ((current_input - self._previous_input) ** 2).mean())


        # store input to compute next identity_mse
        self._previous_input = current_input

    def get_movie(self, layer):
        """Return a movie instance of the selected layer"""
        if isinstance(layer, int):
            layer_id = layer
            layer = list(self.brain.layers)[layer]
        else:
            layer_id = id(layer)

        recorded_frames = self._recorded_frames.get(layer)
        if recorded_frames is None:
            return None
        return Movie(recorded_frames, self._movies[0].fps,
                     name="Recorded frames for layer %d" % layer_id)

    def get_movies(self):
        """Return the movies recorded for each layer of the brain"""
        return [self.get_movie(l) for l in self.brain.get_ranked_layers()]

    def get_mse(self, layer=None):
        """Return the recorded historical mean squared errors for layer

        If no specific layer is provided return the list of all recorded
        MSEs in ranked layers order.
        """
        if layer is not None:
            return self._recorded_mse.get(layer)
        else:
            return [self._recorded_mse.get(l)
                    for l in self.brain.get_ranked_layers()]

    def plot_mse(self, filename, movavg_period=0, only_last=None):
        """Plot the recorded mse into files

        If movavg_period > 0, the plotted data is averaged over a window
        with the requested period.
        """
        plot = make_plot("Recorded Mean Square Errors")
        for i, layer in enumerate(self.brain.get_ranked_layers()):
            mse = self._recorded_mse.get(layer)
            identity_mse = array(self._recorded_identity_mse.get(layer))

            # prevent zeros values to allow for log plot
            mse = maximum(mse, 1e-6)
            identity_mse = maximum(identity_mse, 1e-6)

            if mse is not None:
                if only_last is not None:
                    mse = mse[-only_last:]
                    identity_mse = identity_mse[-only_last:]

                label = "MSE for layer %d" % i
                if movavg_period > 0:
                    plot.semilogy(movavg(mse, movavg_period), label=label)
                    plot.semilogy(movavg(identity_mse, movavg_period),
                                  label="Identity " + label)
                else:
                    plot.semilogy(mse, label=label)
                    plot.semilogy(identity_mse, label="Identity " + label)
        plot.legend()
        save_plot(plot, filename)

    def plot_mse_gain_over_identity(self, filename, movavg_period=0):
        """Plot the ration between recorded MSE and the MSE of the identity

        If movavg_period > 0, the plotted data is averaged over a window
        with the requested period.
        """
        plot = make_plot("MSE gain over identity prediction")
        for i, layer in enumerate(self.brain.get_ranked_layers()):
            mse = array(self._recorded_mse.get(layer))
            identity_mse = array(self._recorded_identity_mse.get(layer))
            mse = mse / identity_mse
            if mse is not None:
                label = "Layer %d" % i
                if movavg_period > 0:
                    plot.semilogy(movavg(mse, movavg_period), label=label)
                else:
                    plot.semilogy(mse, label=label)
        plot.legend()
        save_plot(plot, filename)

    def next(self):
        """Watch the next frame and predict the outcome as an Image instance"""
        return self._frame_generator.next()

    def reset(self):
        self._previous_input = None
        self._recorded_frames.clear()
        self._recorded_mse.clear()
        self._recorded_identity_mse.clear()
        self.brain.reset()
        self._frame_generator = self.build_frame_generator()
        self._training_set = None

    def train(self, nb_passes=None, find_parameters=False,
              max_sample_size=None, **kw):
        """Train the brain using the movie as training set

        TODO: explain the training scheme here
        TODO: make it possible to load the movies lazily from the disk without
              holding them in memory all at once
        """

        if nb_passes is None:
            # default one pass by layer in the brain
            nb_passes = len(self.brain)

        # build an infinite training set if not done yet
        if self._training_set is None:
            self._training_set = cycle(
                self.img_to_array(f) for movie in self._movies for f, d in movie)

        for pass_index in xrange(nb_passes):
            for layer in self.brain.get_ranked_layers():
                # load the layer historical data with enough data from the
                # movie
                for i in xrange(layer.history_size):
                    input = self._training_set.next()
                    self.brain.predict([input])
                    if self.record:
                        self.record_current_state(current_input=input)

                layer.train(find_parameters=find_parameters,
                            max_sample_size=max_sample_size, **kw)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.