Machine Learning and GA’s
Lately I’ve been on a learning kick, and the thing that has grabbed my interest as of late is Machine Learning. What the heck is it? How does it work? How does a fellow like yourself with no knowledge of it get started? No worries! All will be revealed soon with this article.
What is Machine Learning?
Long story short, you’re giving a machine the ability to “learn”, where learning is described as “progressively improving at a given task”. You tell the machine to do something, and then you tell it how it can know if it did better at that task. Afterwards, you let it work its magic.
Let me reiterate, you are not programming the machine to *do* a specific task. You’re programming it to learn how to get better at that task. Therein lies all of the difference.
Why do we use it?
Well, as any functional human being can tell you, the real world can get really, really complicated really fast. In some cases if we were to program some problems by brute force, we end up with thousands or even hundreds of thousands of calculations. This isn’t practical or feasible for a programmer to do, not to mention the massive amount of time wasted!
As a second reason, again, the real world is thoroughly complex. This means that in addition to the sheer work hours that would be necessary to create a solution, the best solution may not be obvious to us if we were to directly calculate it. It is, in many ways, far more effective to just have something else “figure it out” for us. That’s where Machine Learning comes in! Specifically, Genetic Algorithms.
What is a Genetic Algorithm?
A genetic algorithm is a common and central technique used in machine learning. The entire idea is based on the whole “survival of the fittest” business. Basically, you randomly create a bunch of solutions to your problem. You then take the solutions that are more “fit”, breed those solutions together and you now have their children. Mutate their children, and repeat that process until you get something that fits well.
So, how do we do it?
Glad you asked, curious reader! As it just so happens I have an example of a simple machine learning program made for you in C#! This is coded from scratch with no frameworks or external functions, so it shouldn’t be too difficult to recreate in a language of your choosing.
Let’s get started with the individual:
Individual.cs:
This contains the fitness, the genelength, and the list of genes. It also just so happens to contain the constructors for the individual, and a function to calculate their fitness.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Genetic_Algorithm
{
class Individual
{
public int fitness = 0;
// Free to modify geneLength
static public int geneLength = 20;
public int[] genes = new int[geneLength]; // Calculates the fitness for this individual.
// If the gene value matches our desired binary, then the fitness increases.
public void FitnessCalc()
{
for(int i = 0; i < geneLength; i++)
{
if(genes[i] == 1)
{
fitness++;
}
}
}
// The individual constructor.
public Individual()
{
for(int i = 0; i < genes.Length; i++)
{
// Generates a bit that is either 1 or 0.
genes[i] = Services.Rand.Next() % 2;
}
}
//individual overload, takes an array.
public Individual(int[] genecombination)
{
for(int i = 0; i < geneLength; i++)
{
// Clone to avoid pass by reference issues.
genes = (int[])genecombination.Clone();
}
}
}
}
Population.cs:
Contains values for the population size, the fittest and second fittest values, and an array of all of the individuals.
Get Christopher Tiller’s stories in your inbox
Join Medium for free to get updates from this writer.
It contains a method to initialize the population, to get the fittest individuals, and make every individual calculate their own fitness.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Genetic_Algorithm
{
class Population
{
// Free to modify popsize.
static public int PopSize = 30;
public int fittest = 0;
public int secondFittest = 0;
public Individual[] individuals = new Individual[PopSize];
// Initialize population
public void InitializePopulation(int size)
{
for (int i = 0; i < individuals.Count(); i++)
{
individuals[i] = new Individual();
}
}
// Get the fittest individual(s) Free to modify percentage.
public Individual[][] GetFittestIndividuals(int percentage)
{
// Sort the individuals:
var fitIndividuals = new Individual[2][];
var individualCount = percentage * individuals.Count() / 100;
fitIndividuals[0] = individuals.OrderByDescending(o => o.fitness).Take(individualCount).ToArray();
fittest = fitIndividuals[0].First().fitness;
secondFittest = fitIndividuals[0].Distinct().Skip(1).First().fitness; // The least fit individuals
fitIndividuals[1] = individuals.OrderBy(o => o.fitness).Take(individualCount).ToArray();
return fitIndividuals;
}
public void CalculateFitness()
{
// We calculate the fitness of each individual.
for(int i = 0; i < individuals.Count(); i++)
{
individuals[i].FitnessCalc();
} // After calculating the fitness, we find the fittest individuals.
GetFittestIndividuals(10);
}
}
}
Scheme.cs:
Contains a variable for the entire population, for the fittest genes in a population, one to create a child gene, and one to calculate the current generation.
More importantly, it contains our Selection, Crossover, Mutation, offspring, and new population creation functions. These are what handle the process outlined earlier.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Genetic_Algorithm
{
class Scheme
{
public Population population = new Population();
public Individual[] fittest;
int[] childGene = new int[Individual.geneLength];
public int generationCount = 0; // Selection
public void Selection()
{
// Getting all of the most fit individuals
fittest = population.GetFittestIndividuals(10)[0];
} // Crossover
public int[] Crossover()
{
// Shuffle the array of the fittest first.
var randomizedFittest = fittest.OrderBy(x => Services.Rand.Next()).ToArray();
// Select a random cutoff fitness
int cutoff = Services.Rand.Next(population.secondFittest);
int count = fittest.Count();
// Get two members of the current generation that are above or equal to this fitness.
Individual[] breedPair = new Individual[2];
for (int i = 0; i < count; i++)
{
// This is the first to breed.
if(fittest[i].fitness >= cutoff)
{
if (breedPair[0] != null)
{
breedPair[1] = randomizedFittest[i];
} else
{
breedPair[0] = randomizedFittest[i];
}
}
}
// Select a random crossover point
int crossOverPoint = Services.Rand.Next(Individual.geneLength);
// Do the crossover.
for(int i = 0; i < Individual.geneLength; i++)
{
//Console.WriteLine(i);
if(i < crossOverPoint)
{
childGene[i] = breedPair[0].genes[i];
} else
{
childGene[i] = breedPair[1].genes[i];
}
}
return childGene;
}
// Mutation
public void Mutation()
{
int count = fittest.Count();
// Loop through every child in the new population
foreach (var child in population.individuals)
{
// loop through every gene...
for(int i = 0; i < child.genes.Count(); i++)
{
// Check random probability...
// 1/10 of the time, we mutate.
// Free to modify % 10 <= 1 to change mutation.
if(Services.Rand.Next() % 10 <= 1)
{
//Flip values at the mutation point
if (child.genes[i] == 0)
{
child.genes[i] = 1;
}
else
{
child.genes[i] = 0;
}
}
}
}
}
// Get fittest offspring
public Individual GetFittestOffspring()
{
if (fittest[0].fitness > fittest[1].fitness)
{
return fittest[0];
}
return fittest[1];
} // Create new population
public void CreateNewPopulation()
{
var newPop = new Population();
for(int i = 0; i < Population.PopSize; i++)
{
Crossover();
var newIndividual = new Individual(childGene);
newPop.individuals[i] = newIndividual;
} // Replace the old population with a new population.
population = newPop;
}
}
}
Program.cs:
This is where we run our program. It handles the initialization, selection, crossing, mutation, and new generations.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Genetic_Algorithm
{
class Program
{
static void Main(string[] args)
{
Scheme demo = new Scheme();
// Initialize population
demo.population.InitializePopulation(Population.PopSize);
demo.population.CalculateFitness(); Console.WriteLine($"Generation: {demo.generationCount} , Fittest: {string.Join(",", demo.population.individuals.OrderByDescending(x => x.fitness).First().genes)} : {demo.population.fittest}");
while(demo.population.fittest < Individual.geneLength && demo.generationCount < 100)
{
demo.generationCount++;
// Do selection.
demo.Selection();
// Breed and create a new population.
demo.CreateNewPopulation();
// Mutate new population.
demo.Mutation();
// Calculate fitness and log to console.
demo.population.CalculateFitness();
Console.WriteLine($"Generation: {demo.generationCount} , Fittest: {string.Join(",",demo.population.individuals.OrderByDescending(x => x.fitness).First().genes)} : {demo.population.fittest}");
}
Console.ReadLine();
}
}
}
There’s also a Services.cs file that contains the random function:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Genetic_Algorithm
{
class Services
{
static public Random Rand { get; set; } = new Random();
}
}
And with that, we’re done! Running the program, we get something like:
Generation: 0 , Fittest: 1,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,1,1,0,1 : 14
Generation: 1 , Fittest: 1,1,0,1,0,1,1,1,1,0,1,1,0,1,0,1,1,1,1,1 : 15
Generation: 2 , Fittest: 1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1 : 16
Generation: 3 , Fittest: 1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1 : 17
Generation: 4 , Fittest: 1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1 : 18
Generation: 5 , Fittest: 1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1 : 18
Generation: 6 , Fittest: 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 : 20And that’s all! Some takeaways:
1: Genetic Algorithms are a totally different way of thinking. Instead of Explicitly programming something, you program something to get better at a task. By doing this it can get scarily close to mimicking real life!
2: While this example may have completed for some, it may not complete for everyone. That’s perfectly fine, because what we’re looking for is good enough, not perfect. In the real world a lot of solutions are never mathematically exact, and machine learning is no different. As long as you’re really close to the answer you want, then that’s good enough!
That’s it for this blog post. Let me know what you think in the comments!






