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: self.setField('class', self.getField('target').astype(int)) if self.nClasses <= 0: flat_labels = list(ravel(self['class'])) classes = list(set(flat_labels)) self.nClasses = len(classes)
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 self.outdim != 1: # we already have the correct representation (hopefully...) return if self.nClasses <= 0: self.calculateStatistics() oldtarg = self.getField('target') newtarg = zeros([len(self), self.nClasses], dtype='Int32') + bounds[0] for i in range(len(self)): newtarg[i, int(oldtarg[i])] = bounds[1] self.setField('target', newtarg) self.setField('class', oldtarg) # probably better not to link field, otherwise there may be confusion # if getLinked() is called? ##self.linkFields(self.link.append('class'))
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'] != cls_select) leftDs = self.copy() leftDs.clear() rightDs = leftDs.copy() # check which fields to split splitThis = [] for f in ['input', 'target', 'class', 'importance', 'aux']: if self.hasField(f): splitThis.append(f) # need to synchronize input, target, and class fields for field in splitThis: leftDs.setField(field, self[field][leftIndices, :]) leftDs.endmarker[field] = len(leftIndices) rightDs.setField(field, self[field][rightIndices, :]) rightDs.endmarker[field] = len(rightIndices) leftDs.assignClasses() rightDs.assignClasses() return leftDs, rightDs
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: regDs.setField(f, self[f]) regDs.setField('target', values[self['class'].astype(int)]) return regDs
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 the classes names, supply an iterable of strings as `class_labels`.""" # FIXME: hard to keep nClasses synchronized if appendLinked() etc. is used. SequentialDataSet.__init__(self, inp, target) # we want integer class numbers as targets self.convertField('target', int) if len(self) > 0: # calculate class histogram, if we already have data self.calculateStatistics() self.nClasses = nb_classes self.class_labels = list(range(self.nClasses)) if class_labels is None else class_labels # copy classes (targets may be changed into other representation) self.setField('class', self.getField('target'))
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 sequences in the test dataset, while `evalfrac` specifies the fraction of sequences in the validation dataset. If `evalfrac` equals 0, no validationset is returned. It is assumed that the last target for each class is the class of the sequence. Also mind that the data will be sorted by class in the resulting data sets.""" lastidx = ravel(self['sequence_index'][1:] - 1).astype(int) classes = ravel(self['class'][lastidx]) trnDs = self.copy() trnDs.clear() tstDs = trnDs.copy() valDs = trnDs.copy() for c in range(self.nClasses): # scramble available sequences for current class idx, = where(classes == c) nCls = len(idx) perm = permutation(nCls).tolist() nTst, nVal = (int(testfrac * nCls), int(evalfrac * nCls)) for count, ds in zip([nTst, nVal, nCls - nTst - nVal], [tstDs, valDs, trnDs]): for _ in range(count): feat = self.getSequence(idx[perm.pop()])[0] ds.newSequence() for s in feat: ds.addSample(s, [c]) ds.assignClasses() assert perm == [] if len(valDs) > 0: return trnDs, tstDs, valDs else: return trnDs, tstDs
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 fraction of sequences in the validation dataset. If `evalfrac` equals 0, no validationset is returned. It is assumed that the last target for each class is the class of the sequence. Also mind that the data will be sorted by class in the resulting data sets.
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, len(self) - 1] return self['class'][classidx, 0] else: if index < lastSeq: return self['class'][self['sequence_index'].astype(int)[index + 1, 0] - 1, 0] elif index == lastSeq: return self['class'][len(self) - 1, 0] raise IndexError("Sequence index out of range!")
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']) if self.nClasses > 10: raise from pycdf import CDF, NC # need to regenerate the file name filename = flo.name flo.close() # Create the file. Raise the automode flag, so that # we do not need to worry about setting the define/data mode. d = CDF(filename, NC.WRITE | NC.CREATE | NC.TRUNC) d.automode() # Create 2 global attributes, one holding a string, # and the other one 2 floats. d.title = 'Sequential data exported from PyBrain (www.pybrain.org)' # create the dimensions dimsize = { 'numTimesteps': len(self), 'inputPattSize': self.indim, 'numLabels': self.nClasses, 'numSeqs': self.getNumSequences(), 'maxLabelLength': 2 } dims = {} for name, sz in dimsize.items(): dims[name] = d.def_dim(name, sz) # Create a netCDF record variables inputs = d.def_var('inputs', NC.FLOAT, (dims['numTimesteps'], dims['inputPattSize'])) targetStrings = d.def_var('targetStrings', NC.CHAR, (dims['numSeqs'], dims['maxLabelLength'])) seqLengths = d.def_var('seqLengths', NC.INT, (dims['numSeqs'])) labels = d.def_var('labels', NC.CHAR, (dims['numLabels'], dims['maxLabelLength'])) # Switch to data mode (automatic) # assign float and integer arrays directly inputs.put(self['input'].astype(single)) # strings must be written as scalars (sucks!) for i in range(dimsize['numSeqs']): targetStrings.put_1(i, str(self.getSequenceClass(i))) for i in range(self.nClasses): labels.put_1(i, str(i)) # need colon syntax for assigning list seqLengths[:] = [self.getSequenceLength(i) for i in range(self.getNumSequences())] # Close file print(("wrote netCDF file " + filename)) d.close()
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: [1,2,3] 'none' - no conversion """ switch = { '1d': self._convertArray1d, '2d': self._convertArray2d, 'list': self._convertList, 'none': lambda x:x } try: self._convert = switch[vf] self.__vectorformat = vf except KeyError: raise VectorFormatError("vector format must be one of '1d', '2d', 'list'. given: %s" % 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: [1,2,3] 'none' - no conversion
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: sh = (1,) if len(sh) == 1: # use reshape to add extra dimension if column: return a.reshape((sh[0], 1)) else: return a.reshape((1, sh[0])) else: # vector is not 1d, return a without change return a
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: if l in self.link: link.remove(l) self.link = link else: self.link = []
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 length else: # all linked fields have equal length. return the length of the first. l = self.link[0] return self.endmarker[l]
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]: self._resize(label) self.data[label][self.endmarker[label], :] = row self.endmarker[label] += 1
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 instead.""" if label in self.link: raise OutOfSyncError self._appendUnlinked(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 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 next line.""" if self.link == []: raise NoLinkedFieldsError('The dataset does not have any linked fields.') if index == None: # no index given, return the currently marked line and step marker one line forward index = self.index self.index += 1 else: # return the indexed line and move marker to next line self.index = index + 1 if index >= self.getLength(): raise IndexError('index out of bounds of the dataset.') return [self._convert(self.data[l][index]) for l in self.link]
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.endmarker[label]] # Convert to list if requested. if self.vectorformat == 'list': label_data = label_data.tolist() return label_data
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: # iterate over all fields instead keys = self.data for k in keys: shape = list(self.data[k].shape) # set to zero rows shape[0] = 0 self.data[k] = zeros(shape) self.endmarker[k] = 0
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, :] self.setField(field, temp) Serializable.save_pickle(self, flo, protocol)
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.""" # First calculate how many batches we will have full_batches, rest = divmod(len(self), n) number_of_batches = full_batches if rest == 0 else full_batches + 1 # We make one iterator for the startindexes ... startindexes = (i * n for i in range(number_of_batches)) # ... and one for the stop indexes stopindexes = (((i + 1) * n) for i in range(number_of_batches - 1)) # The last stop index is the last element of the list (last batch # might not be filled completely) stopindexes = chain(stopindexes, [len(self)]) # Now combine them indexes = list(zip(startindexes, stopindexes)) # Shuffle them according to the permutation if one is given if permutation is not None: indexes = [indexes[i] for i in permutation] for start, stop in indexes: yield self.data[label][start:stop]
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()): for j in range(d.dim): if not scipy.isfinite(d[i, j]): d[i, j] = means[j]
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 importance will be set to 1.0 """ if importance == None: importance = ones(len(target)) self.appendLinked(inp, target, importance)
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()**2)) totalError += e ponderation += sum(importance) if verbose: print(( 'out: ', fListToString(list(res)))) print(( 'correct: ', fListToString(target))) print(( 'importance:', fListToString(importance))) print(( 'error: % .8f' % e)) return totalError, ponderation
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 learning names. Instead of 'episodes' though, we deal with 'sequences' here. """ DataSet.__init__(self) # add 3 fields: input, target, importance self.addField('state', statedim) self.addField('action', actiondim) self.addField('reward', 1) # link these 3 fields self.linkFields(['state', 'action', 'reward']) # reset the index marker self.index = 0 # add field that stores the beginning of a new episode self.addField('sequence_index', 1) self.append('sequence_index', 0) self.currentSeq = 0 self.statedim = statedim self.actiondim = actiondim # the input and target dimensions (for compatibility) self.indim = self.statedim self.outdim = self.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 learning names. Instead of 'episodes' though, we deal with 'sequences' here.
__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.getLength() if length != 0: if ravel(self.getField('sequence_index'))[-1] == length: raise EmptySequenceError self._appendUnlinked('sequence_index', length)
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 self.getField(field)[int(seq[index]):] if len(seq) < index + 1: # sequence index beyond number of sequences. raise exception raise IndexError('sequence does not exist.') return self.getField(field)[seq[index]:seq[index + 1]]
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 to access the last sequence, return until end of data return self.endOfData() if len(seq) < index + 1: # sequence index beyond number of sequences. raise exception raise IndexError('sequence does not exist.') else: return self.index >= seq[index + 1]
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 wants to access the last sequence, return until end of data return int(self.getLength() - seq[index]) if len(seq) < index + 1: # sequence index beyond number of sequences. raise exception raise IndexError('sequence does not exist.') return int(seq[index + 1] - seq[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.
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 exist.') sequences = ravel(self.getField('sequence_index')) seqstart = sequences[index] if index == self.getNumSequences() - 1: # last sequence is going to be removed lastSeqDeleted = True seqend = self.getLength() else: lastSeqDeleted = False # sequence to remove is not last one (sequence_index exists) seqend = sequences[index + 1] # cut out data from all fields for label in self.link: # concatenate rows from start to seqstart and from seqend to end self.data[label] = r_[self.data[label][:seqstart, :], self.data[label][seqend:, :]] # update endmarkers of linked fields self.endmarker[label] -= seqend - seqstart # update sequence indices for i, val in enumerate(sequences): if val > seqstart: self.data['sequence_index'][i, :] -= seqend - seqstart # remove sequence index of deleted sequence and reduce its endmarker self.data['sequence_index'] = r_[self.data['sequence_index'][:index, :], self.data['sequence_index'][index + 1:, :]] self.endmarker['sequence_index'] -= 1 if lastSeqDeleted: # last sequence was removed # move sequence marker to last remaining sequence self.currentSeq = index - 1 # move sample marker to end of dataset self.index = self.getLength() # if there was only 1 sequence left, re-initialize sequence index if self.getLength() == 0: self.clear() else: # removed sequence was not last one (sequence_index exists) # move sequence marker to the new sequence at position 'index' self.currentSeq = index # move sample marker to beginning of sequence at position 'index' self.index = ravel(self.getField('sequence_index'))[index]
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 = 0 for seq in self._provideSequences(): module.reset() e, p = self._evaluateSequence(module.activate, seq, **args) totalError += e ponderation += p assert ponderation > 0 res += totalError / ponderation return res / averageOver
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)) leftDs = self.copy() leftDs.clear() rightDs = leftDs.copy() index = 0 for seq in iter(self): if index in leftIndices: leftDs.newSequence() for sp in seq: leftDs.addSample(*sp) else: rightDs.newSequence() for sp in seq: rightDs.addSample(*sp) index += 1 return leftDs, rightDs
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.addField('input', inp) self.addField('target', target) else: self.setField('input', inp) self.setField('target', target) self.linkFields(['input', 'target']) # reset the index marker self.index = 0 # the input and target dimensions self.indim = self.getDimension('input') self.outdim = self.getDimension('target')
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 = self.getDimension('input') elif label == 'target': self.outdim = self.getDimension('target')
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) totalError += e ponderation += p assert ponderation > 0 return totalError/ponderation
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 ponderation += len(target) if verbose: print(( 'out: ', fListToString( list( res ) ))) print(( 'correct:', fListToString( target ))) print(( 'error: % .8f' % e)) return totalError, ponderation
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(module.activate, **args) return res/averageOver
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] rightIndicies = indicies[separator:] leftDs = SupervisedDataSet(inp=self['input'][leftIndicies].copy(), target=self['target'][leftIndicies].copy()) rightDs = SupervisedDataSet(inp=self['input'][rightIndicies].copy(), target=self['target'][rightIndicies].copy()) return leftDs, rightDs
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 index marker self.index = 0
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 challenger = self.bestEvaluable.copy() challenger.mutate() self._oneEvaluation(challenger)
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 self.__evaluator = None setAllArgs(self, kwargs) # bookkeeping self.numEvaluations = 0 self.numLearningSteps = 0 if self.storeAllEvaluated: self._allEvaluated = [] self._allEvaluations = [] elif self.storeAllEvaluations: self._allEvaluations = [] if evaluator is not None: self.setEvaluator(evaluator, initEvaluable)
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.__minimize = False if flag is False: if self.mustMinimize: opp = True self.__minimize = True if self.__evaluator is not None: if opp is not self._wasOpposed: self._flipDirection() self._wasOpposed = opp
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, FitnessEvaluator): if self.desiredEvaluation is None: self.desiredEvaluation = evaluator.desiredValue if self.minimize is None: self.minimize = evaluator.toBeMinimized # in some cases, we can deduce the dimension from the provided evaluator: if isinstance(evaluator, FunctionEnvironment): if self.numParameters is None: self.numParameters = evaluator.xdim elif self.numParameters is not evaluator.xdim: raise ValueError("Parameter dimension mismatch: evaluator expects "+str(evaluator.xdim)\ +" but it was set to "+str(self.numParameters)+".") '''added by JPQ to handle boundaries on the parameters''' self.evaluator = evaluator if self.xBound is None: self.xBound = evaluator.xbound if self.feasible is None: self.feasible = evaluator.feasible if self.constrained is None: self.constrained = evaluator.constrained if self.violation is None: self.violation = evaluator.violation # --- # default: maximize if self.minimize is None: self.minimize = False self.__evaluator = evaluator if self._wasOpposed: self._flipDirection() #set the starting point for optimization (as provided, or randomly) self._setInitEvaluable(initEvaluable) self.bestEvaluation = None self._additionalInit() self.bestEvaluable = self._initEvaluable
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 + additionalLearningSteps - 1 while not self._stoppingCriterion(): try: self._learnStep() self._notify() self.numLearningSteps += 1 except DivergenceError: logging.warning("Algorithm diverged. Stopped after "+str(self.numLearningSteps)+" learning steps.") break except ValueError: logging.warning("Something numerical went wrong. Stopped after "+str(self.numLearningSteps)+" learning steps.") break return self._bestFound()
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: bestF = self.bestEvaluation return bestE, bestF
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: res = self.__evaluator(evaluable.params) else: res = self.__evaluator(evaluable) ''' added by JPQ ''' if self.constrained : self.feasible = self.__evaluator.outfeasible self.violation = self.__evaluator.outviolation # --- if isscalar(res): # detect numerical instability if isnan(res) or isinf(res): raise DivergenceError # always keep track of the best if (self.numEvaluations == 0 or self.bestEvaluation is None or (self.minimize and res <= self.bestEvaluation) or (not self.minimize and res >= self.bestEvaluation)): self.bestEvaluation = res self.bestEvaluable = evaluable.copy() self.numEvaluations += 1 # if desired, also keep track of all evaluables and/or their fitness. if self.storeAllEvaluated: if self._wasUnwrapped: self._allEvaluated.append(self.wrappingEvaluable.copy()) elif self._wasWrapped: self._allEvaluated.append(evaluable.params.copy()) else: self._allEvaluated.append(evaluable.copy()) if self.storeAllEvaluations: if self._wasOpposed and isscalar(res): ''' added by JPQ ''' if self.constrained : self._allEvaluations.append([-res,self.feasible,self.violation]) # --- else: self._allEvaluations.append(-res) else: ''' added by JPQ ''' if self.constrained : self._allEvaluations.append([res,self.feasible,self.violation]) # --- else: self._allEvaluations.append(res) ''' added by JPQ ''' if self.constrained : return [res,self.feasible,self.violation] else: # --- return res
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 or isinstance(evaluable, list) or isinstance(evaluable, ndarray)): raise ValueError('Continuous optimization algorithms require a list, array or'+\ ' ParameterContainer as evaluable.') BlackBoxOptimizer._setInitEvaluable(self, evaluable) self._wasWrapped = False self._initEvaluable = self._initEvaluable.params.copy()
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, bestF
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(self.elitism and chosenOne == self.bestChosenCenter): mu += self.meanShifts[chosenOne] if self.diagonalOnly: sample = normal(mu, self.sigmas[chosenOne]) else: sample = multivariate_normal(mu, self.sigmas[chosenOne]) if self.sampleElitism and len(self.allsamples) > self.windowSize and len(self.allsamples) % self.windowSize == 0: sample = self.bestEvaluable.copy() fit = self._oneEvaluation(sample) if ((not self.minimize and fit >= self.bestEvaluation) or (self.minimize and fit <= self.bestEvaluation) or len(self.allsamples) == 0): # used to determine which center produced the current best self.bestChosenCenter = chosenOne self.bestSigma = self.sigmas[chosenOne].copy() if self.minimize: fit = -fit self.allfitnesses.append(fit) self.allsamples.append(sample) return sample, fit
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 transformedfitnesses /= max(transformedfitnesses) updateSize = transformedfitnesses[sampleIndex] * densities return updateSize * self.forgetFactor
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 self.samples] for p in possible: self.shapingFunction.setParameter(p) transformedFitnesses = self.shapingFunction(self.fitnesses) #transformedFitnesses /= sum(transformedFitnesses) sumValue = sum([x * log(y) for x, y in zip(pdfs, transformedFitnesses) if y > 0]) normalization = sum([x * y for x, y in zip(pdfs, transformedFitnesses) if y > 0]) matchValues.append(sumValue / normalization) self.shapingFunction.setParameter(possible[argmax(matchValues)]) if len(self.allsamples) % 100 == 0: print((possible[argmax(matchValues)])) print((fListToString(matchValues, 3)))
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)) invA = inv(factorSigma) diagInvA = diag(diag(invA)) for i, sample in enumerate(samples): s = dot(invA.T, (sample - mu)) R = outer(s, dot(invA, s)) - diagInvA res[i] = triu2flat(R) return res
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(self._allEvaluated)))
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), 'log|vector|', round(log(dot(self._principalVector, self._principalVector))/2, 3))) if self.listener is not None: self.listener(self.bestEvaluable, self.bestEvaluation)
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._oneEvaluation, tmp)) self._pointers = list(range(len(self._allEvaluated) - self.batchSize, len(self._allEvaluated)))
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]) # using new importance mixing code else: oldpoints = self.allSamples[-self.batchSize:] oldDetFactorSigma = det(self.allFactorSigmas[-2]) newDetFactorSigma = det(self.factorSigma) invA = inv(self.factorSigma) offset = len(self.allSamples) - self.batchSize oldInvA = inv(self.allFactorSigmas[-2]) oldX = self.allCenters[-2] def oldpdf(s): p = dot(oldInvA.T, (s- oldX)) return exp(-0.5 * dot(p, p)) / oldDetFactorSigma def newpdf(s): p = dot(invA.T, (s - self.x)) return exp(-0.5 * dot(p, p)) / newDetFactorSigma def newSample(): p = randn(self.numParameters) return dot(self.factorSigma.T, p) + self.x reused, newpoints = importanceMixing(oldpoints, oldpdf, newpdf, newSample, self.forcedRefresh) self.allGenerated.append(self.allGenerated[-1]+len(newpoints)) for i in reused: self.allSamples.append(self.allSamples[offset+i]) self.allFitnesses.append(self.allFitnesses[offset+i]) for s in newpoints: self._produceNewSample(s)
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 = list(range(len(self._allEvaluated)-self.batchSize, len(self._allEvaluated))) else: reuseindices, newpoints = importanceMixing(list(map(self._base2sample, self._currentEvaluations)), self._oldpdf, self._newpdf, self._produceSample, self.forcedRefresh) [self._oneEvaluation(self._sample2base(s)) for s in newpoints] self._pointers = ([self._pointers[i] for i in reuseindices]+ list(range(len(self._allEvaluated)-self.batchSize+len(reuseindices), len(self._allEvaluated)))) self._allGenSteps.append(self._allGenSteps[-1]+self.batchSize-len(reuseindices)) self._allPointers.append(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)) # calculate the gradient with pseudo inverse for i in range(self.batchSize): deltas = self.perturbation() x = self.current + deltas D[i, :] = deltas R[i, :] = self._oneEvaluation(x) beta = dot(pinv(D), R) gradient = ravel(beta) # update the weights self.current = self.gd(gradient)
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) reward2 = self._oneEvaluation(self.current - deltas) self.mreward = (reward1 + reward2) / 2. if self.baseline is None: # first learning step self.baseline = self.mreward fakt = 0. fakt2 = 0. else: #calc the gradients if reward1 != reward2: #gradient estimate alla SPSA but with likelihood gradient and normalization fakt = (reward1 - reward2) / (2. * self.bestEvaluation - reward1 - reward2) else: fakt=0. #normalized sigma gradient with moving average baseline norm = (self.bestEvaluation-self.baseline) if norm != 0.0: fakt2=(self.mreward-self.baseline)/(self.bestEvaluation-self.baseline) else: fakt2 = 0.0 #update baseline self.baseline = 0.9 * self.baseline + 0.1 * self.mreward # update parameters and sigmas self.current = self.gd(fakt * deltas - self.current * self.sigList * self.wDecay) if fakt2 > 0.: #for sigma adaption alg. follows only positive gradients if self.exploration == "global": #apply sigma update globally self.sigList = self.gdSig(fakt2 * ((self.deltas ** 2).sum() - (self.sigList ** 2).sum()) / (self.sigList * float(self.numParameters))) elif self.exploration == "local": #apply sigma update locally self.sigList = self.gdSig(fakt2 * (deltas * deltas - self.sigList * self.sigList) / self.sigList) elif self.exploration == "cma": #I have to think about that - needs also an option in perturbation raise NotImplementedError() else: raise NotImplementedError(str(self.exploration) + " not a known exploration parameter setting.")
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) reward2 = self._oneEvaluation(self.current - deltas) self.mreward = (reward1 + reward2) / 2. if self.baseline is None: # first learning step self.baseline = self.mreward * 0.99 fakt = 0. else: #calc the gradients if reward1 != reward2: #gradient estimate alla SPSA but with likelihood gradient and normalization (see also "update parameters") fakt = (reward1 - reward2) / (2.0 * self.bestEvaluation - reward1 - reward2) else: fakt = 0.0 self.baseline = 0.9 * self.baseline + 0.1 * self.mreward #update baseline # update parameters # as a simplification we use alpha = alpha * epsilon**2 for decaying the stepsize instead of the usual use method from SPSA # resulting in the same update rule like for PGPE self.current = self.gd(fakt * self.epsilon * self.epsilon / 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) else: p2 = choice(parents) point = choice(list(range(xdim-1))) point += 1 res = zeros(xdim) res[:point] = p1[:point] res[point:] = p2[point:] children.append(res) return children
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) children = [] for i in range(len(parents)//2): p1 = parents[i] p2 = parents[i+(len(parents)//2)] if xdim < 2: children.append(p1) children.append(p2) else: point = choice(list(range(xdim-1))) point += 1 res = zeros(xdim) res[:point] = p1[:point] res[point:] = p2[point:] children.append(res) res = zeros(xdim) res[:point] = p2[:point] res[point:] = p1[point:] children.append(res) shuffle(children) if len(children) > nbChildren: children = children[:nbChildren] else: while (len(children) < nbChildren): children += sample(children,1) return children
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: res[i] = indiv[i] + gauss(0, self.mutationStdDev) else: res[i] = max(min(indiv[i] + gauss(0, self.mutationStdDev),self.maxs[i]), self.mins[i]) return res
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.mutationProb: res[i] = max(min(indiv[i] + gauss(0, self.mutationStdDev),self.maxs[i]), self.mins[i]) if random() < self.mutationProb or in_pop: if self.xBound is None: res[i] = indiv[i] + gauss(0, self.mutationStdDev) else: if in_pop: cmin = abs(indiv[i] - self.mins[i])/(self.maxs[i]-self.mins[i]) cmax = abs(indiv[i] - self.maxs[i])/(self.maxs[i]-self.mins[i]) if cmin < 1.e-7 or cmax < 1.e-7: res[i] = self.mins[i] + random()*random()*(self.maxs[i]-self.mins[i]) else: res[i] = max(min(indiv[i] + gauss(0, self.mutationStdDev),self.maxs[i]), self.mins[i]) else: res[i] = max(min(indiv[i] + gauss(0, self.mutationStdDev),self.maxs[i]), self.mins[i]) return res
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 = list(reversed(tmp))[:self.selectionSize] return [x[1] for x in tmp2] else: # TODO: tournament selection raise NotImplementedError()
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.populationSize - es <= 0: nbchildren = len(parents) for child in self.crossOver(parents, nbchildren ): self.currentpop.append(self.mutated(child)) # ---
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)) self._fitness = None if self.minimize: self.bestFitness = scipy.inf else: self.bestFitness = -scipy.inf
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.tournamentSize == None: self.tournamentSize = self.populationSize # initialize algorithm variables self.steps = 0 self.generation = 0 # the best host and the best parasite from each generation self.hallOfFame = [] # the relative fitnesses from each generation (of the selected individuals) self.hallOfFitnesses = [] # this dictionary stores all the results between 2 players (first one starting): # { (player1, player2): [games won, total games, cumulative score, list of scores] } self.allResults = {} # this dictionary stores the opponents a player has played against. self.allOpponents = {} # a list of all previous populations self.oldPops = [] # build initial populations self._initPopulation(seeds)
: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() > maxSteps: break if self.maxEvaluations != None and self.steps + self._stepsPerGeneration() > self.maxEvaluations: break if self.maxGenerations != None and self.generation >= self.maxGenerations: break self._oneGeneration() return self.hallOfFame[-1]
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.mutate() if self.parentChildAverage < 1: tmp.parent = chosen res.append(tmp) return res
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... selected = [x[1] for x in s[:self._numSelected()]] # ... and reproduce if self.elitism: newpop = self._extendPopulation(selected, self.populationSize) if self.parentChildAverage < 1: self._averageWithParents(newpop, self.parentChildAverage) else: newpop = self._extendPopulation(selected, self.populationSize + self._numSelected()) [self._numSelected():] if self.parentChildAverage < 1: self._averageWithParents(newpop[self._numSelected():], self.parentChildAverage) return newpop
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 = self.allResults[(p, h)][1:3] return (hscore - pscore) / float(hpgames + phgames)
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: pop3.remove(p) if tournamentSize != None and tournamentSize < len(pop3): opps = sample(pop3, tournamentSize) else: opps = pop3 for opp in opps: self._relEval(p, opp) self._relEval(opp, p)
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.allResults[(p, opp)][1] scoresum -= self.allResults[(opp, p)][2] played += self.allResults[(opp, p)][1] # slightly bias the global score in favor of players with more games (just for tie-breaking) played += 0.01 return scoresum / played
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 selectFrom: beaten = [] for opp in relativeTo: if self._beats(p, opp) > 0: beaten.append(opp) tmp[p] = beaten beatlist = [(len(p_beaten[1]), self._globalScore(p_beaten[0]), p_beaten[0]) for p_beaten in list(tmp.items())] shuffle(beatlist) beatlist.sort(key=lambda x: x[:2]) best = beatlist[-1][2] unBeaten = list(set(relativeTo).difference(tmp[best])) otherSelect = selectFrom[:] otherSelect.remove(best) return [best] + self._sharedSampling(numSelect - 1, otherSelect, unBeaten)
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)] = [0, 0, 0., []] res = self.relEvaluator(p, opp) if res > 0: self.allResults[(p, opp)][0] += 1 self.allResults[(p, opp)][1] += 1 self.allResults[(p, opp)][2] += res self.allResults[(p, opp)][3].append(res) self.steps += 1
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) beatsums = {} for p in parasites: beatsums[p] = 0. for h in hosts: if self._beats(h, p) > 0: beatsums[p] += 1 # determine fitnesses for hosts fitnesses = [] for h in hosts: hsum = 0 unplayed = 0 for p in parasites: if self._beats(h, p) > 0: assert beatsums[p] > 0 hsum += 1. / beatsums[p] elif self._beats(h, p) == 0: unplayed += 1 # take into account the number of parasites played, to avoid # biasing for old agents in the elitist case if len(parasites) > unplayed: hsum /= float(len(parasites) - unplayed) # this is purely for breaking ties in favor of globally better players: hsum += 1e-5 * self._globalScore(h) fitnesses.append(hsum) return fitnesses
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) self.pops = [] for i in range(self.numPops): si = seeds[i::self.numPops] self.pops.append(self._extendPopulation(si, self.populationSize)) self.mainpop = 0 self.pop = self.pops[self.mainpop]
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)//2 if bestPart < 1: bestPart = 1 self._doTournament(self.pop, other[:bestPart], self.tournamentSize) fitnesses = [] for p in self.pop: fit = 0 for other in self.pops: if other == self.pop: continue for opp in other: fit += self._beats(p, opp) if self.absEvalProportion > 0 and self.absEvaluator != None: fit = (1-self.absEvalProportion) * fit + self.absEvalProportion * self.absEvaluator(p) fitnesses.append(fit) return fitnesses
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[x], allowequality = allowequality) individuals = set() for front in fronts: remaining = survivors - len(individuals) if not remaining > 0: break if len(front) > remaining: # If the current front does not fit in the spots left, use those # that have the biggest crowding distance. crowd_dist = const_crowding_distance(front, fitnesses) front = sorted(front, key=lambda x: crowd_dist[x], reverse=True) front = set(front[:remaining]) individuals |= front return list(individuals)
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