code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def apply(self, population): """ First determines the number of individuals to be created. Then clones the fittest individuals (=parents), mutates these clones and adds them to the population. """ max_n = population.getMaxNIndividuals() n = population.getIndividua...
First determines the number of individuals to be created. Then clones the fittest individuals (=parents), mutates these clones and adds them to the population.
apply
python
pybrain/pybrain
pybrain/supervised/evolino/filter.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/filter.py
BSD-3-Clause
def __init__(self): """ :key kwargs: See setArgs() method documentation """ SimpleGenomeManipulation.__init__(self) self.mutationVariate = GaussianVariate() self.mutationVariate.alpha = 0.1 self.verbosity = 0
:key kwargs: See setArgs() method documentation
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/gfilter.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/gfilter.py
BSD-3-Clause
def _manipulateValue(self, value): """ Implementation of the abstract method of class SimpleGenomeManipulation Set's the x0 value of the variate to value and takes a new sample value and returns it. """ self.mutationVariate.x0 = value newval = self.mutationVariate...
Implementation of the abstract method of class SimpleGenomeManipulation Set's the x0 value of the variate to value and takes a new sample value and returns it.
_manipulateValue
python
pybrain/pybrain
pybrain/supervised/evolino/gfilter.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/gfilter.py
BSD-3-Clause
def getSortedIndividualList(self): """ Returns a sorted list of all individuals with descending fitness values. """ fitness = self._fitness return sorted(iter(fitness.keys()), key=lambda k:-fitness[k])
Returns a sorted list of all individuals with descending fitness values.
getSortedIndividualList
python
pybrain/pybrain
pybrain/supervised/evolino/gpopulation.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/gpopulation.py
BSD-3-Clause
def getGenome(self): """ Returns the genome created by concatenating the chromosomes supplied by the sub-individuals. """ genome = [] for sub_individual in self._sub_individuals: genome.append(deepcopy(sub_individual.getGenome())) return genome
Returns the genome created by concatenating the chromosomes supplied by the sub-individuals.
getGenome
python
pybrain/pybrain
pybrain/supervised/evolino/individual.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/individual.py
BSD-3-Clause
def __init__(self, genome): """ :key genome: Any kind of nested iteratable container containing floats as leafs """ self.setGenome(genome) self.id = EvolinoSubIndividual._next_id EvolinoSubIndividual._next_id += 1
:key genome: Any kind of nested iteratable container containing floats as leafs
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/individual.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/individual.py
BSD-3-Clause
def _validateGenomeLayer(self, layer): """ Validates the type and state of a layer """ assert isinstance(layer, LSTMLayer) assert not layer.peepholes
Validates the type and state of a layer
_validateGenomeLayer
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def _getGenomeOfLayer(self, layer): """ Returns the genome of a single layer. """ self._validateGenomeLayer(layer) dim = layer.outdim layer_weights = [] connections = self._getInputConnectionsOfLayer(layer) for cell_idx in range(dim): # todo: the ev...
Returns the genome of a single layer.
_getGenomeOfLayer
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def _setGenomeOfLayer(self, layer, weights): """ Sets the genome of a single layer. """ self._validateGenomeLayer(layer) dim = layer.outdim connections = self._getInputConnectionsOfLayer(layer) for cell_idx in range(dim): cell_weights = weights.pop(0) ...
Sets the genome of a single layer.
_setGenomeOfLayer
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def setOutputWeightMatrix(self, W): """ Sets the weight matrix of the output layer's input connection. """ c = self._hid_to_out_connection c.params[:] = W.flatten()
Sets the weight matrix of the output layer's input connection.
setOutputWeightMatrix
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def _getInputConnectionsOfLayer(self, layer): """ Returns a list of all input connections for the layer. """ connections = [] for c in sum(list(self._network.connections.values()), []): if c.outmod is layer: if not isinstance(c, FullConnection): ra...
Returns a list of all input connections for the layer.
_getInputConnectionsOfLayer
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def __init__(self, network): """ :key network: The network to be wrapped """ self.network = network self._output_connection = None self._last_hidden_layer = None self._first_hidden_layer = None self._establishRecurrence()
:key network: The network to be wrapped
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def _establishRecurrence(self): """ Adds a recurrent full connection from the output layer to the first hidden layer. """ network = self.network outlayer = self.getOutputLayer() hid1layer = self.getFirstHiddenLayer() network.addRecurrentConnection(FullConnecti...
Adds a recurrent full connection from the output layer to the first hidden layer.
_establishRecurrence
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def getGenome(self): """ Returns the Genome of the network. See class description for more details. """ weights = [] for layer in self.getHiddenLayers(): if isinstance(layer, LSTMLayer): # if layer is not self._recurrence_layer: wei...
Returns the Genome of the network. See class description for more details.
getGenome
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def setGenome(self, weights): """ Sets the Genome of the network. See class description for more details. """ weights = deepcopy(weights) for layer in self.getHiddenLayers(): if isinstance(layer, LSTMLayer): # if layer is not self._recurrence_layer: ...
Sets the Genome of the network. See class description for more details.
setGenome
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def injectBackproject(self, injection): """ Injects a vector into the recurrent connection. This will be used in the evolino trainingsphase, where the target values need to be backprojected instead of the real output of the net. :key injection: vector of length self.network....
Injects a vector into the recurrent connection. This will be used in the evolino trainingsphase, where the target values need to be backprojected instead of the real output of the net. :key injection: vector of length self.network.outdim
injectBackproject
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def getOutputConnection(self): """ Returns the input connection of the output layer. """ if self._output_connection is None: outlayer = self.getOutputLayer() lastlayer = self.getLastHiddenLayer() for c in self.getConnections(): if c.outmod is outlayer:...
Returns the input connection of the output layer.
getOutputConnection
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def getHiddenLayers(self): """ Returns a list of all hidden layers. """ layers = [] network = self.network for m in network.modules: if m not in network.inmodules and m not in network.outmodules: layers.append(m) return layers
Returns a list of all hidden layers.
getHiddenLayers
python
pybrain/pybrain
pybrain/supervised/evolino/networkwrapper.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/networkwrapper.py
BSD-3-Clause
def __init__(self, individual, subPopulationSize, nCombinations=1, valueInitializer=Randomization(-0.1, 0.1), **kwargs): """ :key individual: A prototype individual which is used to determine the structure of the genome. :key subPopulationSize: integer describing the s...
:key individual: A prototype individual which is used to determine the structure of the genome. :key subPopulationSize: integer describing the size of the subpopulations
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/population.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/population.py
BSD-3-Clause
def getIndividuals(self): """ Returns a set of individuals of type EvolinoIndividual. The individuals are generated on the fly. Note that each subpopulation has the same size. So the number of resulting EvolinoIndividuals is subPopulationSize, since each chromosome of each su...
Returns a set of individuals of type EvolinoIndividual. The individuals are generated on the fly. Note that each subpopulation has the same size. So the number of resulting EvolinoIndividuals is subPopulationSize, since each chromosome of each subpopulation will be assembled once. ...
getIndividuals
python
pybrain/pybrain
pybrain/supervised/evolino/population.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/population.py
BSD-3-Clause
def setIndividualFitness(self, individual, fitness): """ The fitness value is not stored directly inside this population, but is propagated to the subpopulations of all the subindividuals of which the individual consists of. The individual's fitness value is only adjusted if ...
The fitness value is not stored directly inside this population, but is propagated to the subpopulations of all the subindividuals of which the individual consists of. The individual's fitness value is only adjusted if its bigger than the old value. To reset ...
setIndividualFitness
python
pybrain/pybrain
pybrain/supervised/evolino/population.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/population.py
BSD-3-Clause
def __init__(self, chromosome, maxNIndividuals, valueInitializer=Randomization(-0.1, 0.1), **kwargs): """ :key chromosome: The prototype chromosome :key maxNIndividuals: The maximum allowed number of individuals """ SimplePopulation.__init__(self) self._prototype = EvolinoSu...
:key chromosome: The prototype chromosome :key maxNIndividuals: The maximum allowed number of individuals
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/population.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/population.py
BSD-3-Clause
def __init__(self, min_val=0., max_val=1.): """ Initializes the uniform variate with a min and a max value. """ self._min_val = min_val self._max_val = max_val
Initializes the uniform variate with a min and a max value.
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/variate.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/variate.py
BSD-3-Clause
def __init__(self, x0=0., alpha=1.): """ :key x0: Median and mode of the Cauchy distribution :key alpha: scale """ self.x0 = x0 self.alpha = alpha
:key x0: Median and mode of the Cauchy distribution :key alpha: scale
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/variate.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/variate.py
BSD-3-Clause
def __init__(self, x0=0., alpha=1.): """ :key x0: Mean :key alpha: standard deviation """ self.x0 = x0 self.alpha = alpha
:key x0: Mean :key alpha: standard deviation
__init__
python
pybrain/pybrain
pybrain/supervised/evolino/variate.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/evolino/variate.py
BSD-3-Clause
def arrayPermutation(permutation): """Return a permutation function. The function permutes any array as specified by the supplied permutation. """ assert permutation.ndim == 1, \ "Only one dimensional permutaton arrays are supported" def permute(arr): assert arr.ndim == 1, "Only...
Return a permutation function. The function permutes any array as specified by the supplied permutation.
arrayPermutation
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def jacardCoefficient(a, b): """Return the Jacard coefficient of a and b. The jacard coefficient is defined as the overlap between two sets: the sum of all equal elements divided by the size of the sets. Mind that a and b must b in Hamming space, so every element must either be 1 or 0. """ ...
Return the Jacard coefficient of a and b. The jacard coefficient is defined as the overlap between two sets: the sum of all equal elements divided by the size of the sets. Mind that a and b must b in Hamming space, so every element must either be 1 or 0.
jacardCoefficient
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def __init__(self, dim, nPermutations): """Create a hash structure that can hold arrays of size dim and hashes with nPermutations permutations. The number of buckets is dim * nPermutations.""" self.dim = dim self.permutations = array([permutation(dim) ...
Create a hash structure that can hold arrays of size dim and hashes with nPermutations permutations. The number of buckets is dim * nPermutations.
__init__
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def _firstOne(self, arr): """Return the index of the first 1 in the array.""" for i, elem in enumerate(arr): if elem == 1: return i return i + 1
Return the index of the first 1 in the array.
_firstOne
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def _hash(self, item): """Return a hash for item based on the internal permutations. That hash is a tuple of ints. """ self._checkItem(item) result = [] for perm in self._permFuncs: permuted = perm(item) result.append(self._firstOne(permuted)) ...
Return a hash for item based on the internal permutations. That hash is a tuple of ints.
_hash
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def put(self, item, satellite): """Put an item into the hash structure and attach any object satellite to it.""" self._checkItem(item) item = item.astype(bool) bucket = self._hash(item) self.buckets[bucket].append((item, satellite))
Put an item into the hash structure and attach any object satellite to it.
put
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def knn(self, item, k): """Return the k nearest neighbours of the item in the current hash. Mind that the probabilistic nature of the data structure might not return a nearest neighbor at all. """ self._checkItem(item) candidates = self.buckets[self._hash(item)] ...
Return the k nearest neighbours of the item in the current hash. Mind that the probabilistic nature of the data structure might not return a nearest neighbor at all.
knn
python
pybrain/pybrain
pybrain/supervised/knn/lsh/minhash.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/minhash.py
BSD-3-Clause
def __init__(self, dim, omega=4, prob=0.8): """Create a hash for arrays of dimension dim. The hyperspace will be split into hypercubes with a sidelength of omega * sqrt(sqrt(dim)), that is omega * radius. Every point in the dim-dimensional euclidean space will be hashed to its ...
Create a hash for arrays of dimension dim. The hyperspace will be split into hypercubes with a sidelength of omega * sqrt(sqrt(dim)), that is omega * radius. Every point in the dim-dimensional euclidean space will be hashed to its correct bucket with a probability of prob.
__init__
python
pybrain/pybrain
pybrain/supervised/knn/lsh/nearoptimal.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/nearoptimal.py
BSD-3-Clause
def _findHypercube(self, point): """Return where a point lies in what hypercube. The result is a pair of two arrays. The first array is an array of integers that indicate the multidimensional index of the hypercube it is in. The second array is an array of floats, specifying the ...
Return where a point lies in what hypercube. The result is a pair of two arrays. The first array is an array of integers that indicate the multidimensional index of the hypercube it is in. The second array is an array of floats, specifying the coordinates of the point in that hypercube....
_findHypercube
python
pybrain/pybrain
pybrain/supervised/knn/lsh/nearoptimal.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/nearoptimal.py
BSD-3-Clause
def _findLocalBall_noinline(self, point): """Return the index of the ball that the point lies in.""" for i, ball in enumerate(self.gridBalls): distance = point - ball if dot(distance.T, distance) <= self.radiusSquared: return i
Return the index of the ball that the point lies in.
_findLocalBall_noinline
python
pybrain/pybrain
pybrain/supervised/knn/lsh/nearoptimal.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/nearoptimal.py
BSD-3-Clause
def insert(self, point, satellite): """Put a point and its satellite information into the hash structure. """ point = dot(self.projection, point) index = self.findBall(point) self.balls[index].append((point, satellite))
Put a point and its satellite information into the hash structure.
insert
python
pybrain/pybrain
pybrain/supervised/knn/lsh/nearoptimal.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/nearoptimal.py
BSD-3-Clause
def _findKnnCandidates(self, point): """Return a set of candidates that might be nearest neighbours of a query point.""" index = self.findBall(point) logging.debug("Found %i candidates for cNN" % len(self.balls[index])) return self.balls[index]
Return a set of candidates that might be nearest neighbours of a query point.
_findKnnCandidates
python
pybrain/pybrain
pybrain/supervised/knn/lsh/nearoptimal.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/nearoptimal.py
BSD-3-Clause
def knn(self, point, k): """Return the k approximate nearest neighbours of the item in the current hash. Mind that the probabilistic nature of the data structure might not return a nearest neighbor at all and not the nearest neighbour.""" candidates = self._findKnnCandidates(po...
Return the k approximate nearest neighbours of the item in the current hash. Mind that the probabilistic nature of the data structure might not return a nearest neighbor at all and not the nearest neighbour.
knn
python
pybrain/pybrain
pybrain/supervised/knn/lsh/nearoptimal.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/knn/lsh/nearoptimal.py
BSD-3-Clause
def __init__(self, module, dataset=None, learningrate=0.01, lrdecay=1.0, momentum=0., verbose=False, batchlearning=False, weightdecay=0.): """Create a BackpropTrainer to train the specified `module` on the specified `dataset`. The learning rate gives the ratio ...
Create a BackpropTrainer to train the specified `module` on the specified `dataset`. The learning rate gives the ratio of which parameters are changed into the direction of the gradient. The learning rate decreases by `lrdecay`, which is used to to multiply the learning rate after each ...
__init__
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def train(self): """Train the associated module for one epoch.""" assert len(self.ds) > 0, "Dataset cannot be empty." self.module.resetDerivatives() errors = 0 ponderation = 0. shuffledSequences = [] for seq in self.ds._provideSequences(): shuffledSequ...
Train the associated module for one epoch.
train
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def _calcDerivs(self, seq): """Calculate error function and backpropagate output errors to yield the gradient.""" self.module.reset() for sample in seq: self.module.activate(sample[0]) error = 0 ponderation = 0. for offset, sample in reversed(list(enum...
Calculate error function and backpropagate output errors to yield the gradient.
_calcDerivs
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def _checkGradient(self, dataset=None, silent=False): """Numeric check of the computed gradient for debugging purposes.""" if dataset: self.setData(dataset) res = [] for seq in self.ds._provideSequences(): self.module.resetDerivatives() self._calcDeriv...
Numeric check of the computed gradient for debugging purposes.
_checkGradient
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def testOnData(self, dataset=None, verbose=False): """Compute the MSE of the module performance on the given dataset. If no dataset is supplied, the one passed upon Trainer initialization is used.""" if dataset == None: dataset = self.ds dataset.reset() if ve...
Compute the MSE of the module performance on the given dataset. If no dataset is supplied, the one passed upon Trainer initialization is used.
testOnData
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def testOnClassData(self, dataset=None, verbose=False, return_targets=False): """Return winner-takes-all classification output on a given dataset. If no dataset is given, the dataset passed during Trainer initialization is used. If return_targets is set, also return ...
Return winner-takes-all classification output on a given dataset. If no dataset is given, the dataset passed during Trainer initialization is used. If return_targets is set, also return corresponding target classes.
testOnClassData
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def trainUntilConvergence(self, dataset=None, maxEpochs=None, verbose=None, continueEpochs=10, validationProportion=0.25, trainingData=None, validationData=None, convergence_threshold=10): """Train the module on the datase...
Train the module on the dataset until it converges. Return the module with the parameters that gave the minimal validation error. If no dataset is given, the dataset passed during Trainer initialization is used. validationProportion is the ratio of the dataset that is used for ...
trainUntilConvergence
python
pybrain/pybrain
pybrain/supervised/trainers/backprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py
BSD-3-Clause
def __init__(self, evolino_network, dataset, **kwargs): """ :key subPopulationSize: Size of the subpopulations. :key nCombinations: Number of times each chromosome is built into an individual. default=1 :key nParents: Number of individuals left in a subpopulation after select...
:key subPopulationSize: Size of the subpopulations. :key nCombinations: Number of times each chromosome is built into an individual. default=1 :key nParents: Number of individuals left in a subpopulation after selection. :key initialWeightRange: Range of the weights of t...
__init__
python
pybrain/pybrain
pybrain/supervised/trainers/evolino.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/evolino.py
BSD-3-Clause
def gaussian(x, mean, stddev): """ return value of homogenous Gaussian at given vector point x: vector, mean: vector, stddev: scalar """ tmp = -0.5 * sum(((x-mean)/stddev)**2) return np.exp(tmp) / (np.power(2.*np.pi, 0.5*len(x)) * stddev)
return value of homogenous Gaussian at given vector point x: vector, mean: vector, stddev: scalar
gaussian
python
pybrain/pybrain
pybrain/supervised/trainers/mixturedensity.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/mixturedensity.py
BSD-3-Clause
def _calcDerivs(self, seq): """ calculate derivatives assuming we have a Network with a MixtureDensityLayer as output """ assert isinstance(self.module.modulesSorted[-1], MixtureDensityLayer) self.module.reset() for time, sample in enumerate(seq): input = samp...
calculate derivatives assuming we have a Network with a MixtureDensityLayer as output
_calcDerivs
python
pybrain/pybrain
pybrain/supervised/trainers/mixturedensity.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/mixturedensity.py
BSD-3-Clause
def __init__(self, module, etaminus=0.5, etaplus=1.2, deltamin=1.0e-6, deltamax=5.0, delta0=0.1, **kwargs): """ Set up training algorithm parameters, and objects associated with the trainer. :arg module: the module whose parameters should be trained. :key etaminus: factor by which step ...
Set up training algorithm parameters, and objects associated with the trainer. :arg module: the module whose parameters should be trained. :key etaminus: factor by which step width is decreased when overstepping (0.5) :key etaplus: factor by which step width is increased when follo...
__init__
python
pybrain/pybrain
pybrain/supervised/trainers/rprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/rprop.py
BSD-3-Clause
def train(self): """ Train the network for one epoch """ self.module.resetDerivatives() errors = 0 ponderation = 0 for seq in self.ds._provideSequences(): e, p = self._calcDerivs(seq) errors += e ponderation += p if self.verbose: ...
Train the network for one epoch
train
python
pybrain/pybrain
pybrain/supervised/trainers/rprop.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/rprop.py
BSD-3-Clause
def __init__(self, svmunit, dataset, modelfile=None, plot=False): """ Initialize data and unit to be trained, and load the model, if provided. The passed `svmunit` has to be an object of class :class:`SVMUnit` that is going to be trained on the :class:`ClassificationDataSet` o...
Initialize data and unit to be trained, and load the model, if provided. The passed `svmunit` has to be an object of class :class:`SVMUnit` that is going to be trained on the :class:`ClassificationDataSet` object dataset. Compared to FNN training we do not use a test...
__init__
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def train(self, search=False, **kwargs): """ Train the SVM on the dataset. For RBF kernels (the default), an optional meta-parameter search can be performed. :key search: optional name of grid search class to use for RBF kernels: 'GridSearch' or 'GridSearchDOE' :key log2g: base 2 log of the RB...
Train the SVM on the dataset. For RBF kernels (the default), an optional meta-parameter search can be performed. :key search: optional name of grid search class to use for RBF kernels: 'GridSearch' or 'GridSearchDOE' :key log2g: base 2 log of the RBF width parameter :key log2C: base 2 log of ...
train
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def setParams(self, **kwargs): """ Set parameters for SVM training. Apart from the ones below, you can use all parameters defined for the LIBSVM svm_model class, see their documentation. :key searchlog: Save a list of coordinates and the achieved CV accuracy to this file.""" if 'weight...
Set parameters for SVM training. Apart from the ones below, you can use all parameters defined for the LIBSVM svm_model class, see their documentation. :key searchlog: Save a list of coordinates and the achieved CV accuracy to this file.
setParams
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def __init__(self, problem, targets, cmin, cmax, cstep=None, crossval=5, plotflag=False, maxdepth=8, searchlog='gridsearch_results.txt', **params): """ Set up (log) grid search over the two RBF kernel parameters C and gamma. :arg problem: the LIBSVM svm_problem to be optimized, ie. the...
Set up (log) grid search over the two RBF kernel parameters C and gamma. :arg problem: the LIBSVM svm_problem to be optimized, ie. the input and target data :arg targets: unfortunately, the targets used in the problem definition have to be given again here :arg cmin: lower left corner of the l...
__init__
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def search(self): """ iterate successive parameter grid refinement and evaluation; adapted from LIBSVM grid search tool """ jobs = self.calculate_jobs() scores = [] for line in jobs: for (c, g) in line: # run cross-validation for this point sel...
iterate successive parameter grid refinement and evaluation; adapted from LIBSVM grid search tool
search
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def _permute_sequence(self, seq): """ helper function to create a nice sequence of refined regular grids; from LIBSVM grid search tool """ n = len(seq) if n <= 1: return seq mid = int(n / 2) left = self._permute_sequence(seq[:mid]) right = self._permute_sequence(seq[...
helper function to create a nice sequence of refined regular grids; from LIBSVM grid search tool
_permute_sequence
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def _range_f(self, begin, end, step): """ like range, but works on non-integer too; from LIBSVM grid search tool """ seq = [] while 1: if step > 0 and begin > end: break if step < 0 and begin < end: break seq.append(begin) begin = begin + step ...
like range, but works on non-integer too; from LIBSVM grid search tool
_range_f
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def _save_points(self, res): """ save the list of points and corresponding scores into a file """ self.resfile.write("%g, %g, %g\n" % res) logging.info("log2C=%g, log2g=%g, res=%g" % res) self.resfile.flush()
save the list of points and corresponding scores into a file
_save_points
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def search(self, cmin=None, cmax=None): """ iterate parameter grid refinement and evaluation recursively """ if self.depth > self.maxdepth: # maximum search depth reached - finish up best = self.allPts[self.allScores.argmax(), :] logging.info("best log2C=%12.7g, log2g...
iterate parameter grid refinement and evaluation recursively
search
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def refineGrid(self, cmin, cmax): """ given grid boundaries, generate the corresponding DOE pattern from template""" diff = array((cmax - cmin).tolist()*self.nPts).reshape(self.nPts, self.nPars) return self.doepat * diff + array(cmin.tolist()*self.nPts).reshape(self.nPts, self.nPars)
given grid boundaries, generate the corresponding DOE pattern from template
refineGrid
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def _findIndex(self, point): """ determines whether given point already exists in list of all calculated points. raises exception if more than one point is found, returns -1 if no point is found """ if self.depth == 0: return - 1 check = self.allPts[:, 0] == point[0] for i in ran...
determines whether given point already exists in list of all calculated points. raises exception if more than one point is found, returns -1 if no point is found
_findIndex
python
pybrain/pybrain
pybrain/supervised/trainers/svmtrainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/svmtrainer.py
BSD-3-Clause
def setData(self, dataset): """Associate the given dataset with the trainer.""" self.ds = dataset if dataset: assert dataset.indim == self.module.indim assert dataset.outdim == self.module.outdim
Associate the given dataset with the trainer.
setData
python
pybrain/pybrain
pybrain/supervised/trainers/trainer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/trainer.py
BSD-3-Clause
def epsilonCheck(x, epsilon=1e-6): """Checks that x is in (-epsilon, epsilon).""" epsilon = abs(epsilon) return -epsilon < x < epsilon
Checks that x is in (-epsilon, epsilon).
epsilonCheck
python
pybrain/pybrain
pybrain/tests/helpers.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/helpers.py
BSD-3-Clause
def buildAppropriateDataset(module): """ build a sequential dataset with 2 sequences of 3 samples, with arndom input and target values, but the appropriate dimensions to be used on the provided module. """ if module.sequential: d = SequentialDataSet(module.indim, module.outdim) for dummy in ...
build a sequential dataset with 2 sequences of 3 samples, with arndom input and target values, but the appropriate dimensions to be used on the provided module.
buildAppropriateDataset
python
pybrain/pybrain
pybrain/tests/helpers.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/helpers.py
BSD-3-Clause
def gradientCheck(module, tolerance=0.0001, dataset=None): """ check the gradient of a module with a randomly generated dataset, (and, in the case of a network, determine which modules contain incorrect derivatives). """ if module.paramdim == 0: print('Module has no parameters') return True ...
check the gradient of a module with a randomly generated dataset, (and, in the case of a network, determine which modules contain incorrect derivatives).
gradientCheck
python
pybrain/pybrain
pybrain/tests/helpers.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/helpers.py
BSD-3-Clause
def xmlInvariance(n, forwardpasses = 1): """ try writing a network to an xml file, reading it, rewrite it, reread it, and compare if the result looks the same (compare string representation, and forward processing of some random inputs) """ # We only use this for file creation. tmpfile = tempfile.Na...
try writing a network to an xml file, reading it, rewrite it, reread it, and compare if the result looks the same (compare string representation, and forward processing of some random inputs)
xmlInvariance
python
pybrain/pybrain
pybrain/tests/helpers.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/helpers.py
BSD-3-Clause
def testInterface(algo): """ Tests whether the algorithm is properly implementing the correct Blackbox-optimization interface.""" # without any arguments, initialization has to work emptyalgo = algo() try: # but not learning emptyalgo.learn(0) return "Failed to throw missing ...
Tests whether the algorithm is properly implementing the correct Blackbox-optimization interface.
testInterface
python
pybrain/pybrain
pybrain/tests/optimizationtest.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/optimizationtest.py
BSD-3-Clause
def testContinuousInterface(algo): """ Test the specifics for the interface for ContinuousOptimizers """ if not issubclass(algo, bbo.ContinuousOptimizer): return True # list starting points are internally converted to arrays x = algo(sf, xlist2) assert isinstance(x.bestEvaluable, ndarray), '...
Test the specifics for the interface for ContinuousOptimizers
testContinuousInterface
python
pybrain/pybrain
pybrain/tests/optimizationtest.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/optimizationtest.py
BSD-3-Clause
def testMinMax(algo): """ Verify that the algorithm is doing the minimization/maximization consistently. """ if (issubclass(algo, bbo.TopologyOptimizer) or algo == allopts.StochasticHillClimber): # TODO return True xa1[0] = 2 evalx = sf(xa1) amax1 = algo(sf, xa1, minimize=F...
Verify that the algorithm is doing the minimization/maximization consistently.
testMinMax
python
pybrain/pybrain
pybrain/tests/optimizationtest.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/optimizationtest.py
BSD-3-Clause
def testImport(module_name): """Tell wether a module can be imported. This function has a cache, so modules are only tested once on importability. """ try: return testImport.cache[module_name] except KeyError: try: __import__(module_name) except ImportError: ...
Tell wether a module can be imported. This function has a cache, so modules are only tested once on importability.
testImport
python
pybrain/pybrain
pybrain/tests/runtests.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/runtests.py
BSD-3-Clause
def missingDependencies(target_module): """Returns a list of dependencies of the module that the current interpreter cannot import. This does not inspect the code, but instead check for a list of strings called _dependencies in the target_module. This list should contain module names that the modul...
Returns a list of dependencies of the module that the current interpreter cannot import. This does not inspect the code, but instead check for a list of strings called _dependencies in the target_module. This list should contain module names that the module depends on.
missingDependencies
python
pybrain/pybrain
pybrain/tests/runtests.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/runtests.py
BSD-3-Clause
def getSubDirectories(testdir): """Recursively builds a list of all subdirectories in the test suite.""" subdirs = [os.path.join(testdir,d) for d in filter(os.path.isdir,[os.path.join(testdir,dd) for dd in os.listdir(testdir)])] for d in copy(subdirs): subdirs.extend(getSubDirect...
Recursively builds a list of all subdirectories in the test suite.
getSubDirectories
python
pybrain/pybrain
pybrain/tests/runtests.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/runtests.py
BSD-3-Clause
def make_test_suite(): """Load unittests placed in pybrain/tests/unittests, then return a TestSuite object of those.""" # [...]/pybrain/pybrain [cut] /tests/runtests.py path = os.path.abspath(__file__).rsplit(os.sep+'tests', 1)[0] sys.path.append(path.rstrip('pybrain')) top_testdir = os.path.j...
Load unittests placed in pybrain/tests/unittests, then return a TestSuite object of those.
make_test_suite
python
pybrain/pybrain
pybrain/tests/runtests.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/runtests.py
BSD-3-Clause
def runModuleTestSuite(module): """Runs a test suite for all local tests.""" suite = TestSuite([TestLoader().loadTestsFromModule(module)]) # Add local doctests optionflags = ELLIPSIS | NORMALIZE_WHITESPACE | REPORT_ONLY_FIRST_FAILURE | IGNORE_EXCEPTION_DETAIL try: suite.addTest(DocTestSuit...
Runs a test suite for all local tests.
runModuleTestSuite
python
pybrain/pybrain
pybrain/tests/testsuites.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/testsuites.py
BSD-3-Clause
def buildSharedCrossedNetwork(): """ build a network with shared connections. Two hidden modules are symmetrically linked, but to a different input neuron than the output neuron. The weights are random. """ N = FeedForwardNetwork('shared-crossed') h = 1 a = LinearLayer(2, name = 'a') b = Lin...
build a network with shared connections. Two hidden modules are symmetrically linked, but to a different input neuron than the output neuron. The weights are random.
buildSharedCrossedNetwork
python
pybrain/pybrain
pybrain/tests/unittests/structure/connections/test_shared_connections.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/unittests/structure/connections/test_shared_connections.py
BSD-3-Clause
def buildSimpleBorderSwipingNet(size = 3, dim = 3, hsize = 1, predefined = {}): """ build a simple swiping network,of given size and dimension, using linear inputs and output""" # assuming identical size in all dimensions dims = tuple([size]*dim) # also includes one dimension for the swipes hdims = ...
build a simple swiping network,of given size and dimension, using linear inputs and output
buildSimpleBorderSwipingNet
python
pybrain/pybrain
pybrain/tests/unittests/structure/networks/test_borderswipingnetwork.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/unittests/structure/networks/test_borderswipingnetwork.py
BSD-3-Clause
def buildCyclicNetwork(recurrent): """ build a cyclic network with 4 modules :key recurrent: make one of the connections recurrent """ Network = RecurrentNetwork if recurrent else FeedForwardNetwork N = Network('cyc') a = LinearLayer(1, name='a') b = LinearLayer(2, name='b') c = LinearLayer...
build a cyclic network with 4 modules :key recurrent: make one of the connections recurrent
buildCyclicNetwork
python
pybrain/pybrain
pybrain/tests/unittests/structure/networks/test_cyclic_network.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/unittests/structure/networks/test_cyclic_network.py
BSD-3-Clause
def buildMixedNestedNetwork(): """ build a nested network with the inner one being a ffn and the outer one being recurrent. """ N = RecurrentNetwork('outer') a = LinearLayer(1, name='a') b = LinearLayer(2, name='b') c = buildNetwork(2, 3, 1) c.name = 'inner' N.addInputModule(a) N.addModu...
build a nested network with the inner one being a ffn and the outer one being recurrent.
buildMixedNestedNetwork
python
pybrain/pybrain
pybrain/tests/unittests/structure/networks/test_nested_ffn_and_rnn.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/unittests/structure/networks/test_nested_ffn_and_rnn.py
BSD-3-Clause
def buildDecomposableNetwork(): """ three hidden neurons, with 2 in- and 2 outconnections each. """ n = buildNetwork(2, 3, 2, bias = False) ndc = NeuronDecomposableNetwork.convertNormalNetwork(n) # set all the weights to 1 ndc._setParameters(ones(12)) return ndc
three hidden neurons, with 2 in- and 2 outconnections each.
buildDecomposableNetwork
python
pybrain/pybrain
pybrain/tests/unittests/structure/networks/test_network_decomposition.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/unittests/structure/networks/test_network_decomposition.py
BSD-3-Clause
def buildSomeConnections(modules): """ add a connection from every second to every third module """ res = [] for i in range(len(modules)//3-1): res.append(FullConnection(modules[i*2], modules[i*3+1])) return res
add a connection from every second to every third module
buildSomeConnections
python
pybrain/pybrain
pybrain/tests/unittests/structure/networks/test_network_sort.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tests/unittests/structure/networks/test_network_sort.py
BSD-3-Clause
def convertSequenceToTimeWindows(DSseq, NewClass, winsize): """ Converts a sequential classification dataset into time windows of fixed length. Assumes the correct class is given at the last timestep of each sequence. Incomplete windows at the sequence end are pruned. No overlap between windows. :arg D...
Converts a sequential classification dataset into time windows of fixed length. Assumes the correct class is given at the last timestep of each sequence. Incomplete windows at the sequence end are pruned. No overlap between windows. :arg DSseq: the sequential data set to cut up :arg winsize: size of t...
convertSequenceToTimeWindows
python
pybrain/pybrain
pybrain/tools/datasettools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/datasettools.py
BSD-3-Clause
def windowSequenceEval(DS, winsz, result): """ take results of a window-based classification and assess/plot them on the sequence WARNING: NOT TESTED!""" si_old = 0 idx = 0 x = [] y = [] seq_res = [] for i, si in enumerate(DS['sequence_index'][1:].astype(int)): tar = DS['target']...
take results of a window-based classification and assess/plot them on the sequence WARNING: NOT TESTED!
windowSequenceEval
python
pybrain/pybrain
pybrain/tools/datasettools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/datasettools.py
BSD-3-Clause
def normalize(self, ds, field='input'): """ normalize dataset or vector wrt. to stored min and max """ if self.dim <= 0: raise IndexError("No normalization parameters defined!") dsdim = ds[field].shape[1] if self.dim != dsdim: raise IndexError("Dimension of normal...
normalize dataset or vector wrt. to stored min and max
normalize
python
pybrain/pybrain
pybrain/tools/datasettools.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/datasettools.py
BSD-3-Clause
def getAllFilesIn(dir, tag='', extension='.pickle'): """ return a list of all filenames in the specified directory (with the given tag and/or extension). """ allfiles = os.listdir(dir) res = [] for f in allfiles: if f[-len(extension):] == extension and f[:len(tag)] == tag: res.ap...
return a list of all filenames in the specified directory (with the given tag and/or extension).
getAllFilesIn
python
pybrain/pybrain
pybrain/tools/filehandling.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/filehandling.py
BSD-3-Clause
def selectSome(strings, requiredsubstrings=[], requireAll=True): """ Filter the list of strings to only contain those that have at least one of the required substrings. """ if len(requiredsubstrings) == 0: return strings res = [] for s in strings: if requireAll: bad = Fal...
Filter the list of strings to only contain those that have at least one of the required substrings.
selectSome
python
pybrain/pybrain
pybrain/tools/filehandling.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/filehandling.py
BSD-3-Clause
def pickleReadDict(name): """ pickle-read a (default: dictionnary) variable from a file """ try: f = open(name + '.pickle') val = pickle.load(f) f.close() except Exception as e: print(('Nothing read from', name, ':', str(e))) val = {} return val
pickle-read a (default: dictionnary) variable from a file
pickleReadDict
python
pybrain/pybrain
pybrain/tools/filehandling.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/filehandling.py
BSD-3-Clause
def calcFisherInformation(sigma, invSigma=None, factorSigma=None): """ Compute the exact Fisher Information Matrix of a Gaussian distribution, given its covariance matrix. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: fa...
Compute the exact Fisher Information Matrix of a Gaussian distribution, given its covariance matrix. Returns a list of the diagonal blocks.
calcFisherInformation
python
pybrain/pybrain
pybrain/tools/fisher.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/fisher.py
BSD-3-Clause
def calcInvFisher(sigma, invSigma=None, factorSigma=None): """ Efficiently compute the exact inverse of the FIM of a Gaussian. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = cholesky(sigma) dim = sigma.shape...
Efficiently compute the exact inverse of the FIM of a Gaussian. Returns a list of the diagonal blocks.
calcInvFisher
python
pybrain/pybrain
pybrain/tools/fisher.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/fisher.py
BSD-3-Clause
def semilinear(x): """ This function ensures that the values of the array are always positive. It is x+1 for x=>0 and exp(x) for x<0. """ try: # assume x is a numpy array shape = x.shape x.flatten() x = x.tolist() except AttributeError: # no, it wasn't: build ...
This function ensures that the values of the array are always positive. It is x+1 for x=>0 and exp(x) for x<0.
semilinear
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def semilinearPrime(x): """ This function is the first derivative of the semilinear function (above). It is needed for the backward pass of the module. """ try: # assume x is a numpy array shape = x.shape x.flatten() x = x.tolist() except AttributeError: # no,...
This function is the first derivative of the semilinear function (above). It is needed for the backward pass of the module.
semilinearPrime
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def ranking(R): """ Produces a linear ranking of the values in R. """ l = sorted(list(enumerate(R)), cmp=lambda a, b: cmp(a[1], b[1])) l = sorted(list(enumerate(l)), cmp=lambda a, b: cmp(a[1], b[1])) return array([kv[0] for kv in l])
Produces a linear ranking of the values in R.
ranking
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def expln(x): """ This continuous function ensures that the values of the array are always positive. It is ln(x+1)+1 for x >= 0 and exp(x) for x < 0. """ def f(val): if val < 0: # exponential function for x < 0 return exp(val) else: # natural log funct...
This continuous function ensures that the values of the array are always positive. It is ln(x+1)+1 for x >= 0 and exp(x) for x < 0.
expln
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def explnPrime(x): """ This function is the first derivative of the expln function (above). It is needed for the backward pass of the module. """ def f(val): if val < 0: # exponential function for x<0 return exp(val) else: # linear function for x>=0 ...
This function is the first derivative of the expln function (above). It is needed for the backward pass of the module.
explnPrime
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def multivariateNormalPdf(z, x, sigma): """ The pdf of a multivariate normal distribution (not in scipy). The sample z and the mean x should be 1-dim-arrays, and sigma a square 2-dim-array. """ assert len(z.shape) == 1 and len(x.shape) == 1 and len(x) == len(z) and sigma.shape == (len(x), len(z)) tmp = ...
The pdf of a multivariate normal distribution (not in scipy). The sample z and the mean x should be 1-dim-arrays, and sigma a square 2-dim-array.
multivariateNormalPdf
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def simpleMultivariateNormalPdf(z, detFactorSigma): """ Assuming z has been transformed to a mean of zero and an identity matrix of covariances. Needs to provide the determinant of the factorized (real) covariance matrix. """ dim = len(z) return exp(-0.5 * dot(z, z)) / (power(2.0 * pi, dim / 2.) * detFa...
Assuming z has been transformed to a mean of zero and an identity matrix of covariances. Needs to provide the determinant of the factorized (real) covariance matrix.
simpleMultivariateNormalPdf
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def multivariateCauchy(mu, sigma, onlyDiagonal=True): """ Generates a sample according to a given multivariate Cauchy distribution. """ if not onlyDiagonal: u, s, d = svd(sigma) coeffs = sqrt(s) else: coeffs = diag(sigma) r = rand(len(mu)) res = coeffs * tan(pi * (r - 0.5)) ...
Generates a sample according to a given multivariate Cauchy distribution.
multivariateCauchy
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def approxChiFunction(dim): """ Returns Chi (expectation of the length of a normal random vector) approximation according to: Ostermeier 1997. """ dim = float(dim) return sqrt(dim) * (1 - 1 / (4 * dim) + 1 / (21 * dim ** 2))
Returns Chi (expectation of the length of a normal random vector) approximation according to: Ostermeier 1997.
approxChiFunction
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def sqrtm(M): """ Returns the symmetric semi-definite positive square root of a matrix. """ r = real_if_close(expm(0.5 * logm(M)), 1e-8) return (r + r.T) / 2
Returns the symmetric semi-definite positive square root of a matrix.
sqrtm
python
pybrain/pybrain
pybrain/tools/functions.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/functions.py
BSD-3-Clause
def __init__(self, min_params, max_params, n_steps=7, **kwargs): """ :key min_params: Tuple of two elements specifying the minima of the two metaparameters :key max_params: Tuple of two elements specifying the minima of the two metaparame...
:key min_params: Tuple of two elements specifying the minima of the two metaparameters :key max_params: Tuple of two elements specifying the minima of the two metaparameters :key max_param: Tuple of two elements, specifying the numb...
__init__
python
pybrain/pybrain
pybrain/tools/gridsearch.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/gridsearch.py
BSD-3-Clause
def search(self): """ The main search method, that validates all calculated metaparameter settings (=jobs) by calling the abstract _validate() method. After enough new jobs were validated in order to visualize a grid, the _onStep() callback method is called. """ ...
The main search method, that validates all calculated metaparameter settings (=jobs) by calling the abstract _validate() method. After enough new jobs were validated in order to visualize a grid, the _onStep() callback method is called.
search
python
pybrain/pybrain
pybrain/tools/gridsearch.py
https://github.com/pybrain/pybrain/blob/master/pybrain/tools/gridsearch.py
BSD-3-Clause