What's wrong with this simple Genetic Algorithm?

  • Thread starter Thread starter Superposed_Cat
  • Start date Start date
  • Tags Tags
    Algorithm
Click For Summary
The discussion centers around troubleshooting a non-functioning genetic algorithm implementation. Key points include the importance of debugging techniques such as stepping through the code and using print statements to identify issues. Participants emphasize the need for clarity in the code, suggesting that the absence of comments makes it difficult to understand the logic and purpose of various functions, particularly the fitness function. Concerns are raised about the algorithm's convergence and efficiency, with suggestions to ensure that the problem genuinely requires a genetic algorithm, as these methods can be slow. The conversation highlights the necessity of unit testing individual functions before integrating them into the overall program to diagnose and resolve issues effectively.
Superposed_Cat
Messages
388
Reaction score
5
Hey all, writing this simple genetic algorithm but its not working. Any idea why?

C:
static int len = 30;
        static char[,] dog = new char[len, 30];
        static void breed()
        {
            sort();
            int Ii0 = r.Next(0,15);
            int Ii1=r.Next(0,15);
            string i0 = get(Ii0);
          
            string i1 = get(Ii1);
            Cross(Ii0, Ii1);
            Mut(r.Next(0,10), r.Next(0,30),3);
        }
        static void sort()
        {
            for (int p = 0; p < 30; p++)
            {
                for (int i = 0; i < 30 - 1; i++)
                {
                    if (fitness(i) > fitness(i + 1))
                    {
                        string i0 = get(i);
                        string i1 = get(i + 1);
                        set(i, i1);
                        set(i + 1, i0);
                    }
                }
            }
        }
     
        static int getnum(string s)
        {
            int u = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == (int)'1')
                {
                    u++;
                }
                else if ((int)s[i] == (int)'-')
                {
                    u--;
                }
            }
            return u;
        }
        static double fitness(int y)
        {
            dog.ToString();
            string s = get(y);
            int u = getnum(get(y));
              return ( 1 / ((2 * u * u) + (33.25f * u) + 20));//30//-30
      ;
        }
        static double fitness(string y)
        {       
            int u = getnum(y);
            return ( 1 / ((2 * u * u) + (33.25f * u) + 20));//30//-30
        }
        static void init()
        {
            string[] lines = System.IO.File.ReadAllLines("C:/users/e/desktop/init.txt");
                               //      StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < len; i++)
            {
                for (int j = 0; j < 30; j++)
                {
                    dog[i, j] = lines[i][j];
                }
            }
          
        }
        static void Mut(int chr,int pos,int chance)
        {
            var yy = r.Next(0,300);
            if (r.Next(0, 100) < chance)
            {

                if (dog[chr, pos] == '0')
                {
                    if (r.Next(100) < 50)
                    {
                        dog[chr, pos] = '1';
                    }
                    else
                    {
                        dog[chr, pos] = '-';
                    }

                }

                if (dog[chr, pos] == '1')
                {
                    if (r.Next(100) < 50)
                    {
                        dog[chr, pos] = '0';
                    }
                    else
                    {
                        dog[chr, pos] = '-';
                    }

                }

                if (dog[chr, pos] == '-')
                {
                    if (r.Next(100) < 50)
                    {
                        dog[chr, pos] = '1';
                    }
                    else
                    {
                        dog[chr, pos] = '0';
                    }

                }

            }
        }
       static Random r = new Random();
        static void Cross(int j, int k)
        {
            for (int i = 0; i < len; i++)
            {
                if (r.Next(100) < 50)
                {
                    char jt = dog[j, i];
                    char kt = dog[k, i];
                    dog[k, i] = jt;
                    dog[j, i] = kt;
                }
            }
        }
        static string get(int y)
        {
            string h = "";
            for (int i = 0; i < 30; i++)
            {
                h += dog[y, i];
            }
            return h;
        }
        static void set(int y,string s)
        {
            for (int i = 0; i < 30; i++)
            {
                dog[y, i] = s[i];
            }
        }
        static void Main(string[] args)
        {
            init();
            for (int i = 0; i < len; i++)
            {
                Console.WriteLine(getnum(get(i)));
            }
       
            for (int j = 0; j < 10; j++)
            {
                for (int i = 0; i < 400; i++)
                {
                    breed();
                 
                }
                sort();
                Console.WriteLine(fitness(0));
                Console.WriteLine(getnum(get(0)));
            }
            for (int i = -30; i < 30; i++)
            {
                Console.WriteLine(i.ToString() + ":" + (i).ToString());
            }
       
            Console.Read();
        }
