def _create_neuron(dna: DNASequence, network: NeuralNetwork, neuron: NeuralNetworkNeuron): dna.extend(DNASequences.NEURON_CREATE) neuron_layer_index = network.layers.index(neuron.layer) # write bias float_encode(dna, neuron.bias) for connection in neuron.connections: dna.extend(DNASequences.NEURON_CREATE_LINK) node = connection.node # type: NeuralNetworkNeuron layer_size = len(node.layer.neurons) - 1 if layer_size == 0: layer_size = 1 node_index = node.layer.neurons.index(node) / layer_size * __NEURON_INDEX_REMAP if node.layer == network.input: link_layer_index = -1 else: link_layer_index = network.layers.index(node.layer) relative_index = neuron_layer_index - link_layer_index - 1 float_encode(dna, relative_index + node_index) float_encode(dna, connection.weight)
def encode(dna: DNASequence, value: float, accuracy: float = EPS): r = (-1.0, 0.0, 1.0) while True: # check for match and range control values if abs(r[0] - value) <= accuracy: dna.extend(_SELECT_RANGE_START) break if abs(r[1] - value) <= accuracy: dna.extend(_SELECT_RANGE_CENTER) break if abs(r[2] - value) <= accuracy: dna.extend(_SELECT_RANGE_END) break if value < r[0] or value > r[2]: dna.extend(_INCREASE_RANGE) r = (r[0] * 2, r[1], r[2] * 2) continue if r[0] < value < r[1]: dna.extend(_SELECT_FIRST_HALF) r = (r[0], r[0] + (r[1] - r[0]) * 0.5, r[1]) continue if r[1] < value < r[2]: dna.extend(_SELECT_SECOND_HALF) r = (r[1], r[1] + (r[2] - r[1]) * 0.5, r[2]) continue assert False and "Problem"
def _create_layer(dna: DNASequence, network: NeuralNetwork, layer: NeuralNetworkLayer): dna.extend(DNASequences.NEURON_CREATE_LAYER) for neuron in layer.neurons: _create_neuron(dna, network, neuron)