Exemple #1
0
 def __init__(self,
              id,
              layer,
              boxid,
              u,
              sigma,
              birth,
              modelConfiguration={},
              coord=None):
     '''
     特征神经元,每个神经元表达一个特征值
     :param id:                  int  id
     :param layer:               int  所属层
     :param boxid:               int  所属盒子id
     :param u:                   list 中心特征值
     :param sigma:               list of list 方差
     :param birth:               int  出生年代
     :param modelConfiguration:  dict 模型配置
     :param coord:               list 坐标
     '''
     Neuron.__init__(self, id, layer, birth, modelConfiguration, coord)
     self.states['activation'] = 0.
     #self.state['clock'] = 0
     self.features = {}
     self.features['liveness'] = 0.
     self.u = u
     self.sigma = sigma
     self.boxid = boxid
     self.history_states = []
     self.cur_capcity_count = 0
    def createLayer(self, layerIndex, modelConfig):
        if layerIndex < 0 or layerIndex >= len(self.definition.neuronCounts):
            raise RuntimeError('createLayer failed: invaild layerIndex:' +
                               str(layerIndex))
        count = self.definition.neuronCounts[layerIndex]
        # 计算实际层编号
        layerInterval = int((self.definition.config.range[0][1] -
                             self.definition.config.range[0][0]) /
                            (len(self.definition.neuronCounts) - 1))
        layer = 0
        if layerIndex == 0: layer = self.definition.config.range[0][0]
        elif layerIndex == len(self.definition.neuronCounts) - 1:
            layer = self.definition.config.range[0][1]
        else:
            layer = self.definition.config.range[0][
                0] + layerIndex * layerInterval

        while len(self.neurons) <= layerIndex:
            self.neurons.insert(layerIndex, [])
        # 生成神经元坐标
        idGenerator = idGenerators.find(self.definition.idGenerator)
        coords = self.__createCoord(layer, count)

        # 创建神经元
        for i in range(count):
            coord = coords[i]
            neuronid = idGenerator.getNeuronId(self, coord, None)
            neuron = Neuron(neuronid, layer, 0, modelConfig, coord)
            self.neurons[layerIndex].append(neuron)

        return self.neurons[layerIndex]
    def __createLayerNeuron(self, net, netdef, layerIndex, count, modelConfig):
        if count <= 0: return None

        # 计算实际层编号
        layerInterval = int(
            (netdef.config.range[0][1] - netdef.config.range[0][0]) /
            (len(netdef.neuronCounts) - 1))
        layer = 0
        if layerIndex == 0: layer = 0
        elif layerIndex == len(netdef.neuronCounts) - 1:
            layer = netdef.config.range[0][1]
        else:
            layer = layerIndex * layerInterval

        # 生成神经元坐标
        idGenerator = networks.idGenerators.find(netdef.idGenerator)
        while len(net.neurons) <= layerIndex:
            net.neurons.insert(layerIndex, [])
        coords = self.__createCoord(netdef, layer, count)

        # 创建神经元
        for i in range(count):
            coord = coords[i]
            neuronid = idGenerator.getNeuronId(net, coord, None)
            neuron = Neuron(neuronid, layer, 0, modelConfig, coord)
            net.neurons[layerIndex].append(neuron)

        return net.neurons[layerIndex]
Exemple #4
0
    def __do_mutate_addnode(self, ind, session):
        net = ind.genome
        synapses = net.getSynapses()
        synapse = None
        if len(synapses) <= 0:
            r, msg, synapse = self.____do_mutate_addconnection(ind)
        else:
            synapse = choice(synapses)

        fromneuron = net.getNeuron(synapse.fromId)
        toneuron = net.getNeuron(synapse.toId)
        neuronModel = net.definition.models.hidden
        synapseModel = net.definition.models.synapse
        newNeuronLayer = int((toneuron.layer + fromneuron.layer) / 2)
        idgenerator = networks.idGenerators.find(net.definition.idGenerator)
        newNeuronid = idgenerator.getNeuronId(net, None, synapse)
        newNeuron = Neuron(newNeuronid, newNeuronLayer, session.curTime,
                           neuronModel)
        net.putneuron(newNeuron, fromneuron.id, toneuron.id, synapseModel)
        net.remove(synapse)

        return True, '', 'addnode', newNeuron
    def put(self,
            birth,
            coord,
            layer,
            neuronModelConfig,
            id=None,
            inids=None,
            outinds=None,
            synapseModelConfig=None):
        '''
        添加神经元
        :param birth:                int or float 添加时间,必须
        :param coord:                Coordinate   坐标,可选
        :param layer:                int          层,必须
        :param neuronModelConfig:    dict 神经计算模型配置,必须
        :param id                    int  神经元id,可选,如果无效,会尝试生成一个,但是要求coord有效
        :param inids:                int or list,输入神经元id
        :param outinds:              int or list,输入神经元id
        :param synapseModelConfig:   dict,突触计算模型配置
        :return:
        '''
        if birth < 0: raise RuntimeError('添加神经元失败(NeuralNetwork.put):birth无效')
        #if layer < 0:raise  RuntimeError('添加神经元失败(NeuralNetwork.put):layer无效')
        if neuronModelConfig is None:
            raise RuntimeError(
                '添加神经元失败(NeuralNetwork.put):neuronModelConfig无效')
        idGenerator = idGenerators.find(
            self.definition.get('idGenerator', 'default'))
        if idGenerator is None:
            raise RuntimeError(
                "连接神经元失败(NeuralNetwork.connect(srcid,destid)):idGenerator无效")

        if id is None:
            id = idGenerator.getNeuronId(self, coord, None)
        n = Neuron(id, layer, birth, neuronModelConfig, coord)
        return self.putneuron(n, inids, outinds, synapseModelConfig)