Any help apreciated.
 
Technology news on Phys.org
Have you stepped through your code with a debugger line by line?

Or inserted print statements where you think the error is?

Are you using an IDE to develop the code? They usually have a debugger that can be used.

Also your code doesn't look formatted cleanly, again an IDE will usually have a source reformat action.
 
Yes,
Yes,
Yes,
Yes,

I meant is there a logical error in my fitness function, crossover, mutation etc? The general steps of the GA, its supposed to find the minimum of a function.
 
"It's not working" doesn't give us much of a clue. If it's not working, give us a hint, such as what it should be doing vs. what it's actually doing.

You asked whether there was a logical error in your fitness function, one overload of which is this one:
Code:
static double fitness(string y)
        {       
            int u = getnum(y);
            return ( 1 / ((2 * u * u) + (33.25f * u) + 20));//30//-30
        }
Logic error? Hard to say without knowing what the purpose of this code is. I don't see a single explanatory comment in your code, not counting where you have commented out some code.

It's not obvious from looking what some of the other functions you asked about are doing.
 
If you think something is wrong with your fitness function then why not unit test ie test it by itself giving it some input and see if you get the expected result.

Writing programs doesn't mean write and test it whole. It really means unit test each function or method and then combine them together and test the bigger assembly of components. It's the only way to really know if your program will perform.
 
  • Like
Likes FactChecker
Ive tried doing everything seperatly, every function seems to work by itself, but as a whole it doesn't, maybe I am leaving something out or doing it in the wrong order?
Mark44 said:
"It's not working" doesn't give us much of a clue. If it's not working, give us a hint, such as what it should be doing vs. what it's actually doing.

You asked whether there was a logical error in your fitness function, one overload of which is this one:
Logic error? Hard to say without knowing what the purpose of this code is. I don't see a single explanatory comment in your code, not counting where you have commented out some code.

It's not obvious from looking what some of the other functions you asked about are doing.
Superposed_Cat said:
ts supposed to find the minimum of a function.

Sorry should have put it in main post.
 
You're missing the point here. "Its not working" doesn't tell us anything.

If you tell me you got a NullPointerException on line 999 then I have something to go on. In general, we are sight reviewing your code. We aren't actually trying to run it trying to look for possible trouble spots for you to investigate.

I guess the problem you are encountering is that it runs for a long time and never converges onto the answer you expect and so its not working. These kinds of problems are some of the hardest to diagnose and in the end only the programmer who wrote the code needs to suffer through the analysis and figure out why things aren't working as expected.

Doing so will make you a better programmer.

My understanding of GA's are that they follow theses steps:
- initially generate a set of solution vectors
- scores the solution vectors
- use some sort of cutoff that passes half and discards half of the solutions
- use the "good" solutions to make new solutions using random adjustments or element swapping between any two good solutions
- and repeating the steps until the "best" solutions are found.

http://en.wikipedia.org/wiki/Genetic_algorithm
 
  • Like
Likes Mark44
The reason it isn't working is because there are no comments. Go through and comment every line and I'll bet it works (because you will find the error while writing the comments). If, by chance,I am wrong and you don't find the error, then at least we will understand what you are trying to do and be able to help.
 
  • Like
Likes Mark44 and DrClaude
Before all :
Are you sure that your problem absolutely need an génétic algorithm ?
Gradient, levemberg maquardt, gauss-Newton fail ?
Don't forget that genetic algorithm are SLOW !
 

Similar threads

  • · Replies 0 ·
Replies
0
Views
626
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 5 ·
Replies
5
Views
1K
Replies
2
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
Replies
5
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
Replies
55
Views
6K
Replies
3
Views
1K