# What's wrong with this simple Genetic Algorithm?

• Superposed_Cat
In summary, the conversation is about a person trying to write a genetic algorithm but it is not working. They discuss the code and functions involved, including a breeding function, sorting function, and fitness function. They also mention a file used for initialization.
Superposed_Cat
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()
{
//      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());
}

}
Any help apreciated.

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.

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

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.

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 !

## 1. What is a Genetic Algorithm?

A Genetic Algorithm (GA) is a heuristic search and optimization technique inspired by the process of natural selection in biological evolution. It is used to find optimal solutions to complex problems by simulating the process of natural selection, crossover, and mutation in a population of potential solutions.

## 2. What are the key components of a Genetic Algorithm?

The key components of a Genetic Algorithm include the initial population of potential solutions, a fitness function to evaluate the solutions, selection methods to choose the fittest solutions, crossover and mutation operators to create new solutions, and termination criteria to end the algorithm when a satisfactory solution is found.

## 3. What are some common problems with Genetic Algorithms?

Some common problems with Genetic Algorithms include premature convergence, where the algorithm gets stuck in a local optimum instead of finding the global optimum, and the loss of diversity in the population which can lead to a lack of exploration and suboptimal solutions.

## 4. How can the performance of a Genetic Algorithm be improved?

The performance of a Genetic Algorithm can be improved by fine-tuning the parameters such as the population size, selection methods, crossover and mutation rates, and termination criteria. Additionally, using adaptive methods to adjust these parameters during the algorithm can also improve its performance.

## 5. What are some applications of Genetic Algorithms?

Genetic Algorithms have been used in a variety of fields such as engineering, economics, finance, and computer science to solve complex optimization problems. Some common applications include scheduling, routing, design optimization, and machine learning.

• Programming and Computer Science
Replies
55
Views
4K
• Programming and Computer Science
Replies
3
Views
2K
• Programming and Computer Science
Replies
5
Views
1K
• Programming and Computer Science
Replies
9
Views
2K
• Programming and Computer Science
Replies
5
Views
1K
• Programming and Computer Science
Replies
1
Views
1K
• Programming and Computer Science
Replies
9
Views
1K
• Programming and Computer Science
Replies
3
Views
3K
• Programming and Computer Science
Replies
2
Views
2K
• Programming and Computer Science
Replies
3
Views
951