遗传算法通用写法C#

遗传算法是通过模拟生物进化而进行数据寻优的一种进化算法。主要过程是初始种群的产生,选择,交叉,变异,循环迭代,直至出现最优解。本程序两个主要类,种群类与个体类。定义进化策略接口,计算适应度策略接口。进化策略接口实现三个行为,交叉,变异,选择,其中,进化策略接口可以加上自己的实现。大致实现如下:

//
//class Population
//
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace SGA.SingleGA
{
     /*
     群体类,实现了种群初始化,有交叉,变异行为,选择等行为。同时统计种群的平均适应度,最大适应度,适应度之和。
     */
    public class Population : CollectionBase,ICloneable,IDisposable
    {
        private IGeneticStrategy _iGeneticStrategy;
       
        public Population(IGeneticStrategy iGeneticStrategy) { this._iGeneticStrategy = iGeneticStrategy; }
        public Population() { }
        public void Init(int iMax)
        {
            Random rd = new Random();
            for (int i = 0; i < iMax; i++)
            {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < 22; j++)
                {
                    sb.Append(rd.Next(0,2));
                }
                this.List.Add(new Individual(sb.ToString()));
            }
        }
        public double MaxFitness
        {
            get
            {
                double dmax = double.MinValue;
                for (int i = 0; i < List.Count; i++)
                {
                    if ((List[i] as Individual).Fitness > dmax) dmax = (List[i] as Individual).Fitness;
                }
                return dmax;
            }          
        }
        public double AverageFitness
        {
            get
            {
                return SumFitness / List.Count;
            }
        }
        public double SumFitness
        {
            get
            {
                double dSum = 0;
                for (int i = 0; i < List.Count; i++)
                {
                    dSum += (List[i] as Individual).Fitness;
                }
                return dSum;
            }
        }
        public IGeneticStrategy GeneticStrategy
        {
            get { return this._iGeneticStrategy; }
            set { this._iGeneticStrategy = value; }
        }
        public Population Select()
        {
            if (_iGeneticStrategy == null) return null;
            return _iGeneticStrategy.Select(this);
        }

        public void Crossover()
        {
            if (_iGeneticStrategy == null) return;
            _iGeneticStrategy.Crossover(this);
        }
        public void Mutation()
        {
            if (_iGeneticStrategy == null) return;
            _iGeneticStrategy.Mutation(this);
        }

        public Individual this[int index]
        {
            get { return (Individual)this.List[index]; }
            set { this.List[index] = value; }
        }
        public void Add(Individual ind)
        {
            this.List.Add(ind);
        }
        public int Indexof(Individual ind)
        {
            return this.List.IndexOf(ind);
        }
        public void Print()
        {
            for (int i = 0; i < List.Count; i++)
            {
                Console.WriteLine(“第{0}个体fit={2} {1}”, i.ToString(), (List[i] as Individual).Variable.ToString(), (List[i] as Individual).Fitness);
            }
        }
      

        #region ICloneable 成员

        public object Clone()
        {
            Population pop = new Population(this.GeneticStrategy);
            for (int i = 0; i < this.List.Count; i++)
                pop.List.Add(this.List[i]);
            return pop;
        }

        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            _iGeneticStrategy = null;
        }

        #endregion
    }
}

//
//Individual
//

using System;
using System.Collections.Generic;
using System.Text;

namespace SGA.SingleGA
{
    public class Individual : ICloneable
    {
        private string _gene;
        private double _fitness = double.MinValue;
        public static IFitness _calFit = new OneDFitness();
        public string Gene
        {
            get { return _gene; }
            set
            {
                _gene = value;
                _fitness = _calFit.Fitness(Variable);
            }
        }
        public double Fitness
        {
            get { return _fitness; }
        }
        public double Variable
        {
            get { return Coder.ToReal(_gene, -1.0, 2.0); }
        }
        public Individual()
        {
        }
        public Individual(string sGene)
        {
            Gene = sGene;
        }
        public Individual(string sGene,IFitness calFit)
        {
            _calFit = calFit;
            this.Gene = sGene;
        }
        //public IFitness CalFit
        //{
        //    get { return this._calFit; }
        //    set
        //    {
        //        this._calFit = value;
        //        _fitness = _calFit.Fitness(Coder.ToReal(_gene, -1.0, 2.0));
        //    }
        //}

        public int ToMetrication()
        {
            return Convert.ToInt32(Gene, 2);
        }

        public static int operator * (Individual ind1,Individual ind2)
        {
            Random rd = new Random();
            int iStart = rd.Next(0, ind1.Gene.Length-2);
            int iLast = rd.Next(iStart+1,ind1.Gene.Length-1);
            while (ind1.Gene.Substring(iStart, iLast – iStart) == ind2.Gene.Substring(iStart, iLast – iStart))
            {
                iStart = rd.Next(0, ind1.Gene.Length – 2);
                iLast = rd.Next(iStart + 1, ind1.Gene.Length – 1);
            }

            StringBuilder sbGene1 = new StringBuilder();
            sbGene1.Append(ind1.Gene.Substring(0, iStart));
            sbGene1.Append(ind2.Gene.Substring(iStart, iLast-iStart));
            sbGene1.Append(ind1.Gene.Substring(iLast));
            StringBuilder sbGene2 = new StringBuilder();
            sbGene2.Append(ind2.Gene.Substring(0, iStart));
            sbGene2.Append(ind1.Gene.Substring(iStart,iLast-iStart));
            sbGene2.Append(ind2.Gene.Substring(iLast));
            ind1.Gene = sbGene1.ToString();
            ind2.Gene = sbGene2.ToString();

            return iLast – iStart;
        }
        public int Crossover(Individual ind)
        {
            return this * ind;
        }
        public int Mutation()
        {
            Random rd = new Random();
            int iPos = rd.Next(0, this.Gene.Length-1);
            StringBuilder sb = new StringBuilder(this.Gene);
            sb[iPos] = sb[iPos] == ‘0’ ? ‘1’ : ‘0’;
            this.Gene = sb.ToString();
            return iPos;
        }

       

        public override string ToString()
        {
            return this.Gene;
        }
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        #region ICloneable 成员

        public object Clone()
        {
            return new Individual(this.Gene);
        }

        #endregion
    }
}

    原文作者:遗传算法
    原文地址: https://blog.csdn.net/ysg8422am/article/details/4773604
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