_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q9200
Collection.set_default_subject
train
def set_default_subject(self, subject): """ Sets the subject's location media URL as a link. It displays as the default subject on PFE. - **subject** can be a single :py:class:`.Subject` instance or a single subject ID. Examples:: collection.set_default_subject(1234) collection.set_default_subject(Subject(1234)) """ if not ( isinstance(subject, Subject) or isinstance(subject, (int, str,)) ):
python
{ "resource": "" }
q9201
Workflow.retire_subjects
train
def retire_subjects(self, subjects, reason='other'): """ Retires subjects in this workflow. - **subjects** can be a list of :py:class:`Subject` instances, a list of subject IDs, a single :py:class:`Subject` instance, or a single subject ID. - **reason** gives the reason the :py:class:`Subject` has been retired. Defaults to **other**. Examples:: workflow.retire_subjects(1234) workflow.retire_subjects([1,2,3,4]) workflow.retire_subjects(Subject(1234)) workflow.retire_subjects([Subject(12), Subject(34)])
python
{ "resource": "" }
q9202
PanoptesObject.where
train
def where(cls, **kwargs): """ Returns a generator which yields instances matching the given query arguments. For example, this would yield all :py:class:`.Project`:: Project.where() And this would yield all launch approved :py:class:`.Project`::
python
{ "resource": "" }
q9203
PanoptesObject.reload
train
def reload(self): """ Re-fetches the object from the API, discarding any local changes. Returns without doing anything if the object is new. """ if not self.id:
python
{ "resource": "" }
q9204
PanoptesObject.delete
train
def delete(self): """ Deletes the object. Returns without doing anything if the object is new. """ if not self.id: return
python
{ "resource": "" }
q9205
LinkCollection.add
train
def add(self, objs): """ Adds the given `objs` to this `LinkCollection`. - **objs** can be a list of :py:class:`.PanoptesObject` instances, a list of object IDs, a single :py:class:`.PanoptesObject` instance, or a single object ID. Examples:: organization.links.projects.add(1234) organization.links.projects.add(Project(1234)) workflow.links.subject_sets.add([1,2,3,4]) workflow.links.subject_sets.add([Project(12), Project(34)]) """ if self.readonly: raise NotImplementedError( '{} links can\'t be modified'.format(self._slug) )
python
{ "resource": "" }
q9206
LinkCollection.remove
train
def remove(self, objs): """ Removes the given `objs` from this `LinkCollection`. - **objs** can be a list of :py:class:`.PanoptesObject` instances, a list of object IDs, a single :py:class:`.PanoptesObject` instance, or a single object ID. Examples:: organization.links.projects.remove(1234) organization.links.projects.remove(Project(1234)) workflow.links.subject_sets.remove([1,2,3,4]) workflow.links.subject_sets.remove([Project(12), Project(34)]) """ if self.readonly: raise NotImplementedError( '{} links can\'t be modified'.format(self._slug) ) if not self._parent.id: raise ObjectNotSavedException( "Links can not be modified before the object has been saved." ) _objs =
python
{ "resource": "" }
q9207
write
train
def write(nml, nml_path, force=False, sort=False): """Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is equivalent to the ``write`` function of the ``Namelist`` object ``nml``. >>> nml.write('data.nml') By default, ``write`` will not overwrite an existing file. To override this, use
python
{ "resource": "" }
q9208
patch
train
def patch(nml_path, nml_patch, out_path=None): """Create a new namelist based on an input namelist and reference dict. >>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml') This function is equivalent to the ``read`` function of the ``Parser`` object with the patch output arguments. >>> parser = f90nml.Parser() >>> nml = parser.read('data.nml', nml_patch, 'patched_data.nml') A patched namelist file will retain any formatting
python
{ "resource": "" }
q9209
Canvas.convert
train
def convert(self, format="png", **kwargs): """ png, ps, pdf, gif, jpg, svg returns image in format as bytes """ if format.upper() in cairosvg.SURFACES: surface = cairosvg.SURFACES[format.upper()] else:
python
{ "resource": "" }
q9210
Canvas.toPIL
train
def toPIL(self, **attribs): """ Convert canvas to a PIL image """ import PIL.Image bytes = self.convert("png")
python
{ "resource": "" }
q9211
Canvas.toGIF
train
def toGIF(self, **attribs): """ Convert canvas to GIF bytes """ im = self.toPIL(**attribs)
python
{ "resource": "" }
q9212
Canvas.getPixels
train
def getPixels(self): """ Return a stream of pixels from current Canvas. """ array = self.toArray() (width, height, depth) = array.size
python
{ "resource": "" }
q9213
Circle.getP1
train
def getP1(self): """ Left, upper point """ return Point(self.center[0]
python
{ "resource": "" }
q9214
Circle.getP2
train
def getP2(self): """ Right, lower point """ return
python
{ "resource": "" }
q9215
Simulation.start_sim
train
def start_sim(self, gui=True, set_values={}, error=None): """ Run the simulation in the background, showing the GUI by default. """ self.error = error if not self.is_running.is_set(): def loop(): self.need_to_stop.clear() self.is_running.set() for robot in self.robots: if robot.brain: self.runBrain(robot.brain) count = 0 while not self.need_to_stop.isSet(): if not self.paused.is_set(): self.clock += self.sim_time for robot in self.robots: try: robot.update() except Exception as exc: self.need_to_stop.set() if error: error.value = "Error: %s. Now stopping simulation." % str(exc) else: raise if gui: self.draw() if count % self.gui_update == 0:
python
{ "resource": "" }
q9216
Simulation.draw
train
def draw(self): """ Render and draw the world and robots. """
python
{ "resource": "" }
q9217
Simulation.sleep
train
def sleep(self, seconds): """ Sleep in simulated time. """ start = self.time()
python
{ "resource": "" }
q9218
Simulation.runBrain
train
def runBrain(self, f): """ Run a brain program in the background. """ if self.error: self.error.value = "" def wrapper(): self.brain_running.set() try: f() except KeyboardInterrupt: # Just stop pass except Exception as e: if self.error:
python
{ "resource": "" }
q9219
Robot.forward
train
def forward(self, seconds, vx=5): """ Move continuously in simulator for seconds and velocity vx. """
python
{ "resource": "" }
q9220
DNARobot.codon2weight
train
def codon2weight(self, codon): """ Turn a codon of "000" to "999" to a number between -5.0 and 5.0. """ length = len(codon)
python
{ "resource": "" }
q9221
DNARobot.weight2codon
train
def weight2codon(self, weight, length=None): """ Given a weight between -5 and 5, turn it into a codon, eg "000" to "999" """ if length is None: length = self.clen retval = 0 weight = min(max(weight + 5.0, 0), 10.0) * (10 ** (length - 1)) for i in range(length): if i == length - 1: # last one d = int(round(weight / (10 ** (length - i - 1))))
python
{ "resource": "" }
q9222
is_nullable_list
train
def is_nullable_list(val, vtype): """Return True if list contains either values of type `vtype` or None.""" return (isinstance(val, list) and
python
{ "resource": "" }
q9223
Namelist.column_width
train
def column_width(self, width): """Validate and set the column width.""" if isinstance(width, int): if width >= 0: self._column_width = width else:
python
{ "resource": "" }
q9224
Namelist.indent
train
def indent(self, value): """Validate and set the indent width.""" # Explicit indent setting if isinstance(value, str): if value.isspace() or len(value) == 0: self._indent = value else: raise ValueError('String indentation can only contain ' 'whitespace.') # Set indent width elif isinstance(value, int):
python
{ "resource": "" }
q9225
Namelist.end_comma
train
def end_comma(self, value): """Validate and set the comma termination flag.""" if not isinstance(value, bool): raise
python
{ "resource": "" }
q9226
Namelist.index_spacing
train
def index_spacing(self, value): """Validate and set the index_spacing flag.""" if not
python
{ "resource": "" }
q9227
Namelist.uppercase
train
def uppercase(self, value): """Validate and set the uppercase flag.""" if not isinstance(value,
python
{ "resource": "" }
q9228
Namelist.float_format
train
def float_format(self, value): """Validate and set the upper case flag.""" if isinstance(value, str): # Duck-test the format string;
python
{ "resource": "" }
q9229
Namelist.logical_repr
train
def logical_repr(self, value): """Set the string representation of logical values.""" if not any(isinstance(value, t) for t in (list, tuple)): raise TypeError("Logical representation must be a tuple with " "a
python
{ "resource": "" }
q9230
Namelist.false_repr
train
def false_repr(self, value): """Validate and set the logical false representation.""" if isinstance(value, str): if not (value.lower().startswith('f') or value.lower().startswith('.f')): raise ValueError("Logical false representation must start "
python
{ "resource": "" }
q9231
Namelist.start_index
train
def start_index(self, value): """Validate and set the vector start index.""" # TODO: Validate contents? (May want to set before adding the data.) if not isinstance(value,
python
{ "resource": "" }
q9232
Namelist.write
train
def write(self, nml_path, force=False, sort=False): """Write Namelist to a Fortran 90 namelist file. >>> nml = f90nml.read('input.nml') >>> nml.write('out.nml') """ nml_is_file = hasattr(nml_path, 'read') if not force and not nml_is_file and os.path.isfile(nml_path): raise IOError('File {0} already exists.'.format(nml_path))
python
{ "resource": "" }
q9233
Namelist.patch
train
def patch(self, nml_patch): """Update the namelist from another partial or full namelist. This is different from the intrinsic `update()` method, which replaces a namelist section. Rather, it updates the values within a section. """
python
{ "resource": "" }
q9234
Namelist.groups
train
def groups(self): """Return an iterator that spans values with group and variable names. Elements of the iterator consist of a tuple containing two values. The first is internal tuple containing the current namelist group and its variable name. The second element of the returned tuple is the value associated
python
{ "resource": "" }
q9235
Namelist._write_nmlgrp
train
def _write_nmlgrp(self, grp_name, grp_vars, nml_file, sort=False): """Write namelist group to target file.""" if self._newline: print(file=nml_file) self._newline = True if self.uppercase: grp_name = grp_name.upper() if sort: grp_vars = Namelist(sorted(grp_vars.items(), key=lambda t: t[0])) print('&{0}'.format(grp_name), file=nml_file) for v_name, v_val in grp_vars.items():
python
{ "resource": "" }
q9236
Namelist.todict
train
def todict(self, complex_tuple=False): """Return a dict equivalent to the namelist. Since Fortran variables and names cannot start with the ``_`` character, any keys starting with this token denote metadata, such as starting index. The ``complex_tuple`` flag is used to convert complex data into an equivalent 2-tuple, with metadata stored to flag the variable as complex. This is primarily used to facilitate the storage of the namelist into an equivalent format which does not support complex numbers, such as JSON or YAML. """ # TODO: Preserve ordering nmldict = OrderedDict(self) # Search for namelists within the namelist # TODO: Move repeated stuff to new functions for key, value in self.items(): if isinstance(value, Namelist): nmldict[key] = value.todict(complex_tuple) elif isinstance(value, complex) and complex_tuple: nmldict[key] = [value.real, value.imag] try: nmldict['_complex'].append(key) except KeyError:
python
{ "resource": "" }
q9237
Namelist._f90repr
train
def _f90repr(self, value): """Convert primitive Python types to equivalent Fortran strings.""" if isinstance(value, bool): return self._f90bool(value) elif isinstance(value, numbers.Integral): return self._f90int(value) elif isinstance(value, numbers.Real):
python
{ "resource": "" }
q9238
Namelist._f90complex
train
def _f90complex(self, value): """Return a Fortran 90 representation of a complex number.""" return
python
{ "resource": "" }
q9239
Namelist._f90str
train
def _f90str(self, value): """Return a Fortran 90 representation of a string.""" # Replace Python quote escape sequence with Fortran result = repr(str(value)).replace("\\'", "''").replace('\\"', '""')
python
{ "resource": "" }
q9240
Cursor.extract_data
train
def extract_data(self, page): """Extract the AppNexus object or list of objects from the response""" response_keys = set(page.keys()) uncommon_keys = response_keys - self.common_keys for possible_data_key in uncommon_keys: element = page[possible_data_key] if isinstance(element, dict): return [self.representation(self.client, self.service_name,
python
{ "resource": "" }
q9241
Cursor.first
train
def first(self): """Extract the first AppNexus object present in the response""" page = self.get_page(num_elements=1)
python
{ "resource": "" }
q9242
Cursor.size
train
def size(self): """Return the number of elements of the cursor with skip and limit""" initial_count =
python
{ "resource": "" }
q9243
sumMerge
train
def sumMerge(dict1, dict2): """ Adds two dictionaries together, and merges into the first, dict1. Returns first dict. """ for key in
python
{ "resource": "" }
q9244
loadNetworkFromFile
train
def loadNetworkFromFile(filename, mode = 'pickle'): """ Deprecated. Use loadNetwork instead. """ if mode == 'pickle': import pickle fp = open(filename) network = pickle.load(fp) fp.close() return network elif mode in ['plain', 'conx']: fp = open(filename, "r") line = fp.readline() network = None while line: if line.startswith("layer,"): # layer, name, size temp, name, sizeStr = line.split(",") name = name.strip() size = int(sizeStr) network.addLayer(name, size) line = fp.readline() weights = [float(f) for f in line.split()] for i in range(network[name].size): network[name].weight[i] = weights[i] elif line.startswith("connection,"): # connection, fromLayer, toLayer temp, nameFrom, nameTo = line.split(",") nameFrom, nameTo = nameFrom.strip(), nameTo.strip() network.connect(nameFrom, nameTo) for i in range(network[nameFrom].size): line = fp.readline() weights = [float(f)
python
{ "resource": "" }
q9245
randomArray2
train
def randomArray2(size, bound): """ Returns an array initialized to random values between -bound and bound distributed in a gaussian probability distribution more
python
{ "resource": "" }
q9246
randomArray
train
def randomArray(size, bound): """ Returns an array initialized to random values between -max and max. """ if type(size) == type(1):
python
{ "resource": "" }
q9247
writeArray
train
def writeArray(fp, a, delim = " ", nl = 1): """ Writes a sequence a of floats to file pointed to by file pointer. """ for i in
python
{ "resource": "" }
q9248
Layer.RMSError
train
def RMSError(self): """ Returns Root Mean Squared Error for this layer's pattern. """
python
{ "resource": "" }
q9249
Layer.getCorrect
train
def getCorrect(self, tolerance): """ Returns the number of nodes within tolerance of the target. """
python
{ "resource": "" }
q9250
Layer.setLog
train
def setLog(self, fileName, writeName=False): """ Opens a log file with name fileName. """ self.log = 1 self.logFile
python
{ "resource": "" }
q9251
Layer.closeLog
train
def closeLog(self): """ Closes the log file. """ self._logPtr.close() if
python
{ "resource": "" }
q9252
Layer.writeLog
train
def writeLog(self, network): """ Writes to the log file. """ if self.log: writeArray(self._logPtr, self.activation)
python
{ "resource": "" }
q9253
Layer.toString
train
def toString(self): """ Returns a string representation of Layer instance. """ string = "Layer '%s': (Kind: %s, Size: %d, Active: %d, Frozen: %d)\n" % ( self.name, self.kind, self.size, self.active, self.frozen) if (self.type == 'Output'): string += toStringArray('Target ', self.target, self.displayWidth) string += toStringArray('Activation', self.activation, self.displayWidth) if (self.type != 'Input' and self._verbosity > 1): string += toStringArray('Error ', self.error, self.displayWidth) if (self._verbosity > 4 and self.type != 'Input'): string += toStringArray('weight
python
{ "resource": "" }
q9254
Layer.display
train
def display(self): """ Displays the Layer instance to the screen. """ if self.displayWidth == 0: return print("=============================") print("Layer '%s': (Kind: %s, Size: %d, Active: %d, Frozen: %d)" % ( self.name, self.kind, self.size, self.active, self.frozen)) if (self.type == 'Output'): displayArray('Target ', self.target, self.displayWidth) displayArray('Activation', self.activation, self.displayWidth) if (self.type != 'Input' and self._verbosity > 1): displayArray('Error ', self.error, self.displayWidth) if (self._verbosity > 4 and self.type != 'Input'):
python
{ "resource": "" }
q9255
Layer.copyActivations
train
def copyActivations(self, arr, reckless = 0): """ Copies activations from the argument array into layer activations. """ array = Numeric.array(arr) if not len(array) == self.size: raise LayerError('Mismatched activation size and layer
python
{ "resource": "" }
q9256
Layer.copyTargets
train
def copyTargets(self, arr): """ Copies the targets of the argument array into the self.target attribute. """ array = Numeric.array(arr) if not len(array) == self.size: raise LayerError('Mismatched target size and layer size in call to copyTargets()', \ (len(array), self.size)) # Removed this because both propagate and backprop (via compute_error) set targets #if self.verify and not self.targetSet == 0: # if not self.warningIssued: # print 'Warning! Targets have already been set and no intervening backprop() was called.', \ #
python
{ "resource": "" }
q9257
Connection.initialize
train
def initialize(self): """ Initializes self.dweight and self.wed to zero matrices. """ self.randomize() self.dweight = Numeric.zeros((self.fromLayer.size, \ self.toLayer.size), 'f') self.wed = Numeric.zeros((self.fromLayer.size, \
python
{ "resource": "" }
q9258
Connection.display
train
def display(self): """ Displays connection information to the screen. """ if self.toLayer._verbosity > 4: print("wed: from '" + self.fromLayer.name + "' to '" + self.toLayer.name +"'") for j in range(self.toLayer.size): print(self.toLayer.name, "[", j, "]", end=" ") print('') for i in range(self.fromLayer.size): print(self.fromLayer.name, "[", i, "]", ": ", end=" ") for j in range(self.toLayer.size): print(self.wed[i][j], end=" ") print('') print('') print("dweight: from '" + self.fromLayer.name + "' to '" + self.toLayer.name +"'") for j in range(self.toLayer.size): print(self.toLayer.name, "[", j, "]", end=" ") print('') for i in range(self.fromLayer.size): print(self.fromLayer.name, "[", i, "]", ": ", end=" ") for j in range(self.toLayer.size): print(self.dweight[i][j], end=" ")
python
{ "resource": "" }
q9259
Connection.toString
train
def toString(self): """ Connection information as a string. """ string = "" if self.toLayer._verbosity > 4: string += "wed: from '" + self.fromLayer.name + "' to '" + self.toLayer.name +"'\n" string += " " for j in range(self.toLayer.size): string += " " + self.toLayer.name + "[" + str(j) + "]" string += '\n' for i in range(self.fromLayer.size): string += self.fromLayer.name+ "["+ str(i)+ "]"+ ": " for j in range(self.toLayer.size): string += " " + str(self.wed[i][j]) string += '\n' string += '\n' string += "dweight: from '" + self.fromLayer.name + "' to '" + self.toLayer.name +"'\n"
python
{ "resource": "" }
q9260
Network.getLayerIndex
train
def getLayerIndex(self, layer): """ Given a reference to a layer, returns the index of that layer in self.layers. """ for i in range(len(self.layers)):
python
{ "resource": "" }
q9261
Network.isConnected
train
def isConnected(self, fromName, toName): """ Are these two layers connected this way? """ for c in self.connections: if (c.fromLayer.name ==
python
{ "resource": "" }
q9262
Network.connect
train
def connect(self, *names): """ Connects a list of names, one to the next. """
python
{ "resource": "" }
q9263
Network.connectAt
train
def connectAt(self, fromName, toName, position = None): """ Connects two layers by instantiating an instance of Connection class. Allows a position number, indicating the ordering of the connection. """ fromLayer = self.getLayer(fromName) toLayer = self.getLayer(toName) if self.getLayerIndex(fromLayer) >= self.getLayerIndex(toLayer): raise NetworkError('Layers out of order.', (fromLayer.name, toLayer.name)) if (fromLayer.type == 'Output'): fromLayer.type = 'Hidden' fromLayer.patternReport = 0 # automatically turned off for hidden layers if fromLayer.kind == 'Output': fromLayer.kind = 'Hidden' elif (fromLayer.type == 'Undefined'): fromLayer.type = 'Input' fromLayer.patternReport = 0 # automatically turned off for input layers if fromLayer.kind == 'Undefined': fromLayer.kind = 'Input' if (toLayer.type == 'Input'):
python
{ "resource": "" }
q9264
Network.addLayerNode
train
def addLayerNode(self, layerName, bias = None, weights = {}): """ Adds a new node to a layer, and puts in new weights. Adds node on the end. Weights will be random, unless specified. bias = the new node's bias weight weights = dict of {connectedLayerName: [weights], ...} Example: >>> net = Network() # doctest: +ELLIPSIS Conx using seed: ... >>> net.addLayers(2, 5, 1) >>> net.addLayerNode("hidden", bias = -0.12, weights = {"input": [1, 0], "output": [0]}) """ self.changeLayerSize(layerName, self[layerName].size + 1) if bias != None: self[layerName].weight[-1] = bias for name in list(weights.keys()):
python
{ "resource": "" }
q9265
Network.changeLayerSize
train
def changeLayerSize(self, layername, newsize): """ Changes layer size. Newsize must be greater than zero. """ # for all connection from to this layer, change matrix: if self.sharedWeights: raise AttributeError("shared weights broken")
python
{ "resource": "" }
q9266
Network.getActivationsDict
train
def getActivationsDict(self, nameList): """ Returns a dictionary of layer names that map to a list of activations. """ retval = {} for name in nameList:
python
{ "resource": "" }
q9267
Network.setSeed
train
def setSeed(self, value): """ Sets the seed to value. """ self.seed = value random.seed(self.seed)
python
{ "resource": "" }
q9268
Network.setVerbosity
train
def setVerbosity(self, value): """ Sets network self._verbosity and each layer._verbosity to value. """
python
{ "resource": "" }
q9269
Network.setOrderedInputs
train
def setOrderedInputs(self, value): """ Sets self.orderedInputs to value. Specifies if inputs should be ordered and if so orders the inputs. """ self.orderedInputs = value if self.orderedInputs:
python
{ "resource": "" }
q9270
Network.verifyArguments
train
def verifyArguments(self, arg): """ Verifies that arguments to setInputs and setTargets are appropriately formatted. """ for l in arg: if not type(l) == list and \ not type(l) == type(Numeric.array([0.0])) and \ not type(l) == tuple and \ not type(l) == dict: return 0 if type(l) == dict:
python
{ "resource": "" }
q9271
Network.setTargets
train
def setTargets(self, targets): """ Sets the targets. """ if not self.verifyArguments(targets) and not self.patterned: raise NetworkError('setTargets() requires
python
{ "resource": "" }
q9272
Network.copyActivations
train
def copyActivations(self, layer, vec, start = 0): """ Copies activations in vec to the specified layer, replacing patterns if necessary. """ vector = self.replacePatterns(vec, layer.name) if self.verbosity > 4:
python
{ "resource": "" }
q9273
Network.getDataMap
train
def getDataMap(self, intype, pos, name, offset = 0): """ Hook defined to lookup a name, and get it from a vector. Can be overloaded to get it from somewhere else. """ if intype == "input": vector = self.inputs
python
{ "resource": "" }
q9274
Network.getData
train
def getData(self, pos): """ Returns dictionary with input and target given pos. """ retval = {} if pos >= len(self.inputs): raise IndexError('getData() pattern beyond range.', pos) if self.verbosity >= 1: print("Getting input", pos, "...") if len(self.inputMap) == 0: if type(self.inputs[pos]) == dict: # allow inputs to be a dict retval.update(self.inputs[pos]) else: retval[self.layers[0].name] = self.inputs[pos]
python
{ "resource": "" }
q9275
Network.RMSError
train
def RMSError(self): """ Returns Root Mean Squared Error for all output layers in this network. """ tss = 0.0 size = 0 for layer in self.layers: if
python
{ "resource": "" }
q9276
Network.numConnects
train
def numConnects(self, layerName): """ Number of incoming weights, including bias. Assumes fully connected. """ count = 0 if self[layerName].active: count += 1 # 1 = bias for connection in self.connections:
python
{ "resource": "" }
q9277
Network.prop_from
train
def prop_from(self, startLayers): """ Start propagation from the layers in the list startLayers. Make sure startLayers are initialized with the desired activations. NO ERROR CHECKING. """ if self.verbosity > 2: print("Partially propagating network:") # find all the layers involved in the propagation propagateLayers = [] # propagateLayers should not include startLayers (no loops) for startLayer in startLayers: for layer in self.layers: if self.path(startLayer, layer): propagateLayers.append(layer) for layer in propagateLayers: if layer.active: layer.netinput = (layer.weight).copy() for layer in propagateLayers: if layer.active: for connection in self.connections: if connection.active and connection.toLayer.name == layer.name: connection.toLayer.netinput = connection.toLayer.netinput
python
{ "resource": "" }
q9278
Network.propagateTo
train
def propagateTo(self, toLayer, **args): """ Propagates activation to a layer. Optionally, takes input layer names as keywords, and their associated activations. Returns the toLayer's activation. Examples: >>> net = Network() # doctest: +ELLIPSIS Conx using seed: ... >>> net.addLayers(2, 5, 1) >>> len(net.propagateTo("output")) 1 >>> len(net.propagateTo("hidden")) 5 >>> len(net.propagateTo("hidden", input = [0, 0])) 5 """ for layerName in args: self[layerName].activationSet = 0 # force it to be ok self[layerName].copyActivations(args[layerName]) # init toLayer: self[toLayer].netinput = (self[toLayer].weight).copy() # for each connection, in order: for connection in self.connections:
python
{ "resource": "" }
q9279
Network.activationFunctionASIG
train
def activationFunctionASIG(self, x): """ Determine the activation of a node based on that nodes net input. """ def act(v): if v < -15.0: return 0.0
python
{ "resource": "" }
q9280
Network.actDerivASIG
train
def actDerivASIG(self, x): """ Only works on scalars. """ def act(v): if v < -15.0: return 0.0 elif v > 15.0: return 1.0 else: return
python
{ "resource": "" }
q9281
Network.useTanhActivationFunction
train
def useTanhActivationFunction(self): """ Change the network to use the hyperbolic tangent activation function for all layers. Must be called after all layers have been added. """ self.activationFunction = self.activationFunctionTANH self.ACTPRIME = self.ACTPRIMETANH self.actDeriv = self.actDerivTANH
python
{ "resource": "" }
q9282
Network.useFahlmanActivationFunction
train
def useFahlmanActivationFunction(self): """ Change the network to use Fahlman's default activation function for all layers. Must be called after all layers have been added. """
python
{ "resource": "" }
q9283
Network.backprop
train
def backprop(self, **args): """ Computes error and wed for back propagation of error. """
python
{ "resource": "" }
q9284
Network.errorFunction
train
def errorFunction(self, t, a): """ Using a hyperbolic arctan on the error slightly exaggerates the actual error non-linearly. Return t - a to just use the difference. t - target vector a - activation vector """ def difference(v): if not self.hyperbolicError: #if -0.1 < v < 0.1: return 0.0 #else: return
python
{ "resource": "" }
q9285
Network.ce_init
train
def ce_init(self): """ Initializes error computation. Calculates error for output layers and initializes hidden layer error to zero. """ retval = 0.0; correct = 0; totalCount = 0 for layer in self.layers: if layer.active: if layer.type == 'Output': layer.error = self.errorFunction(layer.target, layer.activation) totalCount += layer.size retval += Numeric.add.reduce((layer.target - layer.activation) ** 2)
python
{ "resource": "" }
q9286
Network.compute_error
train
def compute_error(self, **args): """ Computes error for all non-output layers backwards through all projections. """ for key in args: layer = self.getLayer(key) if layer.kind == 'Output': self.copyTargets(layer, args[key]) self.verifyTargets() # better have targets set error, correct, total = self.ce_init() pcorrect = {} # go backwards through each proj but don't redo output errors! if len(self.cacheConnections) != 0: changeConnections = self.cacheConnections else: changeConnections = self.connections for connect in reverse(changeConnections): if connect.active and connect.toLayer.active
python
{ "resource": "" }
q9287
Network.compute_wed
train
def compute_wed(self): """ Computes weight error derivative for all connections in self.connections starting with the last connection. """ if len(self.cacheConnections) != 0: changeConnections = self.cacheConnections else: changeConnections = self.connections for connect in reverse(changeConnections): if connect.active and connect.fromLayer.active and connect.toLayer.active: connect.wed = connect.wed + Numeric.outerproduct(connect.fromLayer.activation,
python
{ "resource": "" }
q9288
Network.toString
train
def toString(self): """ Returns the network layers as a string. """ output = ""
python
{ "resource": "" }
q9289
Network.arrayify
train
def arrayify(self): """ Returns an array of node bias values and connection weights for use in a GA. """ gene = [] for layer in self.layers: if layer.type != 'Input':
python
{ "resource": "" }
q9290
Network.unArrayify
train
def unArrayify(self, gene): """ Copies gene bias values and weights to network bias values and weights. """ g = 0 # if gene is too small an IndexError will be thrown for layer in self.layers: if layer.type != 'Input': for i in range(layer.size): layer.weight[i] = float( gene[g]) g += 1 for connection in self.connections: for i
python
{ "resource": "" }
q9291
Network.saveWeightsToFile
train
def saveWeightsToFile(self, filename, mode='pickle', counter=None): """ Deprecated. Use saveWeights instead.
python
{ "resource": "" }
q9292
Network.saveWeights
train
def saveWeights(self, filename, mode='pickle', counter=None): """ Saves weights to file in pickle, plain, or tlearn mode. """ # modes: pickle/conx, plain, tlearn if "?" in filename: # replace ? pattern in filename with epoch number import re char = "?" match = re.search(re.escape(char) + "+", filename) if match: num = self.epoch if counter != None: num = counter elif self.totalEpoch != 0: # use a total epoch, if one: num = self.totalEpoch fstring = "%%0%dd" % len(match.group()) filename = filename[:match.start()] + \ fstring % self.epoch + \ filename[match.end():] self.lastAutoSaveWeightsFilename = filename if mode == 'pickle': mylist = self.arrayify() import pickle fp = open(filename, "w") pickle.dump(mylist, fp) fp.close() elif mode in ['plain', 'conx']: fp = open(filename, "w") fp.write("# Biases\n") for layer in self.layers: if layer.type != 'Input': fp.write("# Layer: " + layer.name + "\n") for i in range(layer.size): fp.write("%f " % layer.weight[i] ) fp.write("\n") fp.write("# Weights\n") for connection in self.connections: fp.write("# from " + connection.fromLayer.name + " to " + connection.toLayer.name + "\n") for i in range(connection.fromLayer.size): for j in range(connection.toLayer.size): fp.write("%f " % connection.weight[i][j] )
python
{ "resource": "" }
q9293
Network.saveNetwork
train
def saveNetwork(self, filename, makeWrapper = 1, mode = "pickle", counter = None): """ Saves network to file using pickle.
python
{ "resource": "" }
q9294
Network.loadInputPatterns
train
def loadInputPatterns(self, filename, cols = None, everyNrows = 1, delim = ' ', checkEven = 1): """ Loads inputs as patterns from file. """
python
{ "resource": "" }
q9295
Network.loadInputs
train
def loadInputs(self, filename, cols = None, everyNrows = 1, delim = ' ', checkEven = 1): """
python
{ "resource": "" }
q9296
Network.loadTargetPatterns
train
def loadTargetPatterns(self, filename, cols = None, everyNrows = 1, delim = ' ', checkEven = 1): """ Loads targets as patterns from file. """
python
{ "resource": "" }
q9297
Network.replacePatterns
train
def replacePatterns(self, vector, layer = None): """ Replaces patterned inputs or targets with activation vectors. """ if not self.patterned: return vector if type(vector) == str: return self.replacePatterns(self.lookupPattern(vector, layer), layer) elif type(vector) != list: return vector # should be a vector if we made it here vec = [] for v in vector: if type(v) ==
python
{ "resource": "" }
q9298
Network.patternVector
train
def patternVector(self, vector): """ Replaces vector with patterns. Used for loading inputs or targets from a file and still preserving patterns. """ if not self.patterned: return vector if type(vector) == int: if self.getWord(vector) != '': return self.getWord(vector) else: return vector elif type(vector) == float:
python
{ "resource": "" }
q9299
Network.getPattern
train
def getPattern(self, word): """ Returns the pattern with key word. Example: net.getPattern("tom") => [0, 0, 0, 1] """ if word in self.patterns:
python
{ "resource": "" }