{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n", "import theano\n", "import theano.tensor as T\n", "from theano.ifelse import ifelse" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Dropout:\n", "\n", " def __init__(self):\n", " \n", " # Set seed for the random numbers\n", " np.random.seed(1234)\n", " rng = np.random.RandomState(1234)\n", " \n", " # Generate a theano RandomStreams\n", " self.srng = RandomStreams(rng.randint(999999)) \n", " \n", " \n", " def __dropit(self, weight, drop):\n", " \"\"\"\n", " Drops some of the cells of 'weight' matrix based on a binomial representation with prob = drop\n", " \n", " # Arguments:\n", " \n", " :param weight : Parameter matrix of the model\n", " :type : theano.tensor\n", " \n", " :param drop : proportion to dropout from the 'weight'\n", " :type : float32\n", " \n", " # Returns: Dropped out matrix\n", " \"\"\"\n", " retain_prob = 1 - drop\n", " mask = self.srng.binomial(n=1, p=retain_prob, size=weight.shape, dtype='floatX')\n", " \n", " return theano.tensor.cast(weight * mask, theano.config.floatX)\n", "\n", " def __dont_dropit(self, weight, drop):\n", " \"\"\"\n", " Scale the weight parameters if train = 0\n", " \n", " # Arguments:\n", " \n", " :param weight : Parameter matrix of the model\n", " :type : theano.tensor\n", " \n", " :param drop : proportion to dropout from the 'weight'\n", " :type : float32\n", " \n", " # Returns: Scaled Dropped out matrix\n", " \"\"\"\n", " return (1 - drop) * theano.tensor.cast(weight, theano.config.floatX)\n", "\n", " def dropout_layer(self, weight, drop, train = 1): \n", " \"\"\"\n", " Drops some of the cells of 'weight' matrix based on a binomial representation with prob = drop\n", " \n", " # Arguments:\n", " \n", " :param weight : Parameter matrix of the model\n", " :type : theano.tensor\n", " \n", " :param drop : proportion to dropout from the 'weight'\n", " :type : float32\n", " \n", " :param train : Flag to switch on/off the dropout\n", " :type : int32\n", " \n", " # Returns: Dropped out matrix if train = 1\n", " \"\"\"\n", " result = theano.ifelse.ifelse(theano.tensor.eq(train, 1), self.__dropit(weight, drop), self.__dont_dropit(weight, drop))\n", " return result" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" } }, "nbformat": 4, "nbformat_minor": 0 }