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 assignClasses(self): """Ensure that the class field is properly defined and nClasses is set. """ if len(self['class']) < len(self['target']): if self.outdim > 1: raise IndexError('Classes and 1-of-k representation out of sync!') else: s...
Ensure that the class field is properly defined and nClasses is set.
assignClasses
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def getClass(self, idx): """Return the label of given class.""" try: return self.class_labels[idx] except IndexError: print("error: classes not defined yet!")
Return the label of given class.
getClass
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def _convertToOneOfMany(self, bounds=(0, 1)): """Converts the target classes to a 1-of-k representation, retaining the old targets as a field `class`. To supply specific bounds, set the `bounds` parameter, which consists of target values for non-membership and membership.""" if ...
Converts the target classes to a 1-of-k representation, retaining the old targets as a field `class`. To supply specific bounds, set the `bounds` parameter, which consists of target values for non-membership and membership.
_convertToOneOfMany
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def splitByClass(self, cls_select): """Produce two new datasets, the first one comprising only the class selected (0..nClasses-1), the second one containing the remaining samples.""" leftIndices, dummy = where(self['class'] == cls_select) rightIndices, dummy = where(self['class']...
Produce two new datasets, the first one comprising only the class selected (0..nClasses-1), the second one containing the remaining samples.
splitByClass
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def castToRegression(self, values): """Converts data set into a SupervisedDataSet for regression. Classes are used as indices into the value array given.""" regDs = SupervisedDataSet(self.indim, 1) fields = self.getFieldNames() fields.remove('target') for f in fields: ...
Converts data set into a SupervisedDataSet for regression. Classes are used as indices into the value array given.
castToRegression
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def __init__(self, inp, target, nb_classes=0, class_labels=None): """Initialize an empty dataset. `inp` is used to specify the dimensionality of the input. While the number of targets is given by implicitly by the training samples, it can also be set explicity by `nb_classes`. To give t...
Initialize an empty dataset. `inp` is used to specify the dimensionality of the input. While the number of targets is given by implicitly by the training samples, it can also be set explicity by `nb_classes`. To give the classes names, supply an iterable of strings as `class_labels`.
__init__
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def stratifiedSplit(self, testfrac=0.15, evalfrac=0): """Stratified random split of a sequence data set, i.e. (almost) same proportion of sequences in each class for all fragments. Return (training, test[, eval]) data sets. The parameter `testfrac` specifies the fraction of total sequen...
Stratified random split of a sequence data set, i.e. (almost) same proportion of sequences in each class for all fragments. Return (training, test[, eval]) data sets. The parameter `testfrac` specifies the fraction of total sequences in the test dataset, while `evalfrac` specifies the f...
stratifiedSplit
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def getSequenceClass(self, index=None): """Return a flat array (or single scalar) comprising one class per sequence as given by last pattern in each sequence.""" lastSeq = self.getNumSequences() - 1 if index is None: classidx = r_[self['sequence_index'].astype(int)[1:, 0] - 1...
Return a flat array (or single scalar) comprising one class per sequence as given by last pattern in each sequence.
getSequenceClass
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def removeSequence(self, index): """Remove sequence (including class field) from the dataset.""" self.assignClasses() self.linkFields(['input', 'target', 'class']) SequentialDataSet.removeSequence(self, index) self.unlinkFields(['class'])
Remove sequence (including class field) from the dataset.
removeSequence
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def save_netcdf(self, flo, **kwargs): """Save the current dataset to the given file as a netCDF dataset to be used with Alex Graves nnl_ndim program in task="sequence classification" mode.""" # make sure classes are defined properly assert len(self['class']) == len(self['target']...
Save the current dataset to the given file as a netCDF dataset to be used with Alex Graves nnl_ndim program in task="sequence classification" mode.
save_netcdf
python
pybrain/pybrain
pybrain/datasets/classification.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/classification.py
BSD-3-Clause
def setVectorFormat(self, vf): """Determine which format to use for returning vectors. Use the property vectorformat. :key type: possible types are '1d', '2d', 'list' '1d' - example: array([1,2,3]) '2d' - example: array([[1,2,3]]) 'list' - example...
Determine which format to use for returning vectors. Use the property vectorformat. :key type: possible types are '1d', '2d', 'list' '1d' - example: array([1,2,3]) '2d' - example: array([[1,2,3]]) 'list' - example: [1,2,3] 'none' - no conv...
setVectorFormat
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def _convertArray2d(self, vector, column=False): """Converts the incoming `vector` to a 2d vector with shape (1,x), or (x,1) if `column` is set, where x is the number of elements.""" a = asarray(vector) sh = a.shape # also reshape scalar values to 2d-index if len(sh) == 0...
Converts the incoming `vector` to a 2d vector with shape (1,x), or (x,1) if `column` is set, where x is the number of elements.
_convertArray2d
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def addField(self, label, dim): """Add a field to the dataset. A field consists of a string `label` and a numpy ndarray of dimension `dim`.""" self.data[label] = zeros((0, dim), float) self.endmarker[label] = 0
Add a field to the dataset. A field consists of a string `label` and a numpy ndarray of dimension `dim`.
addField
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def setField(self, label, arr): """Set the given array `arr` as the new array of field `label`,""" as_arr = asarray(arr) self.data[label] = as_arr self.endmarker[label] = as_arr.shape[0]
Set the given array `arr` as the new array of field `label`,
setField
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def linkFields(self, linklist): """Link the length of several fields given by the list of strings `linklist`.""" length = self[linklist[0]].shape[0] for l in linklist: if self[l].shape[0] != length: raise OutOfSyncError self.link = linklist
Link the length of several fields given by the list of strings `linklist`.
linkFields
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def unlinkFields(self, unlinklist=None): """Remove fields from the link list or clears link given by the list of string `linklist`. This method has no effect if fields are not linked.""" link = self.link if unlinklist is not None: for l in unlinklist: ...
Remove fields from the link list or clears link given by the list of string `linklist`. This method has no effect if fields are not linked.
unlinkFields
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def getDimension(self, label): """Return the dimension/number of columns for the field given by `label`.""" try: dim = self.data[label].shape[1] except KeyError: raise KeyError('dataset field %s not found.' % label) return dim
Return the dimension/number of columns for the field given by `label`.
getDimension
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def getLength(self): """Return the length of the linked data fields. If no linked fields exist, return the length of the longest field.""" if self.link == []: try: length = self.endmarker[max(self.endmarker)] except ValueError: return 0 ...
Return the length of the linked data fields. If no linked fields exist, return the length of the longest field.
getLength
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def _resizeArray(self, a): """Increase the buffer size. It should always be one longer than the current sequence length and double on every growth step.""" shape = list(a.shape) shape[0] = (shape[0] + 1) * 2 return resize(a, shape)
Increase the buffer size. It should always be one longer than the current sequence length and double on every growth step.
_resizeArray
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def _appendUnlinked(self, label, row): """Append `row` to the field array with the given `label`. Do not call this function from outside, use ,append() instead. Automatically casts vector to a 2d (or higher) shape.""" if self.data[label].shape[0] <= self.endmarker[label]: se...
Append `row` to the field array with the given `label`. Do not call this function from outside, use ,append() instead. Automatically casts vector to a 2d (or higher) shape.
_appendUnlinked
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def append(self, label, row): """Append `row` to the array given by `label`. If the field is linked with others, the function throws an `OutOfSyncError` because all linked fields always have to have the same length. If you want to add a row to all linked fields, use appendLink i...
Append `row` to the array given by `label`. If the field is linked with others, the function throws an `OutOfSyncError` because all linked fields always have to have the same length. If you want to add a row to all linked fields, use appendLink instead.
append
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def appendLinked(self, *args): """Add rows to all linked fields at once.""" assert len(args) == len(self.link) for i, l in enumerate(self.link): self._appendUnlinked(l, args[i])
Add rows to all linked fields at once.
appendLinked
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def getLinked(self, index=None): """Access the dataset randomly or sequential. If called with `index`, the appropriate line consisting of all linked fields is returned and the internal marker is set to the next line. Otherwise the marked line is returned and the marker is moved to the ...
Access the dataset randomly or sequential. If called with `index`, the appropriate line consisting of all linked fields is returned and the internal marker is set to the next line. Otherwise the marked line is returned and the marker is moved to the next line.
getLinked
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def getField(self, label): """Return the entire field given by `label` as an array or list, depending on user settings.""" # Note: label_data should always be a np.array, so this will never # actually clone a list (performances are O(1)). label_data = self.data[label][:self.endma...
Return the entire field given by `label` as an array or list, depending on user settings.
getField
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def convertField(self, label, newtype): """Convert the given field to a different data type.""" try: self.setField(label, self.data[label].astype(newtype)) except KeyError: raise KeyError('convertField: dataset field %s not found.' % label)
Convert the given field to a different data type.
convertField
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def clear(self, unlinked=False): """Clear the dataset. If linked fields exist, only the linked fields will be deleted unless `unlinked` is set to True. If no fields are linked, all data will be deleted.""" self.reset() keys = self.link if keys == [] or unlinked: ...
Clear the dataset. If linked fields exist, only the linked fields will be deleted unless `unlinked` is set to True. If no fields are linked, all data will be deleted.
clear
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def reconstruct(cls, filename): """Read an incomplete data set (option arraysonly) into the given one. """ # FIXME: Obsolete! Kept here because of some old files... obj = cls(1, 1) for key, val in pickle.load(file(filename)).items(): obj.setField(key, val) return obj
Read an incomplete data set (option arraysonly) into the given one.
reconstruct
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def save_pickle(self, flo, protocol=0, compact=False): """Save data set as pickle, removing empty space if desired.""" if compact: # remove padding of zeros for each field for field in self.getFieldNames(): temp = self[field][0:self.endmarker[field] + 1, :] ...
Save data set as pickle, removing empty space if desired.
save_pickle
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def batches(self, label, n, permutation=None): """Yield batches of the size of n from the dataset. A single batch is an array of with dim columns and n rows. The last batch is possibly smaller. If permutation is given, batches are yielded in the corresponding order.""" ...
Yield batches of the size of n from the dataset. A single batch is an array of with dim columns and n rows. The last batch is possibly smaller. If permutation is given, batches are yielded in the corresponding order.
batches
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def randomBatches(self, label, n): """Like .batches(), but the order is random.""" permutation = random.shuffle(list(range(len(self)))) return self.batches(label, n, permutation)
Like .batches(), but the order is random.
randomBatches
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def replaceNansByMeans(self): """Replace all not-a-number entries in the dataset by the means of the corresponding column.""" for d in self.data.values(): means = scipy.nansum(d[:self.getLength()], axis=0) / self.getLength() for i in range(self.getLength()): ...
Replace all not-a-number entries in the dataset by the means of the corresponding column.
replaceNansByMeans
python
pybrain/pybrain
pybrain/datasets/dataset.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/dataset.py
BSD-3-Clause
def addSample(self, inp, target, importance=None): """ adds a new sample consisting of input, target and importance. :arg inp: the input of the sample :arg target: the target of the sample :key importance: the importance of the sample. If left None, the impo...
adds a new sample consisting of input, target and importance. :arg inp: the input of the sample :arg target: the target of the sample :key importance: the importance of the sample. If left None, the importance will be set to 1.0
addSample
python
pybrain/pybrain
pybrain/datasets/importance.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/importance.py
BSD-3-Clause
def _evaluateSequence(self, f, seq, verbose = False): """ return the importance-ponderated MSE over one sequence. """ totalError = 0 ponderation = 0. for input, target, importance in seq: res = f(input) e = 0.5 * dot(importance.flatten(), ((target-res).flatten()**...
return the importance-ponderated MSE over one sequence.
_evaluateSequence
python
pybrain/pybrain
pybrain/datasets/importance.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/importance.py
BSD-3-Clause
def __init__(self, statedim, actiondim): """ initialize the reinforcement dataset, add the 3 fields state, action and reward, and create an index marker. This class is basically a wrapper function that renames the fields of SupervisedDataSet into the more common reinforcement ...
initialize the reinforcement dataset, add the 3 fields state, action and reward, and create an index marker. This class is basically a wrapper function that renames the fields of SupervisedDataSet into the more common reinforcement learning names. Instead of 'episodes' though, we de...
__init__
python
pybrain/pybrain
pybrain/datasets/reinforcement.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/reinforcement.py
BSD-3-Clause
def newSequence(self): """Marks the beginning of a new sequence. this function does nothing if called at the very start of the data set. Otherwise, it starts a new sequence. Empty sequences are not allowed, and an EmptySequenceError exception will be raised.""" length = self.getL...
Marks the beginning of a new sequence. this function does nothing if called at the very start of the data set. Otherwise, it starts a new sequence. Empty sequences are not allowed, and an EmptySequenceError exception will be raised.
newSequence
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def _getSequenceField(self, index, field): """Return a sequence of one single field given by `field` and indexed by `index`.""" seq = ravel(self.getField('sequence_index')) if len(seq) == index + 1: # user wants to access the last sequence, return until end of data ...
Return a sequence of one single field given by `field` and indexed by `index`.
_getSequenceField
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def endOfSequence(self, index): """Return True if the marker was moved over the last element of sequence `index`, False otherwise. Mostly used like .endOfData() with while loops.""" seq = ravel(self.getField('sequence_index')) if len(seq) == index + 1: # user wants t...
Return True if the marker was moved over the last element of sequence `index`, False otherwise. Mostly used like .endOfData() with while loops.
endOfSequence
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def gotoSequence(self, index): """Move the internal marker to the beginning of sequence `index`.""" try: self.index = ravel(self.getField('sequence_index'))[index] except IndexError: raise IndexError('sequence does not exist')
Move the internal marker to the beginning of sequence `index`.
gotoSequence
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def getCurrentSequence(self): """Return the current sequence, according to the marker position.""" seq = ravel(self.getField('sequence_index')) return len(seq) - sum(seq > self.index) - 1
Return the current sequence, according to the marker position.
getCurrentSequence
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def getSequenceLength(self, index): """Return the length of the given sequence. If `index` is pointing to the last sequence, the sequence is considered to go until the end of the dataset.""" seq = ravel(self.getField('sequence_index')) if len(seq) == index + 1: # user...
Return the length of the given sequence. If `index` is pointing to the last sequence, the sequence is considered to go until the end of the dataset.
getSequenceLength
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def removeSequence(self, index): """Remove the `index`'th sequence from the dataset and places the marker to the sample following the removed sequence.""" if index >= self.getNumSequences(): # sequence doesn't exist, raise exception raise IndexError('sequence does not exi...
Remove the `index`'th sequence from the dataset and places the marker to the sample following the removed sequence.
removeSequence
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def evaluateModuleMSE(self, module, averageOver=1, **args): """Evaluate the predictions of a module on a sequential dataset and return the MSE (potentially average over a number of epochs).""" res = 0. for dummy in range(averageOver): ponderation = 0. totalError =...
Evaluate the predictions of a module on a sequential dataset and return the MSE (potentially average over a number of epochs).
evaluateModuleMSE
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def splitWithProportion(self, proportion=0.5): """Produce two new datasets, each containing a part of the sequences. The first dataset will have a fraction given by `proportion` of the dataset.""" l = self.getNumSequences() leftIndices = sample(list(range(l)), int(l * proportion...
Produce two new datasets, each containing a part of the sequences. The first dataset will have a fraction given by `proportion` of the dataset.
splitWithProportion
python
pybrain/pybrain
pybrain/datasets/sequential.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/sequential.py
BSD-3-Clause
def __init__(self, inp, target): """Initialize an empty supervised dataset. Pass `inp` and `target` to specify the dimensions of the input and target vectors.""" DataSet.__init__(self) if isscalar(inp): # add input and target fields and link them self.add...
Initialize an empty supervised dataset. Pass `inp` and `target` to specify the dimensions of the input and target vectors.
__init__
python
pybrain/pybrain
pybrain/datasets/supervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py
BSD-3-Clause
def setField(self, label, arr, **kwargs): """Set the given array `arr` as the new array of the field specfied by `label`.""" DataSet.setField(self, label, arr, **kwargs) # refresh dimensions, in case any of these fields were modified if label == 'input': self.indim = ...
Set the given array `arr` as the new array of the field specfied by `label`.
setField
python
pybrain/pybrain
pybrain/datasets/supervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py
BSD-3-Clause
def evaluateMSE(self, f, **args): """Evaluate the predictions of a function on the dataset and return the Mean Squared Error, incorporating importance.""" ponderation = 0. totalError = 0 for seq in self._provideSequences(): e, p = self._evaluateSequence(f, seq, **args...
Evaluate the predictions of a function on the dataset and return the Mean Squared Error, incorporating importance.
evaluateMSE
python
pybrain/pybrain
pybrain/datasets/supervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py
BSD-3-Clause
def _evaluateSequence(self, f, seq, verbose = False): """Return the ponderated MSE over one sequence.""" totalError = 0. ponderation = 0. for input, target in seq: res = f(input) e = 0.5 * sum((target-res).flatten()**2) totalError += e pond...
Return the ponderated MSE over one sequence.
_evaluateSequence
python
pybrain/pybrain
pybrain/datasets/supervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py
BSD-3-Clause
def evaluateModuleMSE(self, module, averageOver = 1, **args): """Evaluate the predictions of a module on a dataset and return the MSE (potentially average over a number of epochs).""" res = 0. for dummy in range(averageOver): module.reset() res += self.evaluateMSE...
Evaluate the predictions of a module on a dataset and return the MSE (potentially average over a number of epochs).
evaluateModuleMSE
python
pybrain/pybrain
pybrain/datasets/supervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py
BSD-3-Clause
def splitWithProportion(self, proportion = 0.5): """Produce two new datasets, the first one containing the fraction given by `proportion` of the samples.""" indicies = random.permutation(len(self)) separator = int(len(self) * proportion) leftIndicies = indicies[:separator] ...
Produce two new datasets, the first one containing the fraction given by `proportion` of the samples.
splitWithProportion
python
pybrain/pybrain
pybrain/datasets/supervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/supervised.py
BSD-3-Clause
def __init__(self, dim): """Initialize an empty unsupervised dataset. Pass `dim` to specify the dimensionality of the samples.""" super(UnsupervisedDataSet, self).__init__() self.addField('sample', dim) self.linkFields(['sample']) self.dim = dim # reset the inde...
Initialize an empty unsupervised dataset. Pass `dim` to specify the dimensionality of the samples.
__init__
python
pybrain/pybrain
pybrain/datasets/unsupervised.py
https://github.com/pybrain/pybrain/blob/master/pybrain/datasets/unsupervised.py
BSD-3-Clause
def _learnStep(self): """ generate a new evaluable by mutation, compare them, and keep the best. """ # re-evaluate the current individual in case the evaluator is noisy if self.evaluatorIsNoisy: self.bestEvaluation = self._oneEvaluation(self.bestEvaluable) # hill-climbing ...
generate a new evaluable by mutation, compare them, and keep the best.
_learnStep
python
pybrain/pybrain
pybrain/optimization/hillclimber.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/hillclimber.py
BSD-3-Clause
def __init__(self, evaluator = None, initEvaluable = None, **kwargs): """ The evaluator is any callable object (e.g. a lambda function). Algorithm parameters can be set here if provided as keyword arguments. """ # set all algorithm-specific parameters in one go: self.__minimize = None ...
The evaluator is any callable object (e.g. a lambda function). Algorithm parameters can be set here if provided as keyword arguments.
__init__
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def _setMinimize(self, flag): """ Minimization vs. maximization: priority to algorithm requirements, then evaluator, default = maximize.""" self.__minimize = flag opp = False if flag is True: if self.mustMaximize: opp = True self.__min...
Minimization vs. maximization: priority to algorithm requirements, then evaluator, default = maximize.
_setMinimize
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def setEvaluator(self, evaluator, initEvaluable = None): """ If not provided upon construction, the objective function can be given through this method. If necessary, also provide an initial evaluable.""" # default settings, if provided by the evaluator: if isinstance(evaluator,...
If not provided upon construction, the objective function can be given through this method. If necessary, also provide an initial evaluable.
setEvaluator
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def learn(self, additionalLearningSteps = None): """ The main loop that does the learning. """ assert self.__evaluator is not None, "No evaluator has been set. Learning cannot start." if additionalLearningSteps is not None: self.maxLearningSteps = self.numLearningSteps + additionalLe...
The main loop that does the learning.
learn
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def _bestFound(self): """ return the best found evaluable and its associated fitness. """ bestE = self.bestEvaluable.params.copy() if self._wasWrapped else self.bestEvaluable if self._wasOpposed and isscalar(self.bestEvaluation): bestF = -self.bestEvaluation else: ...
return the best found evaluable and its associated fitness.
_bestFound
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def _oneEvaluation(self, evaluable): """ This method should be called by all optimizers for producing an evaluation. """ if self._wasUnwrapped: self.wrappingEvaluable._setParameters(evaluable) res = self.__evaluator(self.wrappingEvaluable) elif self._wasWrapped: ...
This method should be called by all optimizers for producing an evaluation.
_oneEvaluation
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def _notify(self): """ Provide some feedback during the run. """ if self.verbose: print(('Step:', self.numLearningSteps, 'best:', self.bestEvaluation)) if self.listener is not None: self.listener(self.bestEvaluable, self.bestEvaluation)
Provide some feedback during the run.
_notify
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def _setInitEvaluable(self, evaluable): """ If the parameters are wrapped, we keep track of the wrapper explicitly. """ if isinstance(evaluable, ParameterContainer): self.wrappingEvaluable = evaluable.copy() self._wasUnwrapped = True elif not (evaluable is None ...
If the parameters are wrapped, we keep track of the wrapper explicitly.
_setInitEvaluable
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def _bestFound(self): """ return the best found evaluable and its associated fitness. """ bestE, bestF = BlackBoxOptimizer._bestFound(self) if self._wasUnwrapped: self.wrappingEvaluable._setParameters(bestE) bestE = self.wrappingEvaluable.copy() return bestE, best...
return the best found evaluable and its associated fitness.
_bestFound
python
pybrain/pybrain
pybrain/optimization/optimizer.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/optimizer.py
BSD-3-Clause
def sorti(vect): """ sort, but also return the indices-changes """ tmp = sorted([(x_y[1], x_y[0]) for x_y in enumerate(ravel(vect))]) res1 = array([x[0] for x in tmp]) res2 = array([int(x[1]) for x in tmp]) return res1, res2
sort, but also return the indices-changes
sorti
python
pybrain/pybrain
pybrain/optimization/distributionbased/cmaes.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/cmaes.py
BSD-3-Clause
def _generateConformingBatch(self): """ Generate a batch of samples that conforms to the current distribution. If importance mixing is enabled, this can reuse old samples. """
Generate a batch of samples that conforms to the current distribution. If importance mixing is enabled, this can reuse old samples.
_generateConformingBatch
python
pybrain/pybrain
pybrain/optimization/distributionbased/distributionbased.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/distributionbased.py
BSD-3-Clause
def _produceNewSample(self): """ returns a new sample, its fitness and its densities """ chosenOne = drawIndex(self.alphas, True) mu = self.mus[chosenOne] if self.useAnticipatedMeanShift: if len(self.allsamples) % 2 == 1 and len(self.allsamples) > 1: if not(s...
returns a new sample, its fitness and its densities
_produceNewSample
python
pybrain/pybrain
pybrain/optimization/distributionbased/fem.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/fem.py
BSD-3-Clause
def _computeUpdateSize(self, densities, sampleIndex): """ compute the the center-update-size for each sample using transformed fitnesses """ # determine (transformed) fitnesses transformedfitnesses = self.shapingFunction(self.fitnesses) # force renormaliziation transfor...
compute the the center-update-size for each sample using transformed fitnesses
_computeUpdateSize
python
pybrain/pybrain
pybrain/optimization/distributionbased/fem.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/fem.py
BSD-3-Clause
def _updateShaping(self): """ Daan: "This won't work. I like it!" """ assert self.numberOfCenters == 1 possible = self.shapingFunction.getPossibleParameters(self.windowSize) matchValues = [] pdfs = [multivariateNormalPdf(s, self.mus[0], self.sigmas[0]) for s in s...
Daan: "This won't work. I like it!"
_updateShaping
python
pybrain/pybrain
pybrain/optimization/distributionbased/fem.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/fem.py
BSD-3-Clause
def _logDerivsFactorSigma(self, samples, mu, invSigma, factorSigma): """ Compute the log-derivatives w.r.t. the factorized covariance matrix components. This implementation should be faster than the one in Vanilla. """ res = zeros((len(samples), self.numDistrParams - self.numParameters)) ...
Compute the log-derivatives w.r.t. the factorized covariance matrix components. This implementation should be faster than the one in Vanilla.
_logDerivsFactorSigma
python
pybrain/pybrain
pybrain/optimization/distributionbased/nes.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/nes.py
BSD-3-Clause
def _produceSamples(self): """ Append batch size new samples and evaluate them. """ tmp = [self._sample2base(self._produceSample()) for _ in range(self.batchSize)] list(map(self._oneEvaluation, tmp)) self._pointers = list(range(len(self._allEvaluated) - self.batchSize, len(se...
Append batch size new samples and evaluate them.
_produceSamples
python
pybrain/pybrain
pybrain/optimization/distributionbased/rank1.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/rank1.py
BSD-3-Clause
def _notify(self): """ Provide some feedback during the run. """ if self.verbose: if self.numEvaluations % self.verboseGaps == 0: print(('Step:', self.numLearningSteps, 'best:', self.bestEvaluation, 'logVar', round(self._logDetA, 3), 'l...
Provide some feedback during the run.
_notify
python
pybrain/pybrain
pybrain/optimization/distributionbased/rank1.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/rank1.py
BSD-3-Clause
def test(): """ Rank-1 NEX easily solves high-dimensional Rosenbrock functions. """ from pybrain.rl.environments.functions.unimodal import RosenbrockFunction dim = 40 f = RosenbrockFunction(dim) x0 = -ones(dim) l = Rank1NES(f, x0, verbose=True, verboseGaps=500) l.learn()
Rank-1 NEX easily solves high-dimensional Rosenbrock functions.
test
python
pybrain/pybrain
pybrain/optimization/distributionbased/rank1.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/rank1.py
BSD-3-Clause
def _produceSamples(self): """ Append batch size new samples and evaluate them. """ if self.clearStorage: self._allEvaluated = [] self._allEvaluations = [] tmp = [self._sample2base(self._produceSample()) for _ in range(self.batchSize)] list(map(self._...
Append batch size new samples and evaluate them.
_produceSamples
python
pybrain/pybrain
pybrain/optimization/distributionbased/snes.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/snes.py
BSD-3-Clause
def _produceSamples(self): """ Append batchsize new samples and evaluate them. """ if self.numLearningSteps == 0 or not self.importanceMixing: for _ in range(self.batchSize): self._produceNewSample() self.allGenerated.append(self.batchSize + self.allGenerated[-1])...
Append batchsize new samples and evaluate them.
_produceSamples
python
pybrain/pybrain
pybrain/optimization/distributionbased/ves.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/ves.py
BSD-3-Clause
def _hasConverged(self): """ When the largest eigenvalue is smaller than 10e-20, we assume the algorithms has converged. """ eigs = abs(diag(self.factorSigma)) return min(eigs) < 1e-10
When the largest eigenvalue is smaller than 10e-20, we assume the algorithms has converged.
_hasConverged
python
pybrain/pybrain
pybrain/optimization/distributionbased/ves.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/ves.py
BSD-3-Clause
def _revertToSafety(self): """ When encountering a bad matrix, this is how we revert to a safe one. """ self.factorSigma = eye(self.numParameters) self.x = self.bestEvaluable self.allFactorSigmas[-1][:] = self.factorSigma self.sigma = dot(self.factorSigma.T, self.factorSigma)
When encountering a bad matrix, this is how we revert to a safe one.
_revertToSafety
python
pybrain/pybrain
pybrain/optimization/distributionbased/ves.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/ves.py
BSD-3-Clause
def _produceSamples(self): """ Append batch size new samples and evaluate them. """ reuseindices = [] if self.numLearningSteps == 0 or not self.importanceMixing: [self._oneEvaluation(self._sample2base(self._produceSample())) for _ in range(self.batchSize)] self._pointers ...
Append batch size new samples and evaluate them.
_produceSamples
python
pybrain/pybrain
pybrain/optimization/distributionbased/xnes.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/distributionbased/xnes.py
BSD-3-Clause
def _learnStep(self): """ calls the gradient calculation function and executes a step in direction of the gradient, scaled with a small learning rate alpha. """ # initialize matrix D and vector R D = ones((self.batchSize, self.numParameters)) R = zeros((self.batchSize, 1)) ...
calls the gradient calculation function and executes a step in direction of the gradient, scaled with a small learning rate alpha.
_learnStep
python
pybrain/pybrain
pybrain/optimization/finitedifference/fd.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/finitedifference/fd.py
BSD-3-Clause
def _learnStep(self): """ calculates the gradient and executes a step in the direction of the gradient, scaled with a learning rate alpha. """ deltas = self.perturbation() #reward of positive and negative perturbations reward1 = self._oneEvaluation(self.current + deltas) ...
calculates the gradient and executes a step in the direction of the gradient, scaled with a learning rate alpha.
_learnStep
python
pybrain/pybrain
pybrain/optimization/finitedifference/pgpe.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/finitedifference/pgpe.py
BSD-3-Clause
def _learnStep(self): """ calculates the gradient and executes a step in the direction of the gradient, scaled with a learning rate alpha. """ deltas = self.perturbation() #reward of positive and negative perturbations reward1 = self._oneEvaluation(self.current + deltas) ...
calculates the gradient and executes a step in the direction of the gradient, scaled with a learning rate alpha.
_learnStep
python
pybrain/pybrain
pybrain/optimization/finitedifference/spsa.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/finitedifference/spsa.py
BSD-3-Clause
def switchMutations(self): """ interchange the mutate() and topologyMutate() operators """ tm = self._initEvaluable.__class__.topologyMutate m = self._initEvaluable.__class__.mutate self._initEvaluable.__class__.topologyMutate = m self._initEvaluable.__class__.mutate = tm
interchange the mutate() and topologyMutate() operators
switchMutations
python
pybrain/pybrain
pybrain/optimization/memetic/memetic.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/memetic/memetic.py
BSD-3-Clause
def crossOverOld(self, parents, nbChildren): """ generate a number of children by doing 1-point cross-over """ xdim = self.numParameters children = [] for _ in range(nbChildren): p1 = choice(parents) if xdim < 2: children.append(p1) els...
generate a number of children by doing 1-point cross-over
crossOverOld
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def mutatedOld(self, indiv): """ mutate some genes of the given individual """ res = indiv.copy() for i in range(self.numParameters): if random() < self.mutationProb: res[i] = indiv[i] + gauss(0, self.mutationStdDev) return res
mutate some genes of the given individual
mutatedOld
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def crossOver(self, parents, nbChildren): """ generate a number of children by doing 1-point cross-over """ """ change as the <choice> return quite often the same p1 and even several time p2 was return the same than p1 """ xdim = self.numParameters shuffle(parents) ch...
generate a number of children by doing 1-point cross-over
crossOver
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def mutated(self, indiv): """ mutate some genes of the given individual """ res = indiv.copy() #to avoid having a child identical to one of the currentpopulation''' for i in range(self.numParameters): if random() < self.mutationProb: if self.xBound is None: ...
mutate some genes of the given individual
mutated
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def old_jpq_mutated(self, indiv, pop): """ mutate some genes of the given individual """ res = indiv.copy() #to avoid having a child identical to one of the currentpopulation''' in_pop = self.childexist(indiv,pop) for i in range(self.numParameters): if random() < self...
mutate some genes of the given individual
old_jpq_mutated
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def select(self): """ select some of the individuals of the population, taking into account their fitnesses :return: list of selected parents """ if not self.tournament: tmp = list(zip(self.fitnesses, self.currentpop)) tmp.sort(key = lambda x: x[0]) tmp2 = li...
select some of the individuals of the population, taking into account their fitnesses :return: list of selected parents
select
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def produceOffspring(self): """ produce offspring by selection, mutation and crossover. """ parents = self.select() es = min(self.eliteSize, self.selectionSize) self.currentpop = parents[:es] '''Modified by JPQ ''' nbchildren = self.populationSize - es if self.pop...
produce offspring by selection, mutation and crossover.
produceOffspring
python
pybrain/pybrain
pybrain/optimization/populationbased/ga.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/ga.py
BSD-3-Clause
def best(self, particlelist): """Return the particle with the best fitness from a list of particles. """ picker = min if self.minimize else max return picker(particlelist, key=lambda p: p.fitness)
Return the particle with the best fitness from a list of particles.
best
python
pybrain/pybrain
pybrain/optimization/populationbased/pso.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/pso.py
BSD-3-Clause
def __init__(self, start, minimize): """Initialize a Particle at the given start vector.""" self.minimize = minimize self.dim = scipy.size(start) self.position = start self.velocity = scipy.zeros(scipy.size(start)) self.bestPosition = scipy.zeros(scipy.size(start)) ...
Initialize a Particle at the given start vector.
__init__
python
pybrain/pybrain
pybrain/optimization/populationbased/pso.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/pso.py
BSD-3-Clause
def __init__(self, relEvaluator, seeds, **args): """ :arg relevaluator: an anti-symmetric function that can evaluate 2 elements :arg seeds: a list of initial guesses """ # set parameters self.setArgs(**args) self.relEvaluator = relEvaluator if self.tournam...
:arg relevaluator: an anti-symmetric function that can evaluate 2 elements :arg seeds: a list of initial guesses
__init__
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def learn(self, maxSteps=None): """ Toplevel function, can be called iteratively. :return: best evaluable found in the last generation. """ if maxSteps != None: maxSteps += self.steps while True: if maxSteps != None and self.steps + self._stepsPerGeneration() > m...
Toplevel function, can be called iteratively. :return: best evaluable found in the last generation.
learn
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _extendPopulation(self, seeds, size): """ build a population, with mutated copies from the provided seed pool until it has the desired size. """ res = seeds[:] for dummy in range(size - len(seeds)): chosen = choice(seeds) tmp = chosen.copy() tmp.mu...
build a population, with mutated copies from the provided seed pool until it has the desired size.
_extendPopulation
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _selectAndReproduce(self, pop, fits): """ apply selection and reproduction to host population, according to their fitness.""" # combine population with their fitness, then sort, only by fitness s = list(zip(fits, pop)) shuffle(s) s.sort(key=lambda x:-x[0]) # select......
apply selection and reproduction to host population, according to their fitness.
_selectAndReproduce
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _beats(self, h, p): """ determine the empirically observed score of p playing opp (starting or not). If they never played, assume 0. """ if (h, p) not in self.allResults: return 0 else: hpgames, hscore = self.allResults[(h, p)][1:3] phgames, pscore...
determine the empirically observed score of p playing opp (starting or not). If they never played, assume 0.
_beats
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _doTournament(self, pop1, pop2, tournamentSize=None): """ Play a tournament. :key tournamentSize: If unspecified, play all-against-all """ # TODO: Preferably select high-performing opponents? for p in pop1: pop3 = pop2[:] while p in pop3: ...
Play a tournament. :key tournamentSize: If unspecified, play all-against-all
_doTournament
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _globalScore(self, p): """ The average score over all evaluations for a player. """ if p not in self.allOpponents: return 0. scoresum, played = 0., 0 for opp in self.allOpponents[p]: scoresum += self.allResults[(p, opp)][2] played += self.allResult...
The average score over all evaluations for a player.
_globalScore
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _sharedSampling(self, numSelect, selectFrom, relativeTo): """ Build a shared sampling set of opponents """ if numSelect < 1: return [] # determine the player of selectFrom with the most wins against players from relativeTo (and which ones) tmp = {} for p in select...
Build a shared sampling set of opponents
_sharedSampling
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _relEval(self, p, opp): """ a single relative evaluation (in one direction) with the involved bookkeeping.""" if p not in self.allOpponents: self.allOpponents[p] = [] self.allOpponents[p].append(opp) if (p, opp) not in self.allResults: self.allResults[(p, opp)...
a single relative evaluation (in one direction) with the involved bookkeeping.
_relEval
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/coevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/coevolution.py
BSD-3-Clause
def _competitiveSharedFitness(self, hosts, parasites): """ determine the competitive shared fitness for the population of hosts, w.r. to the population of parasites. """ if len(parasites) == 0: return [0] * len(hosts) # determine beat-sum for parasites (nb of games lost) ...
determine the competitive shared fitness for the population of hosts, w.r. to the population of parasites.
_competitiveSharedFitness
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/competitivecoevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/competitivecoevolution.py
BSD-3-Clause
def _initPopulation(self, seeds): """ one part of the seeds for each population, if there's not enough: randomize. """ for s in seeds: s.parent = None while len(seeds) < self.numPops: tmp = choice(seeds).copy() tmp.randomize() seeds.append(tmp) ...
one part of the seeds for each population, if there's not enough: randomize.
_initPopulation
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py
BSD-3-Clause
def _evaluatePopulation(self): """Each individual in main pop plays against tournSize others of each other population (the best part of them). """ for other in self.pops: if other == self.pop: continue # TODO: parametrize bestPart = len(other)/...
Each individual in main pop plays against tournSize others of each other population (the best part of them).
_evaluatePopulation
python
pybrain/pybrain
pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/coevolution/multipopulationcoevolution.py
BSD-3-Clause
def nsga2select(population, fitnesses, survivors, allowequality = True): """The NSGA-II selection strategy (Deb et al., 2002). The number of individuals that survive is given by the survivors parameter.""" fronts = const_non_dominated_sort(population, key=lambda x: fitnesses[...
The NSGA-II selection strategy (Deb et al., 2002). The number of individuals that survive is given by the survivors parameter.
nsga2select
python
pybrain/pybrain
pybrain/optimization/populationbased/multiobjective/constnsga2.py
https://github.com/pybrain/pybrain/blob/master/pybrain/optimization/populationbased/multiobjective/constnsga2.py
BSD-3-Clause