Pular para o conteúdo principal

Genetic algorithms with Java

One of the most fascinating topics in computer science world is Artificial Intelligence. A subset of Artificial intelligence are the algorithms that were created inspired in the nature. In this group, we have Genetic Algorithms (GA).



Genetic Algorithms 



To find out more about this topic I recommend the following MIT lecture and the Nature of Code book and videos created by Daniel Shiffman.









Genetic Algorithms using Java



After I remembered the basics about it, I wanted to practice, so I tried my own implementation, but I would have to write a lot of code to do what certainly others already did. So I started looking for Genetic Algorithm libraries and found Jenetics, which is a modern library that uses Java 8 concepts and APIs, and there's also JGAP. I decided to use Jenetics because the User Guide was so clear and it has no other dependency, but Java 8.
The only thing I missed for Jenetics are more small examples like the ones I will show in this post. They have examples, one very basic that you can find in user guide and a complex one.


Simple Genetic Algorithms examples using Jenetics



I have to say that this all happened last 2 days! Therefore, I am not a genetic algorithm specialist, but a hobbyist. I even had to ask Jenetics twitter if I was doing it right.




And at that point I was calling what can be interpreted as the number of generations as the population. I still have a lot to learn and improve how I use the library and the fitness methods I created, but here are some examples:

Select double numbers with the largest digits sum: That's not the most suitable use for genetic algorithms, but it is a way to get familiar with the API and its concepts. The idea was to keep the population that has the largest sum of all numbers digits. I used only a few lines of code to create this small example, but the reason is that Jenetics has a few built in chromosomes, including a LongChromosome:

import java.util.concurrent.atomic.AtomicInteger;
import org.jenetics.Genotype;
import org.jenetics.LongChromosome;
import org.jenetics.LongGene;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.util.Factory;
/**
*
* Select the genotype with greatest algorithms sum
*
* @author wsiqueir
*
*/
public class LargestDigitSum {
private static Integer fitness(Genotype<LongGene> lt) {
LongChromosome lc = lt.getChromosome().as(LongChromosome.class);
AtomicInteger sum = new AtomicInteger(0);
lc.stream().forEach(l -> {
String str = String.valueOf(l.longValue());
for (char ch : str.toCharArray()) {
sum.addAndGet(Integer.parseInt(String.valueOf(ch)));
}
});
System.out.println(lt + ", sum " + sum.get());
return sum.get();
}
public static void main(String[] args) {
Factory<Genotype<LongGene>> gtf = Genotype.of(LongChromosome.of(1, 100, 3));
Engine<LongGene, Integer> engine = Engine.builder(LargestDigitSum::fitness, gtf).build();
Genotype<LongGene> result = engine.stream().limit(10).collect(EvolutionResult.toBestGenotype());
System.out.println("Selected: " + result + ". Sum: " + fitness(result));
}
}
It will produce an output like the following:

[[[85],[23],[62]]], sum 26
[[[42],[5],[53]]], sum 19
[[[4],[82],[14]]], sum 19
[[[17],[99],[41]]], sum 31
[[[32],[16],[23]]], sum 17
[[[15],[85],[38]]], sum 30
[[[54],[30],[51]]], sum 18
[[[31],[20],[76]]], sum 19
[[[88],[63],[69]]], sum 40
[[[52],[11],[6]]], sum 15
 (... lot of intermediate steps..)
[[[88],[97],[97]]], sum 48
[[[88],[97],[97]]], sum 48
[[[88],[29],[25]]], sum 34
[[[88],[97],[95]]], sum 46
[[[88],[97],[97]]], sum 48
Selected: [[[88],[97],[97]]]. Sum: 48


Teach it how to write a sentence: When talking about GA, Daniel Shiffman usually mentions the idea of probability of millions of monkeys randomly typing on a keyboard trying  to write a Shakespeare book - that's almost impossible to get the book done if using only random process - GA would solve it much faster. One example to show how GA works is make it write a sentence - many will say that it is an useless use for the library, but I  say it is good to learn. See the code:

