code
stringlengths
17
6.64M
def sample_discretized_logistic(mean, logscale, inverse_bin_width): x = sample_logistic(mean, logscale) x = (torch.round((x * inverse_bin_width)) / inverse_bin_width) return x
def normal_cdf(value, loc, std): return (0.5 * (1 + torch.erf((((value - loc) * std.reciprocal()) / math.sqrt(2)))))
def log_discretized_normal(x, mean, logvar, inverse_bin_width): std = torch.exp((0.5 * logvar)) log_p = torch.log(((normal_cdf((x + (0.5 / inverse_bin_width)), mean, std) - normal_cdf((x - (0.5 / inverse_bin_width)), mean, std)) + 1e-07)) return log_p
def log_mixture_discretized_normal(x, mean, logvar, pi, inverse_bin_width): std = torch.exp((0.5 * logvar)) x = x.view(x.size(0), x.size(1), x.size(2), x.size(3), 1) p = (normal_cdf((x + (0.5 / inverse_bin_width)), mean, std) - normal_cdf((x - (0.5 / inverse_bin_width)), mean, std)) p = torch.sum((p *...
def sample_discretized_normal(mean, logvar, inverse_bin_width): y = torch.randn_like(mean) x = ((torch.exp((0.5 * logvar)) * y) + mean) x = (torch.round((x * inverse_bin_width)) / inverse_bin_width) return x
def log_mixture_discretized_logistic(x, mean, logscale, pi, inverse_bin_width): scale = torch.exp(logscale) x = x.view(x.size(0), x.size(1), x.size(2), x.size(3), 1) p = (torch.sigmoid((((x + (0.5 / inverse_bin_width)) - mean) / scale)) - torch.sigmoid((((x - (0.5 / inverse_bin_width)) - mean) / scale))) ...
def mixture_discretized_logistic_cdf(x, mean, logscale, pi, inverse_bin_width): scale = torch.exp(logscale) x = x[(..., None)] cdfs = torch.sigmoid((((x + (0.5 / inverse_bin_width)) - mean) / scale)) cdf = torch.sum((cdfs * pi), dim=(- 1)) return cdf
def sample_mixture_discretized_logistic(mean, logs, pi, inverse_bin_width): (b, c, h, w, n_mixtures) = tuple(map(int, pi.size())) pi = pi.view((((b * c) * h) * w), n_mixtures) sampled_pi = torch.multinomial(pi, num_samples=1).view((- 1)) mean = mean.view((((b * c) * h) * w), n_mixtures) mean = mea...
def log_multinomial(logits, targets): return (- F.cross_entropy(logits, targets, reduction='none'))
def sample_multinomial(logits): (b, n_categories, c, h, w) = logits.size() logits = logits.permute(0, 2, 3, 4, 1) p = F.softmax(logits, dim=(- 1)) p = p.view((((b * c) * h) * w), n_categories) x = torch.multinomial(p, num_samples=1).view(b, c, h, w) return x
class ToTensorNoNorm(): def __call__(self, X_i): return torch.from_numpy(np.array(X_i, copy=False)).permute(2, 0, 1)
class PadToMultiple(object): def __init__(self, multiple, fill=0, padding_mode='constant'): assert isinstance(multiple, numbers.Number) assert isinstance(fill, (numbers.Number, str, tuple)) assert (padding_mode in ['constant', 'edge', 'reflect', 'symmetric']) self.multiple = multi...
class CustomTensorDataset(Dataset): 'Dataset wrapping tensors.\n\n Each sample will be retrieved by indexing tensors along the first dimension.\n\n Arguments:\n *tensors (Tensor): tensors that have the same size of the first dimension.\n ' def __init__(self, *tensors, transform=None): ...
def load_cifar10(args, **kwargs): args.input_size = [3, 32, 32] args.input_type = 'continuous' args.dynamic_binarization = False from keras.datasets import cifar10 ((x_train, y_train), (x_test, y_test)) = cifar10.load_data() x_train = x_train.transpose(0, 3, 1, 2) x_test = x_test.transpose...
def extract_tar(tarpath): assert tarpath.endswith('.tar') startdir = (tarpath[:(- 4)] + '/') if os.path.exists(startdir): return startdir print('Extracting', tarpath) with tarfile.open(name=tarpath) as tar: t = 0 done = False while (not done): path = joi...
def load_imagenet(resolution, args, **kwargs): assert ((resolution == 32) or (resolution == 64)) args.input_size = [3, resolution, resolution] trainpath = '../imagenet{res}/train_{res}x{res}.tar'.format(res=resolution) valpath = '../imagenet{res}/valid_{res}x{res}.tar'.format(res=resolution) train...
def load_dataset(args, **kwargs): if (args.dataset == 'cifar10'): (train_loader, val_loader, test_loader, args) = load_cifar10(args, **kwargs) elif (args.dataset == 'imagenet32'): (train_loader, val_loader, test_loader, args) = load_imagenet(32, args, **kwargs) elif (args.dataset == 'image...
def calculate_likelihood(X, model, args, S=5000, MB=500): N_test = X.size(0) X = X.view((- 1), *args.input_size) likelihood_test = [] if (S <= MB): R = 1 else: R = (S // MB) S = MB for j in range(N_test): if ((j % 100) == 0): print('Progress: {:.2f}%...
def plot_training_curve(train_loss, validation_loss, fname='training_curve.pdf', labels=None): '\n Plots train_loss and validation loss as a function of optimization iteration\n :param train_loss: np.array of train_loss (1D or 2D)\n :param validation_loss: np.array of validation loss (1D or 2D)\n :par...
class LiviaSoftmax(HyperDenseNetConvLayer): ' Final Classification layer with Softmax ' def __init__(self, rng, layerID, inputSample_Train, inputSample_Test, inputToLayerShapeTrain, inputToLayerShapeTest, filterShape, applyBatchNorm, applyBatchNormNumberEpochs, maxPoolingParameters, weights_initialization, w...
def computeDice(autoSeg, groundTruth): ' Returns\n -------\n DiceArray : floats array\n \n Dice coefficient as a float on range [0,1].\n Maximum similarity = 1\n No similarity = 0 ' n_classes = int((np.max(groundTruth) + 1)) DiceArray = [] for c_i in xrange(1,...
def dice(im1, im2): '\n Computes the Dice coefficient\n ----------\n im1 : boolean array\n im2 : boolean array\n \n If they are not boolean, they will be converted.\n \n -------\n It returns the Dice coefficient as a float on the range [0,1].\n 1: Perfect overlapping \n 0:...
def applyActivationFunction_Sigmoid(inputData): ' inputData is a tensor5D with shape:\n (batchSize,\n Number of feature Maps,\n convolvedImageShape[0],\n convolvedImageShape[1],\n convolvedImageShape[2]) ' outputData = T.nnet.sigmoid(inputData) return outputData
def applyActivationFunction_Tanh(inputData): 'inputData is a tensor5D with shape:\n # (batchSize,\n # Number of feature Maps,\n # convolvedImageShape[0],\n # convolvedImageShape[1],\n # convolvedImageShape[2])' outputData = T.tanh(inputData) return outputData
def applyActivationFunction_ReLU_v1(inputData): ' inputData is a tensor5D with shape:\n # (batchSize,\n # Number of feature Maps,\n # convolvedImageShape[0],\n # convolvedImageShape[1],\n # convolvedImageShape[2]) ' return T.maximum(inputData, 0)
def applyActivationFunction_ReLU_v2(inputData): return T.switch((inputData < 0.0), 0.0, inputData)
def applyActivationFunction_ReLU_v3(inputData): return ((inputData + abs(inputData)) / 2.0)
def applyActivationFunction_ReLU_v4(inputData): return (((T.sgn(inputData) + 1) * inputData) * 0.5)
def applyActivationFunction_LeakyReLU(inputData, leakiness): 'leakiness : float\n Slope for negative input, usually between 0 and 1.\n A leakiness of 0 will lead to the standard rectifier,\n a leakiness of 1 will lead to a linear activation function,\n and any value in between will giv...
def applyActivationFunction_PReLU(inputData, PreluActivations): 'Parametric Rectified Linear Unit.\n It follows:\n `f(x) = alpha * x for x < 0`,\n `f(x) = x for x >= 0`,\n where `alpha` is a learned array with the same shape as x.\n \n - The input is a tensor of shape (batchSize, FeatMaps, xDim,...
def applyActivationFunction_PReLU_v2(inputData, PreluActivations): ' inputData is a tensor5D with shape:\n (batchSize,\n Number of feature Maps,\n convolvedImageShape[0],\n convolvedImageShape[1],\n convolvedImageShape[2]) ' preluActivationsAsRow = PreluActivations.dimshuffle('x', 0, 'x', ...
def applyActivationFunction_PReLU_v3(inputData, PreluActivations): ' inputData is a tensor5D with shape:\n (batchSize,\n Number of feature Maps,\n convolvedImageShape[0],\n convolvedImageShape[1],\n convolvedImageShape[2]) ' preluActivationsAsRow = PreluActivations.dimshuffle('x', 0, 'x', ...
def apply_Dropout(rng, dropoutRate, inputShape, inputData, task): ' Task:\n # 0: Training\n # 1: Validation\n # 2: Testing ' outputData = inputData if (dropoutRate > 0.001): activationRate = (1 - dropoutRate) srng = T.shared_randomstreams.RandomStreams(rng.randint(999999)...
def convolveWithKernel(W, filter_shape, inputSample, inputSampleShape): wReshapedForConv = W.dimshuffle(0, 4, 1, 2, 3) wReshapedForConvShape = (filter_shape[0], filter_shape[4], filter_shape[1], filter_shape[2], filter_shape[3]) inputSampleReshaped = inputSample.dimshuffle(0, 4, 1, 2, 3) inputSampleRe...
def applyBn(numberEpochApplyRolling, inputTrain, inputTest, inputShapeTrain): numberOfChannels = inputShapeTrain[1] gBn_values = np.ones(numberOfChannels, dtype='float32') gBn = theano.shared(value=gBn_values, borrow=True) bBn_values = np.zeros(numberOfChannels, dtype='float32') bBn = theano.share...
def applySoftMax(inputSample, inputSampleShape, numClasses, softmaxTemperature): inputSampleReshaped = inputSample.dimshuffle(0, 2, 3, 4, 1) inputSampleFlattened = inputSampleReshaped.flatten(1) numClassifiedVoxels = ((inputSampleShape[2] * inputSampleShape[3]) * inputSampleShape[4]) firstDimOfinputSa...
def applyBiasToFeatureMaps(bias, featMaps): featMaps = (featMaps + bias.dimshuffle('x', 0, 'x', 'x', 'x')) return featMaps
class parserConfigIni(object): def __init__(_self): _self.networkName = [] def readConfigIniFile(_self, fileName, task): def createModel(): print(' --- Creating model (Reading parameters...)') _self.readModelCreation_params(fileName) def trainModel(): ...
def printUsage(error_type): if (error_type == 1): print(' ** ERROR!!: Few parameters used.') else: print(' ** ERROR!!: Asked to start with an already created network but its name is not specified.') print(' ******** USAGE ******** ') print(' --- argv 1: Name of the configIni file.') ...
def networkSegmentation(argv): if (len(argv) < 2): printUsage(1) sys.exit() configIniName = argv[0] networkModelName = argv[1] startTesting(networkModelName, configIniName) print(' ***************** SEGMENTATION DONE!!! ***************** ')
def pytest_ignore_collect(path, config): 'Ignore paths that would otherwise be collceted by the doctest\n plugin and lead to ImportError due to missing dependencies.\n ' return any((path.fnmatch(ignore) for ignore in ignore_test_paths))
class Initializer(object): 'Base class for parameter tensor initializers.\n\n The :class:`Initializer` class represents a weight initializer used\n to initialize weight parameters in a neural network layer. It should be\n subclassed when implementing new types of weight initializers.\n\n ' def __...
class Normal(Initializer): 'Sample initial weights from the Gaussian distribution.\n\n Initial weight parameters are sampled from N(mean, std).\n\n Parameters\n ----------\n std : float\n Std of initial parameters.\n mean : float\n Mean of initial parameters.\n ' def __init__(...
class Uniform(Initializer): 'Sample initial weights from the uniform distribution.\n\n Parameters are sampled from U(a, b).\n\n Parameters\n ----------\n range : float or tuple\n When std is None then range determines a, b. If range is a float the\n weights are sampled from U(-range, ran...
class Glorot(Initializer): "Glorot weight initialization.\n\n This is also known as Xavier initialization [1]_.\n\n Parameters\n ----------\n initializer : lasagne.init.Initializer\n Initializer used to sample the weights, must accept `std` in its\n constructor to sample from a distribut...
class GlorotNormal(Glorot): 'Glorot with weights sampled from the Normal distribution.\n\n See :class:`Glorot` for a description of the parameters.\n ' def __init__(self, gain=1.0, c01b=False): super(GlorotNormal, self).__init__(Normal, gain, c01b)
class GlorotUniform(Glorot): 'Glorot with weights sampled from the Uniform distribution.\n\n See :class:`Glorot` for a description of the parameters.\n ' def __init__(self, gain=1.0, c01b=False): super(GlorotUniform, self).__init__(Uniform, gain, c01b)
class He(Initializer): "He weight initialization.\n\n Weights are initialized with a standard deviation of\n :math:`\\sigma = gain \\sqrt{\\frac{1}{fan_{in}}}` [1]_.\n\n Parameters\n ----------\n initializer : lasagne.init.Initializer\n Initializer used to sample the weights, must accept `st...
class HeNormal(He): 'He initializer with weights sampled from the Normal distribution.\n\n See :class:`He` for a description of the parameters.\n ' def __init__(self, gain=1.0, c01b=False): super(HeNormal, self).__init__(Normal, gain, c01b)
class HeUniform(He): 'He initializer with weights sampled from the Uniform distribution.\n\n See :class:`He` for a description of the parameters.\n ' def __init__(self, gain=1.0, c01b=False): super(HeUniform, self).__init__(Uniform, gain, c01b)
class Constant(Initializer): 'Initialize weights with constant value.\n\n Parameters\n ----------\n val : float\n Constant value for weights.\n ' def __init__(self, val=0.0): self.val = val def sample(self, shape): return floatX((np.ones(shape) * self.val))
class Sparse(Initializer): 'Initialize weights as sparse matrix.\n\n Parameters\n ----------\n sparsity : float\n Exact fraction of non-zero values per column. Larger values give less\n sparsity.\n std : float\n Non-zero weights are sampled from N(0, std).\n ' def __init__...
class Orthogonal(Initializer): 'Intialize weights as Orthogonal matrix.\n\n Orthogonal matrix initialization [1]_. For n-dimensional shapes where\n n > 2, the n-1 trailing axes are flattened. For convolutional layers, this\n corresponds to the fan-in, so this makes the initialization usable for\n both...
class Layer(object): "\n The :class:`Layer` class represents a single layer of a neural network. It\n should be subclassed when implementing new types of layers.\n\n Because each layer can keep track of the layer(s) feeding into it, a\n network's output :class:`Layer` instance can double as a handle t...
class MergeLayer(Layer): '\n This class represents a layer that aggregates input from multiple layers.\n It should be subclassed when implementing new types of layers that obtain\n their input from multiple layers.\n\n Parameters\n ----------\n incomings : a list of :class:`Layer` instances or t...
def conv_output_length(input_length, filter_size, stride, pad=0): "Helper function to compute the output size of a convolution operation\n\n This function computes the length along a single axis, which corresponds\n to a 1D convolution. It can also be used for convolutions with higher\n dimensionalities ...
class BaseConvLayer(Layer): "\n lasagne.layers.BaseConvLayer(incoming, num_filters, filter_size,\n stride=1, pad=0, untie_biases=False,\n W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),\n nonlinearity=lasagne.nonlinearities.rectify, flip_filters=True,\n n=None, **kwargs)\n\n Convolu...
class Conv1DLayer(BaseConvLayer): "\n lasagne.layers.Conv1DLayer(incoming, num_filters, filter_size, stride=1,\n pad=0, untie_biases=False, W=lasagne.init.GlorotUniform(),\n b=lasagne.init.Constant(0.), nonlinearity=lasagne.nonlinearities.rectify,\n flip_filters=True, convolution=lasagne.theano_extens...
class Conv2DLayer(BaseConvLayer): "\n lasagne.layers.Conv2DLayer(incoming, num_filters, filter_size,\n stride=(1, 1), pad=0, untie_biases=False,\n W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),\n nonlinearity=lasagne.nonlinearities.rectify, flip_filters=True,\n convolution=theano.tens...
class DenseLayer(Layer): '\n lasagne.layers.DenseLayer(incoming, num_units,\n W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),\n nonlinearity=lasagne.nonlinearities.rectify, **kwargs)\n\n A fully connected layer.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance o...
class NINLayer(Layer): '\n lasagne.layers.NINLayer(incoming, num_units, untie_biases=False,\n W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),\n nonlinearity=lasagne.nonlinearities.rectify, **kwargs)\n\n Network-in-network layer.\n Like DenseLayer, but broadcasting across all trailing d...
class Pool2DDNNLayer(Layer): "\n 2D pooling layer\n\n Performs 2D mean- or max-pooling over the two trailing axes of a 4D input\n tensor. This is an alternative implementation which uses\n ``theano.sandbox.cuda.dnn.dnn_pool`` directly.\n\n Parameters\n ----------\n incoming : a :class:`Layer`...
class MaxPool2DDNNLayer(Pool2DDNNLayer): "\n 2D max-pooling layer\n\n Subclass of :class:`Pool2DDNNLayer` fixing ``mode='max'``, provided for\n compatibility to other ``MaxPool2DLayer`` classes.\n " def __init__(self, incoming, pool_size, stride=None, pad=(0, 0), ignore_border=True, **kwargs): ...
class Pool3DDNNLayer(Layer): "\n 3D pooling layer\n\n Performs 3D mean- or max-pooling over the 3 trailing axes of a 5D input\n tensor. This is an alternative implementation which uses\n ``theano.sandbox.cuda.dnn.dnn_pool`` directly.\n\n Parameters\n ----------\n incoming : a :class:`Layer` i...
class MaxPool3DDNNLayer(Pool3DDNNLayer): "\n 3D max-pooling layer\n\n Subclass of :class:`Pool3DDNNLayer` fixing ``mode='max'``, provided for\n consistency to ``MaxPool2DLayer`` classes.\n " def __init__(self, incoming, pool_size, stride=None, pad=(0, 0, 0), ignore_border=True, **kwargs): ...
class Conv2DDNNLayer(BaseConvLayer): "\n lasagne.layers.Conv2DDNNLayer(incoming, num_filters, filter_size,\n stride=(1, 1), pad=0, untie_biases=False,\n W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),\n nonlinearity=lasagne.nonlinearities.rectify, flip_filters=False,\n **kwargs)\n\n ...
class Conv3DDNNLayer(BaseConvLayer): "\n lasagne.layers.Conv3DDNNLayer(incoming, num_filters, filter_size,\n stride=(1, 1, 1), pad=0, untie_biases=False,\n W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.),\n nonlinearity=lasagne.nonlinearities.rectify, flip_filters=False,\n **kwargs)\n\n...
class EmbeddingLayer(Layer): "\n lasagne.layers.EmbeddingLayer(incoming, input_size, output_size,\n W=lasagne.init.Normal(), **kwargs)\n\n A layer for word embeddings. The input should be an integer type\n Tensor variable.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or ...
def get_all_layers(layer, treat_as_input=None): '\n This function gathers all layers below one or more given :class:`Layer`\n instances, including the given layer(s). Its main use is to collect all\n layers of a network just given the output layer(s). The layers are\n guaranteed to be returned in a to...
def get_output(layer_or_layers, inputs=None, **kwargs): "\n Computes the output of the network at one or more given layers.\n Optionally, you can define the input(s) to propagate through the network\n instead of using the input variable(s) associated with the network's\n input layer(s).\n\n Paramet...
def get_output_shape(layer_or_layers, input_shapes=None): '\n Computes the output shape of the network at one or more given layers.\n\n Parameters\n ----------\n layer_or_layers : Layer or list\n the :class:`Layer` instance for which to compute the output\n shapes, or a list of :class:`L...
def get_all_params(layer, **tags): "\n Returns a list of Theano shared variables that parameterize the layer.\n\n This function gathers all parameter variables of all layers below one or\n more given :class:`Layer` instances, including the layer(s) itself. Its\n main use is to collect all parameters o...
def count_params(layer, **tags): "\n This function counts all parameters (i.e., the number of scalar\n values) of all layers below one or more given :class:`Layer` instances,\n including the layer(s) itself.\n\n This is useful to compare the capacity of various network architectures.\n All paramete...
def get_all_param_values(layer, **tags): '\n This function returns the values of the parameters of all layers below one\n or more given :class:`Layer` instances, including the layer(s) itself.\n\n This function can be used in conjunction with set_all_param_values to save\n and restore model parameters...
def set_all_param_values(layer, values, **tags): "\n Given a list of numpy arrays, this function sets the parameters of all\n layers below one or more given :class:`Layer` instances (including the\n layer(s) itself) to the given values.\n\n This function can be used in conjunction with get_all_param_v...
class InputLayer(Layer): '\n This layer holds a symbolic variable that represents a network input. A\n variable can be specified when the layer is instantiated, else it is\n created.\n\n Parameters\n ----------\n shape : tuple of `int` or `None` elements\n The shape of the input. Any elem...
def autocrop(inputs, cropping): "\n Crops the given input arrays.\n\n Cropping takes a sequence of inputs and crops them per-axis in order to\n ensure that their sizes are consistent so that they can be combined\n in an element-wise fashion. If cropping is enabled for a specific axis,\n the minimum...
def autocrop_array_shapes(input_shapes, cropping): "\n Computes the shapes of the given arrays after auto-cropping is applied.\n\n For more information on cropping, see the :func:`autocrop` function\n documentation.\n\n Parameters\n ----------\n input_shapes : the shapes of input arrays prior to...
class ConcatLayer(MergeLayer): '\n Concatenates multiple inputs along the specified axis. Inputs should have\n the same shape except for the dimension specified in axis, which can have\n different sizes.\n\n Parameters\n -----------\n incomings : a list of :class:`Layer` instances or tuples\n ...
class ElemwiseMergeLayer(MergeLayer): '\n This layer performs an elementwise merge of its input layers.\n It requires all input layers to have the same output shape.\n\n Parameters\n ----------\n incomings : a list of :class:`Layer` instances or tuples\n the layers feeding into this layer, o...
class ElemwiseSumLayer(ElemwiseMergeLayer): '\n This layer performs an elementwise sum of its input layers.\n It requires all input layers to have the same output shape.\n\n Parameters\n ----------\n incomings : a list of :class:`Layer` instances or tuples\n the layers feeding into this laye...
class DropoutLayer(Layer): 'Dropout layer\n\n Sets values to zero with probability p. See notes for disabling dropout\n during testing.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or a tuple\n the layer feeding into this layer, or the expected input shape\n p : floa...
class GaussianNoiseLayer(Layer): 'Gaussian noise layer.\n\n Add zero-mean Gaussian noise of given standard deviation to the input [1]_.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or a tuple\n the layer feeding into this layer, or the expected input shape\n sigma :...
class FlattenLayer(Layer): '\n A layer that flattens its input. The leading ``outdim-1`` dimensions of\n the output will have the same shape as the input. The remaining dimensions\n are collapsed into the last dimension.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or a tup...
class ReshapeLayer(Layer): '\n A layer reshaping its input tensor to another tensor of the same total\n number of elements.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or a tuple\n The layer feeding into this layer, or the expected input shape\n\n shape : tuple\n ...
class DimshuffleLayer(Layer): "\n A layer that rearranges the dimension of its input tensor, maintaining\n the same same total number of elements.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or a tuple\n the layer feeding into this layer, or the expected input shape\n\...
class PadLayer(Layer): '\n Pad all dimensions except the first ``batch_ndim`` with ``width``\n zeros on both sides, or with another value specified in ``val``.\n Individual padding for each dimension or edge can be specified\n using a tuple or list of tuples for ``width``.\n\n Parameters\n -----...
class SliceLayer(Layer): '\n Slices the input at a specific axis and at specific indices.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or a tuple\n The layer feeding into this layer, or the expected input shape\n\n indices : int or slice instance\n If an ``int``,...
def sigmoid(x): 'Sigmoid activation function :math:`\\varphi(x) = \\frac{1}{1 + e^{-x}}`\n\n Parameters\n ----------\n x : float32\n The activation (the summed, weighted input of a neuron).\n\n Returns\n -------\n float32 in [0, 1]\n The output of the sigmoid function applied to th...
def softmax(x): 'Softmax activation function\n :math:`\\varphi(\\mathbf{x})_j =\n \\frac{e^{\\mathbf{x}_j}}{\\sum_{k=1}^K e^{\\mathbf{x}_k}}`\n where :math:`K` is the total number of neurons in the layer. This\n activation function gets applied row-wise.\n\n Parameters\n ----------\n x : floa...
def tanh(x): 'Tanh activation function :math:`\\varphi(x) = \\tanh(x)`\n\n Parameters\n ----------\n x : float32\n The activation (the summed, weighted input of a neuron).\n\n Returns\n -------\n float32 in [-1, 1]\n The output of the tanh function applied to the activation.\n '...
class ScaledTanH(object): 'Scaled tanh :math:`\\varphi(x) = \\tanh(\\alpha \\cdot x) \\cdot \\beta`\n\n This is a modified tanh function which allows to rescale both the input and\n the output of the activation.\n\n Scaling the input down will result in decreasing the maximum slope of the\n tanh and a...
def rectify(x): 'Rectify activation function :math:`\\varphi(x) = \\max(0, x)`\n\n Parameters\n ----------\n x : float32\n The activation (the summed, weighted input of a neuron).\n\n Returns\n -------\n float32\n The output of the rectify function applied to the activation.\n '...
class LeakyRectify(object): 'Leaky rectifier :math:`\\varphi(x) = \\max(\\alpha \\cdot x, x)`\n\n The leaky rectifier was introduced in [1]_. Compared to the standard\n rectifier :func:`rectify`, it has a nonzero gradient for negative input,\n which often helps convergence.\n\n Parameters\n -------...
def elu(x): 'Exponential Linear Unit :math:`\\varphi(x) = (x > 0) ? x : e^x - 1`\n\n The Exponential Linear Unit (EUL) was introduced in [1]_. Compared to the\n linear rectifier :func:`rectify`, it has a mean activation closer to zero\n and nonzero gradient for negative input, which can help convergence....
def softplus(x): 'Softplus activation function :math:`\\varphi(x) = \\log(1 + e^x)`\n\n Parameters\n ----------\n x : float32\n The activation (the summed, weighted input of a neuron).\n\n Returns\n -------\n float32\n The output of the softplus function applied to the activation.\...
def linear(x): 'Linear activation function :math:`\\varphi(x) = x`\n\n Parameters\n ----------\n x : float32\n The activation (the summed, weighted input of a neuron).\n\n Returns\n -------\n float32\n The output of the identity applied to the activation.\n ' return x
def binary_crossentropy(predictions, targets): 'Computes the binary cross-entropy between predictions and targets.\n\n .. math:: L = -t \\log(p) - (1 - t) \\log(1 - p)\n\n Parameters\n ----------\n predictions : Theano tensor\n Predictions in (0, 1), such as sigmoidal output of a neural network...
def categorical_crossentropy(predictions, targets): 'Computes the categorical cross-entropy between predictions and targets.\n\n .. math:: L_i = - \\sum_j{t_{i,j} \\log(p_{i,j})}\n\n Parameters\n ----------\n predictions : Theano 2D tensor\n Predictions in (0, 1), such as softmax output of a ne...
def squared_error(a, b): 'Computes the element-wise squared difference between two tensors.\n\n .. math:: L = (p - t)^2\n\n Parameters\n ----------\n a, b : Theano tensor\n The tensors to compute the squared difference between.\n\n Returns\n -------\n Theano tensor\n An expressi...