Exemple #6
0
    def create(self,popParam):
        # 取得个体类型,神经网络
        indType = agent.individualTypes.find(popParam.indTypeName)
        netdef = popParam.genomeDefinition
        idGenerator = networks.idGenerators.find(netdef.idGenerator)

        genomeFactory = indType.genomeFactory
        if popParam.genomeFactory is not None: genomeFactory = popParam.genomeFactory
        factoryParam = popParam.factoryParam

        size = popParam.size

        genomes = []
        for i in range(size):
            netid = idGenerator.getNetworkId()
            net = NeuralNetwork(netid,netdef)

            # 创建输入神经元
            for i in range(netdef.neuronCounts[0]):
                # 创建输入神经元
                neuron = Neuron(idGenerator.getNeuronId(),0,0,netdef.models.input)
                # 创建输入神经元的模块
                module_sensor = Module(idGenerator.getModuleId(),0,[],[],[neuron])
                module_sensor.attributes['attention'] = 'sensor'
                # 创建输入神经元的值分布模块
                module_sensor_distribution = Module(idGenerator.getModuleId(),0,[module_sensor],[],[])
                module_sensor_distribution.attributes['attentation'] =
                net.putneuron(neuron)
                net.putmodule(module_sensor)

            self.__createLayerNeuron(net,netdef,0,netdef.neuronCounts[0],netdef.models.input)


            # 创建输出神经元
            self.__createLayerNeuron(net,netdef,len(netdef.neuronCounts)-1,netdef.neuronCounts[-1], netdef.models.output)

            # 创建输入神经元的值分布模块


            # 创建中间神经元(如果有)
            hiddenCount = netdef.neuronCounts[1:-1]
            if not collections.isEmpty(hiddenCount):
                for i in range(len(hiddenCount)):
                    self.__createLayerNeuron(net, netdef, i+1, netdef.neuronCounts[i+1], netdef.models.input)

            genomes.append(net)
            # 初始化连接
            if popParam.factoryParam.connectionRate <= 0:         #初始无连接
                continue
            elif popParam.factoryParam.connectionRate >= 1:       #初始全连接
                for i in range(len(net.neurons)-1):
                    for j,n1 in enumerate(net.neurons[i]):       # 取第i层神经元
                        for k,n2 in enumerate(net.neurons[i+1]): # 取第i+1层神经元
                            synapseid = idGenerator.getSynapseId(net,n1.id,n2.id)
                            synapse = Synapse(synapseid,0,n1.id,n2.id,netdef.models.synapse)
                            net.synapses.append(synapse)
            else:                                                # 以一定概率进行连接
                allsynapse = []
                for i in range(len(net.neurons)-1):
                    for j,n1 in enumerate(net.neurons[i]):       # 取第i层神经元
                        for k,n2 in enumerate(net.neurons[i+1]): # 取第i+1层神经元
                            allsynapse.append((n1,n2))
                synapsecount = int(len(allsynapse)*popParam.factoryParam.connectionRate)
                if synapsecount > 0 :
                    indexes = np.random.uniform(0,len(allsynapse)-1,synapsecount)
                    for i in indexes:
                        n1 = allsynapse[i][0]
                        n2 = allsynapse[i][1]
                        synapseid = idGenerator.getSynapseId(net, n1.id, n2.id)
                        synapse = Synapse(synapseid, 0, n1.id, n2.id, netdef.models.synapse)
                        net.synapses.append(synapse)


            logging.debug('# neat工厂创建网络:'+str(net))

        return genomes