import java.util.Random;
import org.jenetics.AnyChromosome;
import org.jenetics.AnyGene;
import org.jenetics.Genotype;
import org.jenetics.RouletteWheelSelector;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.util.Factory;
/**
*
* Will learn how to write the sentence you chose
*
* @author wsiqueir
*
*/
public class SentenceWriter {
final static String SENTENCE = "Be or not to be?";
private static String POSSIBLE_CHARS;
static Random r = new Random();
public static Character generateRandomString() {
POSSIBLE_CHARS = " abcdefghijklmnopqrstuvxzwyABCDEFGHIJKLMNOPQRSTUVXZWY!?.,'";
int i = r.nextInt(POSSIBLE_CHARS.length());
return POSSIBLE_CHARS.charAt(i);
}
private static Integer fitness(Genotype<AnyGene<Character>> ch) {
int sum = 0;
for (int i = 0; i < SENTENCE.length(); i++) {
char target = SENTENCE.charAt(i);
char allele = ch.getChromosome().getGene(i).getAllele();
if (allele == target) {
sum += 100;
}
sum += POSSIBLE_CHARS.length() - Math.abs(target - allele);
}
return sum;
}
public static void main(String[] args) {
Factory<Genotype<AnyGene<Character>>> gtf = Genotype
.of(AnyChromosome.of(SentenceWriter::generateRandomString, SENTENCE.length()));
final Engine<AnyGene<Character>, Integer> engine = Engine.builder(SentenceWriter::fitness, gtf)
.offspringSelector(new RouletteWheelSelector<>()).build();
Genotype<AnyGene<Character>> result = engine.stream().limit(50000).collect(EvolutionResult.toBestGenotype());
System.out.println("Selected: " + result);
}
}
The output will usually be the sentence formed or something close to the sentence. I have to say that at my first implementation I used the entire ascii table to it would guess any text - but that was a bad idea :).


Escape the maze: Ok, so far I have created small examples using mostly Jenetics classes, so I tried something a little more complex - but not that hard (let's not destroy the fun): escape the maze. In the code I have a model Maze, the model and utility methods for a given maze and the MazeSolver, the class that makes use of Jenetics to solve a given maze.



My fitness function is far away from being perfect, but it works! I didn't find no maze that couldn't be solved so far. One thing to improve is how to use less steps because I spent a few hours trying to find a balance between reach the target and use less steps: to give a high score to solutions that used less steps was usually leading to solutions that are not reaching the target!

The full code is on my github - I won't paste the full maze code here - the few readers I have are complaining about large code in a post! (they are right, I hate it too)

And for next post I will talk about the JavaFX view for the maze (I still need to make a few improvements):


Comentários

Postagens mais visitadas deste blog

Dancing lights with Arduino - The idea

I have been having fun with Arduino these days! In this article I am going to show how did I use an electret mic with Arduino to create a Dancing Lights circuit. Dancing Lights   I used to be an eletronician before starting the IT college. I had my own electronics maintenance office to fix television, radios, etc. In my free time I used to create electronic projects to sell and I made a few "reais" selling a version of Dancing lights, but it was too limited: it simply animated lamps using a relay in the output of a 4017 CMOS IC. The circuit was a decimal counter  controlled by a 555. 4017 decimal counter. Source in the image When I met Arduino a few years ago, I was skeptical because I said: I can do this with IC, why should I use a microcontroller. I thought that Arduino was for kids. But now my pride is gone and I am having a lot of fun with Arduino :-) The implementation of Dancing Lights with Arduino uses an electret mic to capture the sound and light leds...

Simplest JavaFX ComboBox autocomplete

Based on this Brazilian community post , I've created a sample Combobox auto complete. What it basically does is: When user type with the combobox selected, it will work on a temporary string to store the typed text; Each key typed leads to the combobox to be showed and updated If backspace is type, we update the filter Each key typed shows the combo box items, when the combobox is hidden, the filter is cleaned and the tooltip is hidden:   The class code and a sample application is below. I also added the source to my personal github , sent me PR to improve it and there are a lot of things to improve, like space and accents support.

Creating Fat JARs for JavaFX Applications

A FAT JAR is a type of Java application distribution where a single JAR contains all other dependencies, so no additional file is required to run the JAR besides the Java Virtual Machine. For any Java maven based application, creating a FAR JAR could be solved by using Maven Shade Plugin . However, creating FAT Jars using JavaFX may be a challenge because JavaFX uses modules. Fortunately this subject was intensely discussed in the WEB, and a good explanation and a solution was provided by Jose Pereda in this StackOverflow response. In this post I want to briefly share the steps to make a FAT JAR and post an example on my github so I can point others to check the example. How to create a FAT JAR for a JavaFX application? 1- Create a main class that will run your application. This class must have the main method and call your actual application static launch method; 2- Add the Shade Plugin to your project. For those using Gradle notice that Jose Pereda also provided an answer about it i...