示例#1
0
        /// <summary>
        /// 基因交叉操作,单点交叉
        /// </summary>
        public static void CompleteCrossover(Genotype parent1, Genotype parent2, float swapChance, out Genotype offspring1, out Genotype offspring2)
        {
            int parameterCount = parent1.ParameterCount;

            float[] off1Parameters = new float[parameterCount];
            float[] off2Parameters = new float[parameterCount];

            //遍历所有参数,随机交换
            for (int i = 0; i < parameterCount; i++)
            {
                //如果生成的随机数小于交换参考值,则进行交换
                if (MathHelper.RandomNext() < swapChance)
                {
                    //交互参数
                    off1Parameters[i] = parent2[i];
                    off2Parameters[i] = parent1[i];
                }
                else
                {
                    //不进行交换,直接遗传到子基因
                    off1Parameters[i] = parent1[i];
                    off2Parameters[i] = parent2[i];
                }
            }
            //根据新的参数矩阵生成新的基于型
            offspring1 = new Genotype(off1Parameters);
            offspring2 = new Genotype(off2Parameters);
        }
示例#2
0
 /// <summary>
 /// 基因变异操作
 /// </summary>
 public static void MutateGenotype(Genotype genotype, float mutationProb, float mutationAmount)
 {
     //mutationProb 一个参数被突变的概率
     //mutationAmount 默认的变异参数
     for (int i = 0; i < genotype.ParameterCount; i++)
     {
         if (MathHelper.RandomNext() < mutationProb)
         {
             //控制变异后的参数在一定的量内
             genotype[i] += (float)(MathHelper.RandomNext() * (mutationAmount * 2) - mutationAmount);
         }
     }
 }
 /// <summary>
 /// 构造遗传代理
 /// </summary>
 /// <param name="_genotype">基因</param>
 /// <param name="_activation">激活函数</param>
 /// <param name="_topogy">拓扑结构</param>
 public Agent(Genotype _genotype, NeuralLayer.ActivationFunction _activation, params uint[] _topogy)
 {
     Genotype = _genotype;
     FNN = new NeuralNetwork(_topogy);
     foreach (NeuralLayer layer in FNN.Layers)
     {
         layer.NeuronActivationFunction = _activation;
     }
     if(FNN.WeightCount != _genotype.ParameterCount)
         throw new ArgumentException("WeightCount != Topology");
     //使用基因参数初始化神经网络
     IEnumerator<float> parameters = _genotype.GetEnumerator();
     foreach (NeuralLayer layer in FNN.Layers)
     {
         for (int i = 0; i < layer.Weights.GetLength(0); i++)
         {
             for (int j = 0; j < layer.Weights.GetLength(1); j++)
             {
                 layer.Weights[i, j] = parameters.Current;
                 parameters.MoveNext();
             }
         }
     }
 }
 public int CompareTo(Agent other)
 {
     return Genotype.CompareTo(other.Genotype);
 }