Best linear model by genetic algorithm, my try

Best linear model by genetic algorithm, my try

Hey! This is my first blog post here. I suppose none of you know me, so... I'm Daniel from Chile, a long and thin country in South America. I'm 18 years old and have just started my first year in college.

I've been coding for a while, but it's always been more like a game for me. Now, as my projects need to be more serious, I've decided to create and share them (if someone reads them). More importantly, I want to maintain a dev log of what I'm achieving.

I created this project a couple of weeks ago, and, to be honest, I'm proud of it. It's like my baby. This JavaScript algorithm takes the data you draw and creates a set of random linear models to fit the input. After that, it evaluates all of them, selects the best ones, and mixes them to evolve. It runs entirely in the browser, and I used p5.js (I love this tool, and I learned it from Daniel Shiffman and his YouTube channel, The Coding Train).

This is a video of it working.

The complete project has around 600 lines of JavaScript code, and here are some of the code blocks that challenged (and expanded) my brain.

class Model {
    //...

    // The method to calculate the fitness of the model
    eval(){

        this.fitness = this.env.data.reduce( (acc,  p) => {
            let real = p.data.y
            let predicted = p.data.x * this.dna.genes[0] + this.dna.genes[1]
            let err = real-predicted
            // Applying some math I know :D
            return acc + pow(err,2)
        }, 0 )

        return this.fitness
    }

}
class DataDrawing {
    // ...

    // This is the method to draw a point in the canvas
    // I really don't know if this is the best but It works

    // Takes the mouse x and y position
    createPoint( x, y ){

            let { origin, plotSize } = this.env.mainPlot.visualizer.showPlotManager
            let newPoint = createVector( x, y ) // Mouse Position
                            .add( p5.Vector.fromAngle( random(2 * PI) ) // Creates a random point with distance less than the radius
                            .setMag( random(this.drawRadius/2) ) )
                            .sub( origin )
                            .mult( 1, -1 ) // HTML5 Canvas is flipped (:
                            .div( plotSize ); // Stores the data in normalized format

            let xLimit = newPoint.x > 0 && newPoint.x < 1
            let yLimit = newPoint.y > 0 && newPoint.y < 1

            if( xLimit && yLimit )
                return { data: newPoint, group: this.env.group.value() } 

        }

}

That's all with this project. I will share with you the repo when I push it, then you can broke it :D

See you!