<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[larswaechter.dev RSS Feed]]></title><description><![CDATA[larswaechter.dev RSS Feed]]></description><link>https://larswaechter.dev</link><generator>GatsbyJS</generator><lastBuildDate>Fri, 19 Dec 2025 20:30:41 GMT</lastBuildDate><item><title><![CDATA[Solving Peg Solitaire using Backtracking]]></title><description><![CDATA[A few days ago I saw a post on Reddit where someone asked what an algorithm for solving Peg Solitaire might look like. If you read the…]]></description><link>https://larswaechter.dev/solitaire-backtracking/</link><guid isPermaLink="false">https://larswaechter.dev/solitaire-backtracking/</guid><pubDate>Thu, 15 Dec 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A few days ago I saw a post on &lt;a href=&quot;https://www.reddit.com/r/compsci/comments/zgrx84/how_would_you_write_an_algorithm_to_solve_this/&quot;&gt;Reddit&lt;/a&gt; where someone asked what an algorithm for solving &lt;a href=&quot;https://en.wikipedia.org/wiki/Peg_solitaire&quot;&gt;Peg Solitaire&lt;/a&gt; might look like. If you read the comments, you&apos;ll notice that backtracking is the most common answer given. I really liked the idea and was curious to solve this puzzle. So in this post we&apos;ll solve Peg Solitaire with the help of backtracking.&lt;/p&gt;
&lt;p&gt;There&apos;s also an example repository on &lt;a href=&quot;https://github.com/larswaechter/peg-solitaire&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;But first things first. What is Peg Solitaire? Peg Solitaire is a single player board game where the player has to move pegs (pins) and remove them on a board in order to win. The rules are simple: each turn you can pick one peg, jump over a neighboring one (horizontal or vertical) and remove the one you just jumped over. The game is won when there&apos;s 1 peg left in the center of the board and it&apos;s lost when you cannot jump anymore or the last peg is not in the center. You&apos;re not allowed to jump over multiple pegs or multiple empty cells.&lt;/p&gt;
&lt;p&gt;An example Peg Solitaire board (&lt;a href=&quot;https://en.wikipedia.org/wiki/Peg_solitaire&quot;&gt;source&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/5/50/Spielzug_von_Solit%C3%A4r.gif&quot; alt=&quot;Peg Solitaire&quot;&gt;&lt;/p&gt;
&lt;h2&gt;Implementation&lt;/h2&gt;
&lt;p&gt;For the implementation we&apos;ll use Kotlin, but of course you can use any other language. Before we can implement the algorithm, we have to write some game logic first. Let&apos;s start with the board representation.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;kt&quot;&gt;&lt;pre class=&quot;language-kt&quot;&gt;&lt;code class=&quot;language-kt&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;val&lt;/span&gt; board&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Array&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;IntArray&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;arrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;intArrayOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The board is encoded as matrix (2D array) including the following values:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;-1&lt;/code&gt; =&gt; No cell (edge)&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt; =&gt; Cell without pin (hole)&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;1&lt;/code&gt; =&gt; Cell with pin&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The printed board looks like this:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt; ---------------
|     X X X     |
|     X X X     |
| X X X X X X X |          -1 =&gt; &quot; &quot;
| X X X o X X X |           0 =&gt; &quot;o&quot;
| X X X X X X X |           1 =&gt; &quot;X&quot;
|     X X X     |
|     X X X     |
 ---------------&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;How do we check if the player has won? As I just mentioned above, the game is won when the last pin is in the center of the board. The board center is at position &lt;code class=&quot;language-text&quot;&gt;board[3][3]&lt;/code&gt;. Quite simple:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;fun hasWon(): Boolean = this.remainingPegs == 1 &amp;amp;&amp;amp; board[3][3] == 1&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Next, we create a class that represents a single move. It has two attributes: &lt;code class=&quot;language-text&quot;&gt;from&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;to&lt;/code&gt;. Both of them include a &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; coordinate that represents the position on our board. For example &lt;code class=&quot;language-text&quot;&gt;Move(Pair(2,3), Pair(2,5))&lt;/code&gt; means that we want to move the pin at &lt;code class=&quot;language-text&quot;&gt;y=2|x=3&lt;/code&gt; to &lt;code class=&quot;language-text&quot;&gt;y=2|x=5&lt;/code&gt;. The first value indicates the row (&lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt;) and the second one the column (&lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;). In this case, the pin at &lt;code class=&quot;language-text&quot;&gt;y=2|x=4&lt;/code&gt; gets removed. The method &lt;code class=&quot;language-text&quot;&gt;getPegToRemove()&lt;/code&gt; returns the position of the pin to remove.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;class Move(val from: Pair&amp;lt;Int, Int&gt;, val to: Pair&amp;lt;Int, Int&gt;) {
    fun getPegToRemove(): Pair&amp;lt;Int, Int&gt; = Pair((from.first + to.first) / 2, (from.second + to.second) / 2)

    override fun toString(): String {
        return &quot;(${from.first}|${from.second}) =&gt; (${to.first}|${to.second})&quot;
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Now that we have the representation of the game board and moves, we can write a method that returns us all possible moves for a given board position. Here, we again iterate over each cell with a pin and check for each direction (horizontal / vertical) if the direct adjacent cell is not empty (&lt;code class=&quot;language-text&quot;&gt;1&lt;/code&gt;) and that this one&apos;s neighbor is empty (&lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt;). Of course, we must take into account the edges of the game board.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;fun getPossibleMoves(): List&amp;lt;Move&gt; {
    val moves = mutableListOf&amp;lt;Move&gt;()

    for ((rowIdx, row) in board.withIndex()) {
        for ((cellIdx, cell) in row.withIndex()) {
            if (cell != 1) continue

            val from = Pair(rowIdx, cellIdx)

            // Left =&gt; Right
            if (cellIdx &amp;lt;= 4 &amp;amp;&amp;amp; row[cellIdx + 1] == 1 &amp;amp;&amp;amp; row[cellIdx + 2] == 0)
                moves.add(Move(from, Pair(rowIdx, cellIdx + 2)))

            // Right =&gt; Left
            if (cellIdx &gt;= 2 &amp;amp;&amp;amp; row[cellIdx - 1] == 1 &amp;amp;&amp;amp; row[cellIdx - 2] == 0)
                moves.add(Move(from, Pair(rowIdx, cellIdx - 2)))

            // Up =&gt; Down
            if (rowIdx &amp;lt;= 4 &amp;amp;&amp;amp; board[rowIdx + 1][cellIdx] == 1 &amp;amp;&amp;amp; board[rowIdx + 2][cellIdx] == 0)
                moves.add(Move(from, Pair(rowIdx + 2, cellIdx)))

            // Down =&gt; Up
            if (rowIdx &gt;= 2 &amp;amp;&amp;amp; board[rowIdx - 1][cellIdx] == 1 &amp;amp;&amp;amp; board[rowIdx - 2][cellIdx] == 0)
                moves.add(Move(from, Pair(rowIdx - 2, cellIdx)))
        }
    }

    return moves
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The next step is to implement a method for playing a given move:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;fun move(move: Move): Solitaire {
    val newBoard = board.map { it.clone() }.toTypedArray()

    val toRemove = move.getPegToRemove()
    newBoard[move.from.first][move.from.second] = 0
    newBoard[toRemove.first][toRemove.second] = 0
    newBoard[move.to.first][move.to.second] = 1

    return Solitaire(newBoard, remainingPegs - 1)
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This method accepts a &lt;code class=&quot;language-text&quot;&gt;Move&lt;/code&gt; and returns a new game instance including the new board and the number of &lt;code class=&quot;language-text&quot;&gt;remainingPegs - 1&lt;/code&gt;. Look how the board is updated using the &lt;code class=&quot;language-text&quot;&gt;from&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;to&lt;/code&gt; attributes of &lt;code class=&quot;language-text&quot;&gt;move&lt;/code&gt;. The variable &lt;code class=&quot;language-text&quot;&gt;toRemove&lt;/code&gt; contains the position of the pin we just jumped over and want to remove.&lt;/p&gt;
&lt;p&gt;Last but not least the most important part: the &lt;a href=&quot;https://en.wikipedia.org/wiki/Backtracking&quot;&gt;backtracking&lt;/a&gt; algorithm. Here, we create a &lt;a href=&quot;https://www.ocf.berkeley.edu/~yosenl/extras/alphabeta/alphabeta.html&quot;&gt;game tree&lt;/a&gt; using depth-first-search. Each node in our tree represents a board position. From the root node (starting position) on, we iterate over all possible moves and search recursively for the one that results in a win. If that move is found, we cancel the search, go back up the child nodes to the root node and return the move of each child node that lead to this winning move.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;fun dfs(
    game: Solitaire = this,
): Pair&amp;lt;Move?, Boolean&gt; {
    if (game.hasWon()) return Pair(null, true)

    // Read from memory
    val hash = game.board.contentDeepHashCode()
    if (memory.containsKey(hash))
        return memory[hash]!!

    val moves = game.getPossibleMoves()
    if (moves.isEmpty()) return Pair(null, false)

    // Play each move and call recursively. Pick first solution that was found.
    for (move in moves) {
        val newGame = game.move(move)
        val hasWon = dfs(newGame).second

        // Return move that lead to win &amp;amp; store in memory
        if (hasWon) {
            memory[hash] = Pair(move, true)
            return memory[hash]!!
        }
    }

    // Case when no solution was found.
    return Pair(moves[0], false)
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The return value of this method is of type &lt;code class=&quot;language-text&quot;&gt;Pair&amp;lt;Move?, Boolean&gt;&lt;/code&gt; containing the next move to play and a boolean whether the game is solvable or not. Moreover, when we have found a winning move, we&apos;ll store it in a &lt;code class=&quot;language-text&quot;&gt;memory&lt;/code&gt; to speed up subsequent searches in the game tree.&lt;/p&gt;
&lt;p&gt;You should notice that the algorithm always returns the same solution. That&apos;s because we cancel the search as soon as the first solution was found. If you want to have more randomness, you have to continue the search at this point for more winning moves and pick a random one of them. You can also shuffle the list of possible moves. Watch out: both will make the algorithm much slower!&lt;/p&gt;
&lt;h2&gt;Performance&lt;/h2&gt;
&lt;p&gt;When simulating a complete game, you&apos;ll see that the algorithm solves the puzzle surprisingly fast. On my laptop (Huawei Matebook 14) a complete simulation runs in ~80ms. Without the &lt;code class=&quot;language-text&quot;&gt;memory&lt;/code&gt; it would take ~500ms, what is still very good.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;var game = Solitaire()

val timeMS = measureTimeMillis {
    var counter = 0
    while (!game.hasWon()) {
        counter++
        val move: Pair&amp;lt;Move?, Boolean&gt; = game.dfs()
        game = game.move(move.first!!)
    }
}

println(&quot;Done in $timeMS ms&quot;)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Nevertheless, you can still improve the performance by using symmetries for example. This &lt;a href=&quot;https://larswaechter.dev/blog/minimax-performance-improvements/&quot;&gt;article&lt;/a&gt; might be a help for you.&lt;/p&gt;
&lt;p&gt;Check out the GitHub &lt;a href=&quot;https://github.com/larswaechter/peg-solitaire&quot;&gt;repo&lt;/a&gt; for an example usage and more code details.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Writing & organizing Node.js API Tests the right way]]></title><description><![CDATA[Testing the code you write is an important step in the process of software engineering. It ensures that your software works as expected and…]]></description><link>https://larswaechter.dev/nodejs-api-testing/</link><guid isPermaLink="false">https://larswaechter.dev/nodejs-api-testing/</guid><pubDate>Tue, 22 Nov 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Testing the code you write is an important step in the process of software engineering. It ensures that your software works as expected and reduces the risk of shipping bugs and vulnerabilities to production. Automated tests in particular play an important role when it comes to testing frequently and consistently. Continous integration makes them even more powerful.&lt;/p&gt;
&lt;p&gt;In this blog post I&apos;ll show you an architecture for testing Node.js REST APIs that use a &lt;strong&gt;database&lt;/strong&gt; in the background. There are some things you should consider in this scenario that we&apos;ll talk about. You&apos;ll see how to separate and organize your application&apos;s components in a way that you can test them independently. Therefore, we&apos;ll use &lt;strong&gt;two different approaches&lt;/strong&gt;. On the one hand we setup a test environment in which we run ours tests against a &lt;strong&gt;test database&lt;/strong&gt;. On the other hand we &lt;strong&gt;mock the database layer&lt;/strong&gt; using &lt;a href=&quot;https://jestjs.io/docs/mock-functions&quot;&gt;mock functions&lt;/a&gt; so that we can run them in an environment in which we have no access to a database.&lt;/p&gt;
&lt;p&gt;We&apos;ll start by writing unit tests for testing single components of our application. In the next step we combine those components and test them using integration tests. Last but not least, we setup a CI/CD pipeline using GitHub actions and run the tests on each push that is made.&lt;/p&gt;
&lt;p&gt;Note that this is not a guide on how testing in general works. There are thousands of articles about frameworks like Jest, Mocha, Supertest and so on.
This is more a guide on how to prepare your Node application and test environment in a way that you can write tests effortlessly and efficiently &lt;strong&gt;with or without a database connection&lt;/strong&gt;. There&apos;s also an example repo on &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing&quot;&gt;GitHub&lt;/a&gt;. You should definitely check it out.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Disclamer: I know there really is no right or wrong when it comes to the architecture. The following is my prefered one.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Let&apos;s start with some of the tools we&apos;ll use. You should know most of them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Language&lt;/strong&gt;: &lt;a href=&quot;https://www.npmjs.com/package/typescript&quot;&gt;Typescript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Server&lt;/strong&gt;: &lt;a href=&quot;https://www.npmjs.com/package/express&quot;&gt;Express&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database&lt;/strong&gt;: &lt;a href=&quot;https://www.npmjs.com/package/pg&quot;&gt;Postgres&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Testing&lt;/strong&gt;: &lt;a href=&quot;https://www.npmjs.com/package/jest&quot;&gt;Jest&lt;/a&gt; &amp;#x26; &lt;a href=&quot;https://www.npmjs.com/package/supertest&quot;&gt;Supertest&lt;/a&gt; &amp;#x26; &lt;a href=&quot;https://www.npmjs.com/package/chai&quot;&gt;Chai&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CI/CD&lt;/strong&gt;: &lt;a href=&quot;https://github.com/features/actions&quot;&gt;GitHub Actions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Containerization&lt;/strong&gt;: &lt;a href=&quot;https://www.docker.com/&quot;&gt;Docker&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One benefit of this architecture is that you can use it with other databases than Postgres too, like &lt;a href=&quot;https://www.npmjs.com/package/mysql2&quot;&gt;MySQL&lt;/a&gt; for example. In this architecture we don&apos;t use any kind of ORM. Moreover, you can replace Jest with &lt;a href=&quot;https://www.npmjs.com/package/mocha&quot;&gt;Mocha&lt;/a&gt; if that is your desired testing framework.&lt;/p&gt;
&lt;h2&gt;Application Architecture&lt;/h2&gt;
&lt;p&gt;The architecture of our application looks roughly like this:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;node-api
├── api
│   ├── components
│   │   ├── user
|   |   │   ├── tests               // Tests for each component
|   |   |   │   ├── http.spec.ts
|   |   |   │   ├── mock.spec.ts
|   |   │   |   └── repo.spec.ts
|   |   │   ├── controller.ts
|   |   │   ├── dto.ts
|   |   │   ├── repository.ts
|   |   │   └── routes.ts
│   └── server.ts
├── factories                       // Factories to setup tests
|   ├── helper.ts
|   ├── abs.factory.ts
|   ├── http.factory.ts
|   └── repo.factory.ts
└── app.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: The example repo contains some more code.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Each component consists of the following four files:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;controller.ts&lt;/strong&gt;: HTTP Handler&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;dto.ts&lt;/strong&gt;: Data Transfer Object (&lt;a href=&quot;https://docs.nestjs.com/controllers#request-payloads&quot;&gt;more&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;repository.ts&lt;/strong&gt;: Database Layer&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;routes.ts&lt;/strong&gt;: HTTP Routing&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;tests&lt;/code&gt; directory includes the tests of the according component. If you want to read more about this architecture, checkout &lt;a href=&quot;https://larswaechter.dev/blog/nodejs-rest-api-structure/&quot;&gt;this&lt;/a&gt; article of mine.&lt;/p&gt;
&lt;h2&gt;Config&lt;/h2&gt;
&lt;p&gt;We&apos;ll start by creating an &lt;code class=&quot;language-text&quot;&gt;.env.test&lt;/code&gt; file that contains the secret environment variables for testing. The npm Postgres package uses them automatically when establishing a new database connection. All we have to do is to make sure that they are loaded using &lt;a href=&quot;https://www.npmjs.com/package/dotenv&quot;&gt;dotenv&lt;/a&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;NODE_PORT=0
NODE_ENV=test

PGHOST=localhost
PGUSER=root
PGPASSWORD=mypassword
PGDATABASE=nodejs_test
PGPORT=5432&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Setting &lt;code class=&quot;language-text&quot;&gt;NODE_PORT=0&lt;/code&gt; lets Node choose the first randomly available port that it finds. This can be useful if you run multiple instances of a HTTP server during testing. You can also set a fixed value other than &lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt; here. Using &lt;code class=&quot;language-text&quot;&gt;PGDATABASE&lt;/code&gt; we provide the name of our test database.&lt;/p&gt;
&lt;p&gt;Next, we setup Jest. The config in &lt;code class=&quot;language-text&quot;&gt;jest.config.js&lt;/code&gt; looks as follows:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;module&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;exports &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;preset&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;ts-jest&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;testEnvironment&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;node&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;roots&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;src&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;setupFiles&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;&amp;lt;rootDir&gt;/setup-jest.js&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;And &lt;code class=&quot;language-text&quot;&gt;setup-jest.js&lt;/code&gt; like this:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token function&quot;&gt;require&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;dotenv&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;config&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;path&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;.env.test&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This snippet ensures that the appropriate environment variables are loaded from the provided &lt;code class=&quot;language-text&quot;&gt;.env&lt;/code&gt; file before running the tests.&lt;/p&gt;
&lt;h2&gt;Testing with database&lt;/h2&gt;
&lt;p&gt;Let&apos;s start with the assumption that we have a test database that we can use. This might be one in a GitHub Actions CI/CD pipeline for example. Later on I&apos;ll show you how to test your application without a database connection.&lt;/p&gt;
&lt;h3&gt;3 rules&lt;/h3&gt;
&lt;p&gt;At the beginning I said that there are some important things we want to consider that make life much easier when testing Node APIs:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Separate the database layer&lt;/li&gt;
&lt;li&gt;Outsource the database connection initialization&lt;/li&gt;
&lt;li&gt;Outsource the HTTP server initialization&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;What do I mean by that?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Separate the database layer&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You should have your own layer, separated from your business logic, that takes care of the communication with the database. In the example Git repo you can find this layer in a component&apos;s &lt;code class=&quot;language-text&quot;&gt;repository.ts&lt;/code&gt; file. This allows us to easily mock a layer&apos;s methods when we have no database available for testing.&lt;/p&gt;
&lt;p&gt;Moreover, it&apos;s easier to replace your database system with another one.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserRepository&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;readAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;IUser&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token builtin&quot;&gt;Promise&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;resolve&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; reject&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      client&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-function&quot;&gt;&lt;span class=&quot;token function&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;IUser&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;SELECT * FROM users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; res&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
          Logger&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;message&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
          &lt;span class=&quot;token function&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Failed to fetch users!&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;res&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;rows&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Outsource the database connection initialization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You should already know that when writing tests against a database, you do not run them against the production one. Instead, you setup a test database. Otherwise, you run the risk messing up your production data.&lt;/p&gt;
&lt;p&gt;Most of the time, your application connects to the database in a startup script, like &lt;code class=&quot;language-text&quot;&gt;index.js&lt;/code&gt;. After the connection is established, you start the HTTP server. That&apos;s what we want to do in our test setup too. This way we can connect to the database and disconnect from it gracefully before and after each test case.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Outsource the HTTP server initialization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;It&apos;s a good practice, whether you use a database or not, to start the HTTP server from inside your tests. Just as we do for the database connection, we create a new HTTP server before and stop it after each test case.&lt;/p&gt;
&lt;p&gt;This might look as follows: (you&apos;ll see the concrete implementation later on)&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token function&quot;&gt;describe&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Component Test&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;beforeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// Connect to db pool &amp;amp;&amp;amp; start Express Server&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;afterEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// Release db pool client &amp;amp;&amp;amp; stop Express Server&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;afterAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// End db pool&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In particular the execution order is:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Connect to the database pool&lt;/li&gt;
&lt;li&gt;Run the SQL seed (create tables)&lt;/li&gt;
&lt;li&gt;Start the Express server&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Run the tests&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Shutdown the Express server &amp;#x26; release db pool client&lt;/li&gt;
&lt;li&gt;Repeat step 1 - 5 for each test case and close the pool at the end&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Tests&lt;/h3&gt;
&lt;p&gt;Each component consists of two test files:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;repo.spec.ts&lt;/li&gt;
&lt;li&gt;http.spec.ts&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Both of them make use of so called &lt;code class=&quot;language-text&quot;&gt;TestFactories&lt;/code&gt; which prepare the test setup. You&apos;ll see their implementation in the next chapter.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: If you have a look at the example Git repo, you&apos;ll see that there are two more: mock.spec.ts and dto.spec.ts. Former one is discussed later on. The latter is not covered in this article.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;repo.spec.ts&lt;/h4&gt;
&lt;p&gt;A repository is an additional abstract layer that is responsible for interacting with the database like reading and inserting new data. That layer is what we test in here. Since a database is required in this case, a new pool client is created to connect to the database using the &lt;code class=&quot;language-text&quot;&gt;RepoTestFactory&lt;/code&gt; before each test case. And it is released, right after the test case is completed. At the end, when all test cases are finished, the pool connection is closed.&lt;/p&gt;
&lt;p&gt;Example on &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/blob/main/src/api/components/user/tests/repo.spec.ts&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token function&quot;&gt;describe&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;User component (REPO)&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; factory&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; RepoTestFactory &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;RepoTestFactory&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUser&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; IUser &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUserDTO&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; UserDTO &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userDTOFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Connect to pool&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;beforeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Release pool client&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;afterEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// End pool&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;afterAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;create new user&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; repo &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserRepository&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; user &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; repo&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;create&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUserDTO&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;to&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;be&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;an&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;object&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; count &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;getTableRowCount&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;count&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;http.spec.ts&lt;/h4&gt;
&lt;p&gt;Here, we test the integration of the user component&apos;s routes, controller and repository. Before each test case, a new pool client is created just as we did above. In addition, a new Express server is started using the &lt;code class=&quot;language-text&quot;&gt;HttpTestFactory&lt;/code&gt;. At the end, both are closed again.&lt;/p&gt;
&lt;p&gt;Example on &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/blob/main/src/api/components/user/tests/http.spec.ts&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token function&quot;&gt;ddescribe&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;User component (HTTP)&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; factory&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; HttpTestFactory &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;HttpTestFactory&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUser&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; IUser &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUserDTO&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; UserDTO &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userDTOFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Connect to pool &amp;amp;&amp;amp; start Express Server&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;beforeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Release pool client &amp;amp;&amp;amp; stop Express Server&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;afterEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// End pool&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;afterAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;POST /users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; res &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;app
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;post&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;send&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUserDTO&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;201&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Content-Type&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token regex&quot;&gt;&lt;span class=&quot;token regex-delimiter&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;token regex-source language-regex&quot;&gt;json&lt;/span&gt;&lt;span class=&quot;token regex-delimiter&quot;&gt;/&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; user&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; IUser &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; res&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;body
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;to&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;be&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;an&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;object&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; count &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;getTableRowCount&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;count&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;Factories&lt;/h2&gt;
&lt;p&gt;The test factories are actually the heart of our tests. They are responsible for setting up and preparing the environment for each test case. That includes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Droping &amp;#x26; creating all db tables&lt;/li&gt;
&lt;li&gt;Initializing the db connection&lt;/li&gt;
&lt;li&gt;Initializing the HTTP server&lt;/li&gt;
&lt;li&gt;Closing both of them again&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There are four &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/tree/main/src/factories&quot;&gt;factories&lt;/a&gt; in total: &lt;code class=&quot;language-text&quot;&gt;AbsTestFactory&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;RepoTestFactory&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;HttpTestFactory&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;MockTestFactory&lt;/code&gt;. Each of them has its own Typescript class.&lt;/p&gt;
&lt;p&gt;The last one is discussed in the chapter &quot;Testing without database&quot;.&lt;/p&gt;
&lt;h3&gt;AbsTestFactory&lt;/h3&gt;
&lt;p&gt;The first one &lt;code class=&quot;language-text&quot;&gt;AbsTestFactory&lt;/code&gt; is an abstract base class that is implemented by the other three. It includes among others a method for connecting to the database pool and one for disconnecting from it.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;abstract&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AbsTestFactory&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;implements&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;ITestFactory&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; poolClient&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; PoolClient

  &lt;span class=&quot;token keyword&quot;&gt;abstract&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;abstract&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;getTableRowCount&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;name&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; rows &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;poolClient&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
      &lt;span class=&quot;token template-string&quot;&gt;&lt;span class=&quot;token template-punctuation string&quot;&gt;`&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;SELECT COUNT(*) FROM &lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token interpolation-punctuation punctuation&quot;&gt;${&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;poolClient&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;escapeIdentifier&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;name&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token interpolation-punctuation punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;token template-punctuation string&quot;&gt;`&lt;/span&gt;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; rows&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;length &lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt;rows&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;count &lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;connectPool&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    pool
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;connect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;poolClient &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;poolClient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; poolClient
        &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;poolClient&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;seed&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;catch&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;releasePoolClient&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;poolClient&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;release&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;endPool&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    pool&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; seed &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;readFileSync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;join&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;__dirname&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;../../db/scripts/create-tables.sql&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      encoding&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;utf-8&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Using the &lt;code class=&quot;language-text&quot;&gt;create-tables.sql&lt;/code&gt; script, the factory &lt;strong&gt;drops and recreates&lt;/strong&gt; all the tables after the connection is established:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;sql&quot;&gt;&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;DROP&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;IF&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;EXISTS&lt;/span&gt; users&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;CREATE&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;TABLE&lt;/span&gt; users &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    id &lt;span class=&quot;token keyword&quot;&gt;SERIAL&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;PRIMARY&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;KEY&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    email &lt;span class=&quot;token keyword&quot;&gt;VARCHAR&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;UNIQUE&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;NULL&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    username &lt;span class=&quot;token keyword&quot;&gt;VARCHAR&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;UNIQUE&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;NULL&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    created_at &lt;span class=&quot;token keyword&quot;&gt;TIMESTAMP&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;DEFAULT&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;CURRENT_TIMESTAMP&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;RepoTestFactory&lt;/h3&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;RepoTestFactory&lt;/code&gt; is used by each component&apos;s repository test (&lt;code class=&quot;language-text&quot;&gt;repo.spec.ts&lt;/code&gt;) that you just saw above. All it does is use the parent class &lt;code class=&quot;language-text&quot;&gt;AbsTestFactory&lt;/code&gt; to connect to the database.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;RepoTestFactory&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AbsTestFactory&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;connectPool&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;releasePoolClient&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;closeAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;endPool&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The methods &lt;code class=&quot;language-text&quot;&gt;prepareEach&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;closeEach&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;closeAll&lt;/code&gt; are called for each test case in the Jest &lt;code class=&quot;language-text&quot;&gt;beforeEach&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;afterEach&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;afterAll&lt;/code&gt; lifecycle.&lt;/p&gt;
&lt;h3&gt;HttpTestFactory&lt;/h3&gt;
&lt;p&gt;The last one &lt;code class=&quot;language-text&quot;&gt;HttpTestFactory&lt;/code&gt; is used by each component&apos;s HTTP test (&lt;code class=&quot;language-text&quot;&gt;http.spec.ts&lt;/code&gt;). Just like &lt;code class=&quot;language-text&quot;&gt;RepoTestFactory&lt;/code&gt;, it uses the parent class for the database connection. Furthermore, it initializes the Express server.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;HttpTestFactory&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AbsTestFactory&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; server&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Server &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Server&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; http&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; HttpServer &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;createServer&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;server&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;app&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;app&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;supertest&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;server&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;app&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;connectPool&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;http&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;listen&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;process&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;env&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;NODE_PORT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;http&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;close&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;releasePoolClient&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;closeAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;endPool&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;Helpers&lt;/h2&gt;
&lt;p&gt;In &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/blob/main/src/factories/helper.ts&quot;&gt;helper.ts&lt;/a&gt;, there are two &lt;a href=&quot;https://www.npmjs.com/package/fishery&quot;&gt;fishery&lt;/a&gt; objects which we can use to create dummy data during the tests.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; userFactory &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-function&quot;&gt;&lt;span class=&quot;token function&quot;&gt;define&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;IUser&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; sequence&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; onCreate &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;onCreate&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    user &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;&lt;span class=&quot;token builtin&quot;&gt;Promise&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;resolve&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; reject&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        pool&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-function&quot;&gt;&lt;span class=&quot;token function&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;IUser&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
          &lt;span class=&quot;token string&quot;&gt;&quot;INSERT INTO users (email, username) VALUES($1, $2) RETURNING *&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
          &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
          &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; res&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;token function&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;res&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;rows&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
          &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    id&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; sequence&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    email&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;john@doe.com&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    username&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;johndoe&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    created_at&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Date&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; userDTOFactory &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token generic-function&quot;&gt;&lt;span class=&quot;token function&quot;&gt;define&lt;/span&gt;&lt;span class=&quot;token generic class-name&quot;&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;UserDTO&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserDTO&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;john@doe.com&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;johndoe&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Usage:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;// Returns new `IUser` instance&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUser1 &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Returns new `IUser` instance &amp;amp; creates db entry&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUser2 &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; userFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;create&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;Rewind&lt;/h2&gt;
&lt;p&gt;Let&apos;s jump back to the &lt;code class=&quot;language-text&quot;&gt;repo.spec.ts&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;http.spec.ts&lt;/code&gt; test files from above. In both of them we used the factories&apos; &lt;code class=&quot;language-text&quot;&gt;prepareEach&lt;/code&gt; method before each and its &lt;code class=&quot;language-text&quot;&gt;afterEach&lt;/code&gt; method after right each test case. The &lt;code class=&quot;language-text&quot;&gt;closeAll&lt;/code&gt; method is called at the very end of the test file. As you have just seen, depending on the type of factory, we establish the database connection and start the HTTP server if needed.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token function&quot;&gt;describe&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Component Test&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;beforeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;afterEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;afterAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeAll&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;One important thing you should keep in mind is that for each test case that uses the database, the factory drops all the tables and recreates them using the provided SQL script afterwards. This way we have a clean database with empty tables in each test case.&lt;/p&gt;
&lt;h2&gt;Testing without database&lt;/h2&gt;
&lt;p&gt;So far we have run our tests against a test database, but what if we have no access to a database? In this case, we need to &lt;a href=&quot;https://jestjs.io/docs/es6-class-mocks&quot;&gt;mock&lt;/a&gt; our database layer implementation (&lt;code class=&quot;language-text&quot;&gt;repository.ts&lt;/code&gt;), which is quite easy if you have separated it from the business logic, as I recommended in rule #1.&lt;/p&gt;
&lt;p&gt;With mocks, the layer does not depend on an external data source any more. Instead, we provide a custom implementation for the class and each of its methods. Be aware that this does not affect the behavior of our &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/blob/main/src/api/components/user/controller.ts&quot;&gt;controller&lt;/a&gt; since it does not care about where the data comes from.&lt;/p&gt;
&lt;p&gt;Example on &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/blob/main/src/api/components/user/tests/mock.spec.ts&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUser &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; dummyUserDTO &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; userDTOFactory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;build&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; mockReadAll &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; jest&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValue&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; mockReadByID &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; jest
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValueOnce&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValueOnce&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValue&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;undefined&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; mockCreate &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; jest&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValue&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; mockReadByEmailOrUsername &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; jest
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValueOnce&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;undefined&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValueOnce&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; mockDelete &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; jest&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockResolvedValue&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

jest&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mock&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;../repository&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  UserRepository&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; jest&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;mockImplementation&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    readAll&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; mockReadAll&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    readByID&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; mockReadByID&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    readByEmailOrUsername&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; mockReadByEmailOrUsername&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    create&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; mockCreate&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;delete&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; mockDelete&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;After mocking the database layer, we can write ours tests as usual. Using &lt;code class=&quot;language-text&quot;&gt;toHaveBeenCalledTimes()&lt;/code&gt; we make sure that our custom method implementation has been called.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token function&quot;&gt;describe&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;User component (MOCK)&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; factory&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; MockTestFactory &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;MockTestFactory&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Start Express Server&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;beforeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Stop Express Server&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;afterEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;done&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;POST /users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; res &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; factory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;app
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;post&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/users&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;send&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUserDTO&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;201&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Content-Type&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token regex&quot;&gt;&lt;span class=&quot;token regex-delimiter&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;token regex-source language-regex&quot;&gt;json&lt;/span&gt;&lt;span class=&quot;token regex-delimiter&quot;&gt;/&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; user&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; IUser &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; res&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;body
    &lt;span class=&quot;token function&quot;&gt;cExpect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;to&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;be&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;an&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;object&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;cExpect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;cExpect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;cExpect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;dummyUser&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;username&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mockCreate&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;toHaveBeenCalledTimes&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mockReadByEmailOrUsername&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;toHaveBeenCalledTimes&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: cExpect is a named import from the &quot;chai&quot; package.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;MockTestFactory&lt;/h3&gt;
&lt;p&gt;Just as we did in the other tests files, we use a test factory here as well. All the &lt;code class=&quot;language-text&quot;&gt;MockTestFactory&lt;/code&gt; does is run a new Express HTTP instance. It &lt;strong&gt;does not&lt;/strong&gt; establish a database connection since we mock the database layer.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;MockTestFactory&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AbsTestFactory&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; server&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Server &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Server&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; http&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; HttpServer &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;createServer&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;server&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;app&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;get&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;app&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;supertest&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;server&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;app&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;prepareEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;http&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;listen&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;process&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;env&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;NODE_PORT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;closeEach&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Error&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;http&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;close&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;cb&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;One drawback we have using this approach is that the layer (&lt;code class=&quot;language-text&quot;&gt;repository.ts&lt;/code&gt;) is not tested at all because we overwrite it. Nevertheless, we can still test the rest of our application, like the business logic for example. Great!&lt;/p&gt;
&lt;h2&gt;Running&lt;/h2&gt;
&lt;p&gt;Using the the commands below we can run the tests with or without a database. Depending on the scenario, the files we do not want to test are excluded from execution.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;json&quot;&gt;&lt;pre class=&quot;language-json&quot;&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;test:db&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;jest --testPathIgnorePatterns mock.spec.ts&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;test:mock&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;jest --testPathIgnorePatterns \&quot;(repo|http).spec.ts\&quot;&quot;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;GitHub Actions&lt;/h2&gt;
&lt;p&gt;The final step is to create a CI/CD pipeline using GitHub actions that runs our tests. The according yaml file is available &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/blob/main/.github/workflows/actions.yml&quot;&gt;here&lt;/a&gt;. There&apos;s also a very good &lt;a href=&quot;https://docs.github.com/en/actions/using-containerized-services/creating-postgresql-service-containers&quot;&gt;tutorial&lt;/a&gt; published on GitHub. You can decide whether to run the tests against a test database or use the mocked data layer. I decided to go with the former.&lt;/p&gt;
&lt;p&gt;When running the pipeline with a test database, we need to make sure that we set the correct environment variables for it. &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing/actions/runs/3514430623/jobs/5888433172&quot;&gt;Here&lt;/a&gt; you can find a test run.&lt;/p&gt;
&lt;h2&gt;Last words&lt;/h2&gt;
&lt;p&gt;My last tip is to have a look at the example repository on &lt;a href=&quot;https://github.com/larswaechter/nodejs-api-testing&quot;&gt;GitHub&lt;/a&gt; and to read it carefully There are some more tests and code snippets that I did not cover in this article. Moreover, checkout the links below. Happy coding!&lt;/p&gt;
&lt;h2&gt;Further resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://jestjs.io/docs/es6-class-mocks&quot;&gt;ES6 Class Mocks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://larswaechter.dev/blog/nodejs-database-seeding/&quot;&gt;Database seeding in Node.js&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://larswaechter.dev/blog/nodejs-rest-api-structure/&quot;&gt;How I structure my Node.js REST APIs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/actions/using-containerized-services/creating-postgresql-service-containers&quot;&gt;Creating PostgreSQL service containers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item><item><title><![CDATA[Recognizing hand drawn Doodles using Deep Learning]]></title><description><![CDATA[In November 2016 Google released an online game called "Quick, Draw!" that asks the player to draw an image of a prescribed object and then…]]></description><link>https://larswaechter.dev/recognizing-hand-drawn-doodles/</link><guid isPermaLink="false">https://larswaechter.dev/recognizing-hand-drawn-doodles/</guid><pubDate>Sat, 02 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In November 2016 Google released an online game called &quot;&lt;a href=&quot;https://quickdraw.withgoogle.com/&quot;&gt;Quick, Draw!&lt;/a&gt;&quot; that asks the player to draw an image of a prescribed object and then uses a neural network to guess what the drawing represents.
All in all there are 345 different objects the neural network can recognize.&lt;/p&gt;
&lt;p&gt;Luckily, Google released the &lt;a href=&quot;https://github.com/googlecreativelab/quickdraw-dataset&quot;&gt;dataset&lt;/a&gt; they trained their neural network with, which includes more than 50 million by the players hand drawn images. So you can use this dataset to train your own neural network. And that&apos;s exactly what this article is about: we&apos;ll build a convolutional neural network to recognize hand drawn images using the Quick, Draw! dataset. Furthermore, we&apos;ll build a simple web app that allows the user to draw images and predict them using the network model later on.&lt;/p&gt;
&lt;p&gt;The complete code and the trained model are available at &lt;a href=&quot;https://github.com/larswaechter/quickdraw-cnn&quot;&gt;GitHub&lt;/a&gt;. You can find the webapp demo on &lt;a href=&quot;https://quickdraw-cnn.fly.dev/&quot;&gt;Fly.io&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Neural Network&lt;/h2&gt;
&lt;p&gt;What we&apos;ll do:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Generate, load &amp;#x26; visualize the training data&lt;/li&gt;
&lt;li&gt;Design the network&lt;/li&gt;
&lt;li&gt;Train &amp;#x26; export the model&lt;/li&gt;
&lt;li&gt;Convert the model to TFLite&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Setup&lt;/h3&gt;
&lt;p&gt;For developing the convolutional neural network we&apos;ll use the following dependencies as listed in &lt;a href=&quot;https://github.com/larswaechter/quickdraw-cnn/blob/main/cnn/requirements.txt&quot;&gt;requirements.txt&lt;/a&gt;:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;tensorflow==2.6.2
numpy~=1.19.5
quickdraw==0.2.0
matplotlib==3.3.4
jupyter==1.0.0
pillow==8.4.0&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Tip: create a new &lt;a href=&quot;https://docs.python.org/3/library/venv.html#module-venv&quot;&gt;virtual environment&lt;/a&gt; for that.&lt;/p&gt;
&lt;p&gt;Install the dependencies using the following command.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;bash&quot;&gt;&lt;pre class=&quot;language-bash&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;pip3 &lt;span class=&quot;token function&quot;&gt;install&lt;/span&gt; &lt;span class=&quot;token parameter variable&quot;&gt;-r&lt;/span&gt; requirements.txt&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Let&apos;s have a look at the dataset before writing the actual code.&lt;/p&gt;
&lt;h3&gt;Dataset&lt;/h3&gt;
&lt;p&gt;You can find the complete dataset at &lt;a href=&quot;https://console.cloud.google.com/storage/browser/quickdraw_dataset/full/simplified?pli=1&quot;&gt;Google Cloud Platform&lt;/a&gt;, which contains more than 50 million images of 345 different categories. A list of all included categories is avaiable &lt;a href=&quot;https://github.com/larswaechter/quickdraw-cnn/blob/main/webapp/static/scripts/labels.js&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A single image is represented as follows in the Quick, Draw! dataset:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;json&quot;&gt;&lt;pre class=&quot;language-json&quot;&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;key_id&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;5891796615823360&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;word&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;nose&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;countrycode&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;AE&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;timestamp&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;2017-03-01 20:41:36.70725 UTC&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;recognized&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;drawing&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;129&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;129&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;129&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;130&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;130&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;131&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;132&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;132&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;133&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;133&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;133&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;133&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;...&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The following properties are important for us:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;word (the image&apos;s category)&lt;/li&gt;
&lt;li&gt;recognized (whether the drawing was recognized by Google&apos;s AI)&lt;/li&gt;
&lt;li&gt;drawing (an array representing the vector drawing)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The actual image in &quot;drawing&quot; is a multi-dimensional array including the pixel coordinates of each single stroke:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;[
  [  // First stroke
    [x0, x1, x2, x3, ...],
    [y0, y1, y2, y3, ...],
    [t0, t1, t2, t3, ...]
  ],
  [  // Second stroke
    [x0, x1, x2, x3, ...],
    [y0, y1, y2, y3, ...],
    [t0, t1, t2, t3, ...]
  ],
  ... // Additional strokes
]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Generation&lt;/h4&gt;
&lt;p&gt;In order to train the neural network we create our own slightly modified dataset from Google&apos;s one. For downloading and accessing the one from Google Cloud Platform we use a Python package called &lt;a href=&quot;https://quickdraw.readthedocs.io/en/latest/&quot;&gt;quickdraw&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The following steps are required to create our own dataset:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Load &lt;strong&gt;1200&lt;/strong&gt; training images for each class from the cloud storage&lt;/li&gt;
&lt;li&gt;Resize them to &lt;strong&gt;28x28&lt;/strong&gt; pixels&lt;/li&gt;
&lt;li&gt;Save them as PNG&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;image_size &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;generate_class_images&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;name&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; max_drawings&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; recognized&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    directory &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Path&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;dataset/&quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; name&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;not&lt;/span&gt; directory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;exists&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        directory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mkdir&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;parents&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    images &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; QuickDrawDataGroup&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;name&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; max_drawings&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;max_drawings&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; recognized&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;recognized&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; img &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; images&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;drawings&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        filename &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; directory&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;as_posix&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;/&quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;img&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;key_id&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;.png&quot;&lt;/span&gt;
        img&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;get_image&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stroke_width&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;resize&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;image_size&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;save&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;filename&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; label &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; QuickDrawData&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;drawing_names&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    generate_class_images&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;label&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; max_drawings&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1200&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; recognized&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Setting &lt;code class=&quot;language-text&quot;&gt;recognized=True&lt;/code&gt; ensures that only images that have been recognized by Google&apos;s AI are loaded.&lt;/p&gt;
&lt;p&gt;After the generation is finished there should be a directory structure that looks like the following.
Each class has its own subdirectory including 1200 images:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;.
└── dataset
|   ├── aircraft carrier
|   │   ├── 4504134474530816.png
|   │   ├── 4506833509154816.png
|   │   ├── ...
|   ├── airplane
|   │   ├── 4508382553702400.png
|   │   ├── 4508818253807616.png
|   │   ├── ...
|   ├── ...&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In total there should be 414.000 images (345 * 1200).&lt;/p&gt;
&lt;h4&gt;Loading&lt;/h4&gt;
&lt;p&gt;Now we can load the images using Keras &lt;code class=&quot;language-text&quot;&gt;image_dataset_from_directory&lt;/code&gt; function and split them into a training and validation set. The &lt;strong&gt;batch size&lt;/strong&gt; is set to 32.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;batch_size &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;32&lt;/span&gt;

train_ds &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; image_dataset_from_directory&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    dataset_dir&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    validation_split&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    subset&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;training&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    seed&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    color_mode&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;grayscale&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    image_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;image_size&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    batch_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;batch_size
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

val_ds &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; image_dataset_from_directory&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    dataset_dir&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    validation_split&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    subset&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;validation&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    seed&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    color_mode&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;grayscale&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    image_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;image_size&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    batch_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;batch_size
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Using a &lt;strong&gt;80/20 split&lt;/strong&gt; we end up having &lt;strong&gt;331.200 training&lt;/strong&gt; and &lt;strong&gt;82.800 validation&lt;/strong&gt; images.&lt;/p&gt;
&lt;h4&gt;Visualization&lt;/h4&gt;
&lt;p&gt;Next, let&apos;s visualize some random training images using &lt;a href=&quot;https://pypi.org/project/matplotlib/&quot;&gt;matplotlib&lt;/a&gt;:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;plt&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;figure&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;figsize&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; images&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; labels &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; train_ds&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;take&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        ax &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; plt&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;subplot&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; i &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        data &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; images&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;i&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;numpy&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;astype&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;uint8&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        plt&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;imshow&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;data&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; cmap&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&apos;gray&apos;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; vmin&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; vmax&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        plt&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;title&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;train_ds&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;class_names&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;labels&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;i&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        plt&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;axis&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;off&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;What outputs:&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 503px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/1efdcd45451e14c845bef53656ed033f/a4078/dataset.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 101.8987341772152%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAACXBIWXMAAAsTAAALEwEAmpwYAAACAklEQVR42qWUx67CQAxF5/9/iQUbNgjYIRBFhCZ6Db0aHUsemYTN07M0gnjs62tfJ+H9fgu2Wq1kPp9L1vD3ej0ZjUZyPB6j//F4yGKx0JzJZCKHw0H94X6/y3g8lkqlIvv9Xp1W5Pl8SqPRkFKpJLVaTdbrtVyvV71bLpdaKGuBi2KxKN1u9wsM2+12MhgMpFwuy3A4VJDz+ayFKJ6maWRmeeH1eukDwVbdG8m0ZokYXQFMLqy/GNqfy+Ui0+k0B8isZrOZsvWA9syMc4BGd7PZxEDzwRo/Lfpx4PMMueMEX5UkmHpAlEU0WBLjO6IYXTGOOMPb7SYcRGE1TqeTzs2MwbdaLWk2m3FtLBmGMKUYuYDr2lCJWRBINQaOEUgBDD+AFPOt4ycf4diEkBUBAANhnqgPy+12q4XYPeuAO/aUUXEgF7KKsvl+JgQCDCBd0BZ3/X5fO+Ceu9za2ExIhqFvy6toh9hfFuQfli2qgL41+zj4QJjw8tMeI/k1ImYZ18ZWAZWyS80sO52OisE9oF48gABFZVZPRWHTOfal8cZuIQQqI4YpbsYzMRDhnlj9OCRJEgONnX0wKIaiKGmvITl0BkvAACUWfyCQt6Rer+tieqb8b7fbWp05AuZXyoxC9qVSwGq1KoVCQZkwKw8Ic3s7fqmaUxnK0OeXAcPir6viAT/8dA7IW9b3zQAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Dataset preview&quot;
        title=&quot;&quot;
        src=&quot;/static/1efdcd45451e14c845bef53656ed033f/a4078/dataset.png&quot;
        srcset=&quot;/static/1efdcd45451e14c845bef53656ed033f/c26ae/dataset.png 158w,
/static/1efdcd45451e14c845bef53656ed033f/6bdcf/dataset.png 315w,
/static/1efdcd45451e14c845bef53656ed033f/a4078/dataset.png 503w&quot;
        sizes=&quot;(max-width: 503px) 100vw, 503px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;h3&gt;Architecture&lt;/h3&gt;
&lt;p&gt;In the next step we design the convolutional neural network. Therefore, we make use of the following 7 Keras layers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/preprocessing_layers/image_preprocessing/rescaling/&quot;&gt;Rescaling&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/normalization_layers/batch_normalization/&quot;&gt;BatchNormalization&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/convolution_layers/convolution2d/&quot;&gt;Conv2D&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/pooling_layers/max_pooling2d/&quot;&gt;MaxPooling2D&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/reshaping_layers/flatten/&quot;&gt;Flatten&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/core_layers/dense/&quot;&gt;Dense&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://keras.io/api/layers/regularization_layers/dropout/&quot;&gt;Dropout&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There are 345 classes in total. The input shape is &lt;strong&gt;(28, 28, 1)&lt;/strong&gt; since all images have a size of 28x28 pixel and 1 color channel (grayscale).&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;n_classes &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;345&lt;/span&gt;
input_shape &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

model &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Sequential&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;
    Rescaling&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1.&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; input_shape&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;input_shape&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    BatchNormalization&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;

    Conv2D&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; kernel_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; padding&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;same&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;relu&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    Conv2D&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; kernel_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; padding&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;same&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;relu&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    Conv2D&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; kernel_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; padding&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;same&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;relu&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    BatchNormalization&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    MaxPooling2D&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;pool_size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;

    Flatten&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;

    Dense&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;700&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;relu&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    BatchNormalization&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    Dropout&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;

    Dense&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;relu&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    BatchNormalization&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    Dropout&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;

    Dense&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;400&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;relu&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    Dropout&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;

    Dense&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;n_classes&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; activation&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;softmax&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Moreover, here&apos;s a summary of the model. In total the modal has 2,068,019 parameters. 2,065,597 of them are trainable.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;Layer (type)                 Output Shape              Param #
=================================================================
rescaling (Rescaling)        (None, 28, 28, 1)         0
_________________________________________________________________
batch_normalization (BatchNo (None, 28, 28, 1)         4
_________________________________________________________________
conv2d (Conv2D)              (None, 28, 28, 6)         60
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 28, 28, 8)         440
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 28, 28, 10)        730
_________________________________________________________________
batch_normalization_1 (Batch (None, 28, 28, 10)        40
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 14, 14, 10)        0
_________________________________________________________________
flatten (Flatten)            (None, 1960)              0
_________________________________________________________________
dense (Dense)                (None, 700)               1372700
_________________________________________________________________
batch_normalization_2 (Batch (None, 700)               2800
_________________________________________________________________
dropout (Dropout)            (None, 700)               0
_________________________________________________________________
dense_1 (Dense)              (None, 500)               350500
_________________________________________________________________
batch_normalization_3 (Batch (None, 500)               2000
_________________________________________________________________
dropout_1 (Dropout)          (None, 500)               0
_________________________________________________________________
dense_2 (Dense)              (None, 400)               200400
_________________________________________________________________
dropout_2 (Dropout)          (None, 400)               0
_________________________________________________________________
dense_3 (Dense)              (None, 345)               138345
=================================================================
Total params: 2,068,019
Trainable params: 2,065,597
Non-trainable params: 2,422&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;Training&lt;/h3&gt;
&lt;p&gt;We&apos;ll train the neural network for 14 epochs. At the end of the training the resulting Keras model is saved to the &lt;code class=&quot;language-text&quot;&gt;models&lt;/code&gt; directory. Additionally, &lt;a href=&quot;https://www.tensorflow.org/tensorboard&quot;&gt;TensorBoard&lt;/a&gt;
helps us to visualize the training process.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;epochs &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;14&lt;/span&gt;

logdir &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; os&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;path&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;join&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;logs&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; datetime&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;datetime&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;now&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;strftime&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;%Y%m%d-%H%M%S&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
tensorboard_callback &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; TensorBoard&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;logdir&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; histogram_freq&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

model&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;fit&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    train_ds&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    validation_data&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;val_ds&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    epochs&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;epochs&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    verbose&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    callbacks&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;tensorboard_callback&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

model&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;save&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&apos;./models/model_&apos;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; datetime&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;datetime&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;now&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;strftime&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;%Y%m%d-%H%M%S&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;After 14 epochs of training the network has a validation accuracy of &lt;strong&gt;61.15%&lt;/strong&gt;, what&apos;s not that bad for 345 categories. Especially because there a similarities between some. I&apos;m sure there are still some things you can improve to get an even better score.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 359px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/f8ae4a7e17f5ea6c2a9f7d8a8f73fc7a/f5eb6/tensorboard.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 193.67088607594937%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAnCAYAAAAPZ2gOAAAACXBIWXMAAAsTAAALEwEAmpwYAAAD80lEQVR42qVWaW/aQBDl//+mfoyUSjmUs0EokoFwY8Dner0+pvOmHmMIpClFWmbPt3PtPPeccxQEAUVRREmSiKzrmi799QDy/v5Ok8mEZrMZjUYjqqrqckDVBlL7ZVkK6CWthz/f92m9XtN2uxX5XyYXRUEPDw/0+PjYyuVy2Wr9z4D4S9NUgmGMkRaGoSxCe4B+V6IJILSM45gQcSxuNhuyWUbWWlmDxNrfxugLIAaIdp7nVPJkyOBxashxcMqqlnlslnWeOzdGv6dRhdlyEy8Yf0FmNqRg9kGONc0zQwVrnuMQu9W6gi+rRBZ8oWWFXFHuNQQgTFbV42BHpTWUbn1K1gsKPjwyU4/SHbsi3FHOzcUR2TikMom4zzJNDgFhcgvI/QKmQCPWLOP5LIkp8VeULqYUTkYUzcYUczPLKcXzD4r6j3tARAd+aAFZW3W2+qooYTL7lPdbnnNV1ZheU2Iy9nn6GVCdC23V2V2n4wIELcdFfHHejB2vVwigBgUHkIeQpzS8KG0OgnIGsKvpl4BQFZNZZiUACQPicIaUYYnXg3XIr8YA7R2/RbwUw0DwKwDxwwGMIfGDj/GDmzTl9N0L4DarKbI1/RgW9OZXdDMrKLDYwO/zRAHolrzjIiKAcV5T6moahzX55o/MigvL12HFqEQr0azeV5DjioJWNmly3KQepuwbNMsOTjhBTRMM+Ap+xDuHRNMSh3MnKzYc+vb2RsPhUDjl9fWVPM+j+XxOLy8v1O/3hXPG47HMow0GAwnIqSLcU0JSs071Tx08yynYiNtQpWEaeAVaw9zdbifzoFmM0bR/NihIxru7O+ETNPRvb2/F9KurK7q+vqb7+3t6enqS9ZubG3HHlzQKDaENbod2qiXG2scebQjIuQzoqT/UFEziGSHKmEcqKIBGtksBJ9+yAurt8CWaljSkixaDbpk7C4jbYbK+TYAh17CpW1W0vH1LQ5gLICkODAatsKFlNxTS5lDOUlwB2m1k2binBZSvL3Z+q2FjsmgITZjdnF4gLFfIi7K5472sDBPbgcnIt9ZkPC+bCy9jU8YHbLClaDWnGEwYBmQ2K0qmI6bbEcUTjwJvcAgIMKQHVDcosNs1Zf6SGc6jhIEyZreM6VI0hjscX8i+q6AtXMLnPmkIQJhvDX/rMF1Gq8WfqMJHoIrGZPElyKuRtnFN60MAatqgjwBtglC+FrrR1KDoYZWfPkUAAu1A8M6BRjkPk30edkmpO26D1sy3JneKu/wjZaqGuMQF4F8ey3yTYup35XGtTgIYMn8kTAE/pyV5QUXPy0JogTpVu1vC9PDx92ELCEKKGfB5VdFHVNMvJqrEdXX+Pqf8Bhic5En8quueAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Tensorboard&quot;
        title=&quot;&quot;
        src=&quot;/static/f8ae4a7e17f5ea6c2a9f7d8a8f73fc7a/f5eb6/tensorboard.png&quot;
        srcset=&quot;/static/f8ae4a7e17f5ea6c2a9f7d8a8f73fc7a/c26ae/tensorboard.png 158w,
/static/f8ae4a7e17f5ea6c2a9f7d8a8f73fc7a/6bdcf/tensorboard.png 315w,
/static/f8ae4a7e17f5ea6c2a9f7d8a8f73fc7a/f5eb6/tensorboard.png 359w&quot;
        sizes=&quot;(max-width: 359px) 100vw, 359px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;h4&gt;Export&lt;/h4&gt;
&lt;p&gt;Last but not least since the web application requires a TFLite model, we have to convert the Keras model as described &lt;a href=&quot;https://www.tensorflow.org/lite/convert&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# Convert the model&lt;/span&gt;
converter &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; tf&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;lite&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;TFLiteConverter&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;from_saved_model&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;models/&amp;lt;Model&gt;&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;# path to the SavedModel directory&lt;/span&gt;
tflite_model &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; converter&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;convert&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;# Save the model.&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&apos;model.tflite&apos;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&apos;wb&apos;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;as&lt;/span&gt; f&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
  f&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;write&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;tflite_model&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;Web-App&lt;/h2&gt;
&lt;p&gt;Next we&apos;ll create the web application which is a simple &lt;a href=&quot;https://fastapi.tiangolo.com/&quot;&gt;FastApi&lt;/a&gt; server that hosts a single static HTML page where the user can draw a canvas
and the predicted labels are output as a pie chart with their probabilities. The REST API includes a single &lt;code class=&quot;language-text&quot;&gt;POST&lt;/code&gt; endpoint which is used for transforming the canvas.&lt;/p&gt;
&lt;p&gt;Make sure to checkout the &lt;a href=&quot;https://quickdraw-cnn.fly.dev/&quot;&gt;live demo&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/5e58913b06dc1ed3931ed04842c68160/f32b7/webapp.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 60.12658227848101%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAYAAABiDJ37AAAACXBIWXMAAAsTAAALEwEAmpwYAAACFElEQVR42mWSy2sTURTG8zeKYBtti8mkVLGlFbVINKK0BRWLOxHEUkM3igi66MKtm+pCRYIaam0TM+ZhnvOImdfP++gkabzwcc69M/e73znfSVxezZJauMTC4gqZi0tMzaT+w/RsWkPlBmdT8yQF1H4mTXLO4HRyjuu52yQ6nQ69nqVgWRbdbo9Opyuihv7ew7EdnCDAtmzM/SNah2Uc38MZDMQ3G9txcPt9Er7vE68oihTGVxiG+J7+JyqW4M4TDm7lCVcewuNX0LXjyyokPM9TSV+w1+t1CoUCzWZTESlCoUrRlaqQXoOpLI2rj4gu3IVTq7D2FPxgSDoklKVJFItFbFGCLF+uQKhThFtv4EwWMhsMljY1YWYdkjfh4/e4nBGhVGWapoqtVkspVv/4xwof7OjLxroi1RD5tDh7uzciDGRJoo+1Wo1SqUSlUqHdbiPPNeGxwvyuVji/oUuXkKTJHHzZHxHGpkgC2TfpllQYmzPs4e8/sHgfzuU0mSH7eQM2d4aGIELC/SsUiP57gUREEOqo9zDwxlz+USa4l8cXDkdXhMvbrwkt56TL42MzfGZibALpuOUSegPqYk4Pvh7hNhoEUU886A0nQhEuP69yftsk/czEyJssv6hiyFxgdqvCtZc1pThWEUUhoXg0it+emNvEp3Kf9z9dPhy6Ijq8+9YSuaP2e+L886/+5J3JIk4Q/gNoEFUJ/DbjIgAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Webapp Screenshot&quot;
        title=&quot;&quot;
        src=&quot;/static/5e58913b06dc1ed3931ed04842c68160/f058b/webapp.png&quot;
        srcset=&quot;/static/5e58913b06dc1ed3931ed04842c68160/c26ae/webapp.png 158w,
/static/5e58913b06dc1ed3931ed04842c68160/6bdcf/webapp.png 315w,
/static/5e58913b06dc1ed3931ed04842c68160/f058b/webapp.png 630w,
/static/5e58913b06dc1ed3931ed04842c68160/40601/webapp.png 945w,
/static/5e58913b06dc1ed3931ed04842c68160/f32b7/webapp.png 1136w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;h3&gt;Setup&lt;/h3&gt;
&lt;p&gt;For developing the web application we’ll use the following dependencies as listed in &lt;a href=&quot;https://github.com/larswaechter/quickdraw-cnn/blob/main/webapp/requirements.txt&quot;&gt;requirements.txt&lt;/a&gt;:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;fastapi==0.71.0
Pillow==9.0.0
starlette==0.17.1
uvicorn==0.16.0
gunicorn==20.1.0&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;Backend&lt;/h3&gt;
&lt;p&gt;The backend is required to resize the canvas to 28x28 pixel as our training images and to crop its content square and remove blank space.&lt;/p&gt;
&lt;p&gt;Instead of using Python you can accomplish the same using Tensorflow&apos;s &lt;a href=&quot;https://js.tensorflow.org/api/latest/#image.resizeBilinear&quot;&gt;resizeBilinear&lt;/a&gt; function. However, I have had bad experiences with this function.
Using it causes a huge quality loss of the image with unwanted color effects. That&apos;s the reason why I&apos;m using &lt;a href=&quot;https://pypi.org/project/Pillow/&quot;&gt;Pillow&lt;/a&gt; on the backend side.&lt;/p&gt;
&lt;p&gt;The endpoint &lt;code class=&quot;language-text&quot;&gt;/transform&lt;/code&gt; expects an image&apos;s strokes and the bounding box for cropping it. Using these two parameters we call &lt;code class=&quot;language-text&quot;&gt;transform_img&lt;/code&gt; which draws the image using it strokes, resize it and crops it.
The resulting image is returned from the endpoint.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;ImageData&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;BaseModel&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    strokes&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;list&lt;/span&gt;
    box&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;list&lt;/span&gt;

app &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; FastAPI&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token decorator annotation punctuation&quot;&gt;@app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;post&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/transform&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;image_data&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt; ImageData&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    filepath &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;./images/&quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;uuid4&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;.png&quot;&lt;/span&gt;
    img &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; transform_img&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;image_data&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;strokes&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; image_data&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;box&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    img&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;save&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;filepath&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; FileResponse&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;filepath&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; background&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;BackgroundTask&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;remove&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; path&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;filepath&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

app&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mount&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; StaticFiles&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;directory&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;static&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; html&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; name&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;static&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;transform_img&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;strokes&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; box&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;# Calc cropped image size&lt;/span&gt;
    width &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; box&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; box&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
    height &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; box&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; box&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;

    image &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Image&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;new&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;RGB&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;width&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; height&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; color&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    image_draw &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; ImageDraw&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;Draw&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;image&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; stroke &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; strokes&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        positions &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stroke&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
            positions&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;append&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stroke&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;i&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; stroke&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;i&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        image_draw&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;line&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;positions&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; fill&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; width&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; image&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;resize&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;size&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The final image looks as follows:&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 28px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/18859b68fc63422d7d157210b8582748/679a9/preprocessed.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAACVElEQVR42o1UR8tiQRD0PwuevXjy4En0IiiYxayYEwYMmBPmgGIAE2YxfPW2v519fLuH7cMw47zqrq7qUfD5K16vF9bhcCiRSK7XK/aVSmU6nWLzfr/5XwrYrtlsBgKBYrG43+9xTCaTUqmUsohEIp/Phz1SNBqNer2+2Ww4MCULh8NATiaTfD6v1Wp7vV6r1XK73bjy+/3lcvl0OpnNZqfTCRaZTMZoNB4OB67yaDTCBWN1u930ev12u8VHSqXS4XDsdju73d7pdHD7fD6xorjL5eLAqDkejwlM+Fqtlk6nB4OBUCisVqugwD5gKwhyYK/Xu1qt+GAcURAYCKFSqUCVCck2Ho+HAxcKBcaK4eVyeSgUarfbYrGYqNIVIc/ns0ajEdCvCoWCtU3XkBfpwD+RSLBWKYBEMcjOgYPBYDab5duITTweB3k41+/3GdXFYgE7UAZJOatwRm+Px4PPGTag8uVySaVSJBWBDQYD2oFt9LEAklBZumaCgQ5pSfPw/h2whspy4FKpRAcC0zqfz0EbfVoslh9TiSlAfWIqwNCAOZ8zAn3mcjmk4JNiWWKxGFkjQBo+cr1ew8BoNAoxMbNQFdr+GA9cYfg4sFqtJifwHuCKTqdDWQiBwQj8CkwLqPIL4KmgOAdGb1TKarViWu73O37tdruRSARSY485MZlMzA6sy+USqO8niblH23y10ZJMJqPGEPAW0rDKs9kMjP48Sf5sIY7HI5BsKrFCP5vNRrahEfT1XZmv8z+DkgIA5yAhjQDn8+f/grLjXwmMqP/P5/MFlZkzJEqEwwMAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Preprocessed&quot;
        title=&quot;&quot;
        src=&quot;/static/18859b68fc63422d7d157210b8582748/679a9/preprocessed.png&quot;
        srcset=&quot;/static/18859b68fc63422d7d157210b8582748/679a9/preprocessed.png 28w&quot;
        sizes=&quot;(max-width: 28px) 100vw, 28px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;It has a resolution of 28x28 pixel and it&apos;s cropped.&lt;/p&gt;
&lt;h3&gt;Frontend&lt;/h3&gt;
&lt;p&gt;Let&apos;s continue with the frontend part of our web application. Here, we&apos;ll need a drawing area which allows the user to draw a canvas.
&lt;a href=&quot;https://p5js.org/&quot;&gt;p5.js&lt;/a&gt; is a great library for such a use case.&lt;/p&gt;
&lt;p&gt;NOTE: I will not cover each line of code here, only the important ones.
As I mentioned above you can finde the complete code &lt;a href=&quot;https://github.com/larswaechter/quickdraw-cnn/tree/main/webapp&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;Model &amp;#x26; Labels&lt;/h4&gt;
&lt;p&gt;First of all, we load our previous trained TFLite model using &lt;a href=&quot;https://github.com/tensorflow/tfjs/tree/master/tfjs-tflite&quot;&gt;tfjs&lt;/a&gt;:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token function-variable function&quot;&gt;loadModel&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  console&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Model loading...&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  model &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; tflite&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;loadTFLiteModel&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;./models/model.tflite&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  model&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;tf&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// warmup&lt;/span&gt;

  console&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token template-string&quot;&gt;&lt;span class=&quot;token template-punctuation string&quot;&gt;`&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;Model loaded! (&lt;/span&gt;&lt;span class=&quot;token interpolation&quot;&gt;&lt;span class=&quot;token interpolation-punctuation punctuation&quot;&gt;${&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;LABELS&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;length&lt;span class=&quot;token interpolation-punctuation punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt; classes)&lt;/span&gt;&lt;span class=&quot;token template-punctuation string&quot;&gt;`&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;code class=&quot;language-text&quot;&gt;LABELS&lt;/code&gt; is an array that contains all 345 image categories. For reasons of space I placed them in a separate &lt;a href=&quot;https://github.com/larswaechter/quickdraw-cnn/blob/main/webapp/static/scripts/labels.js&quot;&gt;file&lt;/a&gt;.
The order of the its elements is really important, don&apos;t change it! Otherwise your model will make wrong predictions.&lt;/p&gt;
&lt;h4&gt;Drawing&lt;/h4&gt;
&lt;p&gt;Setup p5.js as follows:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;WIDTH&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;500&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;HEIGHT&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;500&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;STROKE_WEIGHT&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;setup&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;createCanvas&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;WIDTH&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;HEIGHT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;strokeWeight&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;STROKE_WEIGHT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;stroke&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;black&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token function&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;#FFFFFF&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Handling mouse movement and click inside the canvas:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;mouseDown&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  clicked &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;
  mousePosition &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;mouseX&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; mouseY&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Check whether mouse position is within canvas&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;mouseMoved&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;clicked &lt;span class=&quot;token operator&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;inRange&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mouseX&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;WIDTH&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;inRange&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mouseY&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;HEIGHT&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    strokePixels&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;Math&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;floor&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mouseX&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    strokePixels&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;Math&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;floor&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mouseY&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token function&quot;&gt;line&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;mouseX&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; mouseY&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; mousePosition&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; mousePosition&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    mousePosition &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;mouseX&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; mouseY&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;mouseReleased&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;strokePixels&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;length&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    imageStrokes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;strokePixels&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    strokePixels &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
  clicked &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;false&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;When the mouse is clicked and moved its x/y coordinates are collected in &lt;code class=&quot;language-text&quot;&gt;strokePixels&lt;/code&gt;.
So the array contains all x and y pixels of the current drawn stroke:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;[
  [x1, x2, ..., xn],
  [y1, y2, ..., yn]
]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;When the mouse is released, the &quot;current stroke&quot; is finished and added to the &lt;code class=&quot;language-text&quot;&gt;imageStrokes&lt;/code&gt; array which
contains all drawn strokes of the canvas. In fact it&apos;s an array of &lt;code class=&quot;language-text&quot;&gt;strokePixels&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;[
  // First stroke
  [[x0, x1, x2, x3, ...], [y0, y1, y2, y3, ...]],

  // Second stroke
  [[x0, x1, x2, x3, ...], [y0, y1, y2, y3, ...]],
  ...
]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Preprocessing&lt;/h4&gt;
&lt;p&gt;Before predicting the label we have to preprocess the canvas using our &lt;code class=&quot;language-text&quot;&gt;/transform&lt;/code&gt; endpoint and &lt;a href=&quot;https://www.tensorflow.org/js&quot;&gt;Tensorflow.js&lt;/a&gt;. Therefore, we use the &lt;code class=&quot;language-text&quot;&gt;imageStrokes&lt;/code&gt;
array that contains all the canvas&apos; strokes:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token function-variable function&quot;&gt;preprocess&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token parameter&quot;&gt;cb&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; min&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; max &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;getBoundingBox&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// Resize to 28x28 pixel &amp;amp; crop&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; imageBlob &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;fetch&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;/transform&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token literal-property property&quot;&gt;method&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;POST&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token literal-property property&quot;&gt;headers&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;token string-property property&quot;&gt;&quot;Content-Type&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;application/json&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token literal-property property&quot;&gt;redirect&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;follow&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token literal-property property&quot;&gt;referrerPolicy&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;no-referrer&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token literal-property property&quot;&gt;body&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;JSON&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;stringify&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;token literal-property property&quot;&gt;strokes&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; imageStrokes&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token literal-property property&quot;&gt;box&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;min&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;x&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; min&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; max&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;x&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; max&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;y&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;response&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; response&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;blob&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; img &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Image&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  img&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;src &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;createObjectURL&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;imageBlob&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  img&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;onload&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; tensor &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; tf&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;tidy&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt;
      tf&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;browser
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;fromPixels&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;img&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;toFloat&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;expandDims&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token function&quot;&gt;cb&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;tensor&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The function &lt;code class=&quot;language-text&quot;&gt;getBoundingBox&lt;/code&gt; calculates the minimum / maximum x and y coordinates of the drawing inside the canvas. Those values are used to crop the canvas on the backend side and remove the white background.&lt;/p&gt;
&lt;h4&gt;Prediction&lt;/h4&gt;
&lt;p&gt;When making predictions we use our &lt;code class=&quot;language-text&quot;&gt;model&lt;/code&gt; and the tensor returned from &lt;code class=&quot;language-text&quot;&gt;preprocess&lt;/code&gt;. Afterwards, we select the top 3 predictions and output their probabilities with a &lt;a href=&quot;https://www.chartjs.org/docs/latest/charts/doughnut.html#pie&quot;&gt;pie chart&lt;/a&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token function-variable function&quot;&gt;predict&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;!&lt;/span&gt;imageStrokes&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;length&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;LABELS&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;length&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Error&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;No labels found!&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;preprocess&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;tensor&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; predictions &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; model&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;tensor&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;dataSync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; top3 &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Array&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;from&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predictions&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;p&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; i&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token literal-property property&quot;&gt;probability&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; p&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;token literal-property property&quot;&gt;className&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token constant&quot;&gt;LABELS&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;i&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;token literal-property property&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; i&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;sort&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;a&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;probability &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; a&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;probability&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;slice&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;token function&quot;&gt;drawPie&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;top3&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    console&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;top3&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;hr&gt;
&lt;p&gt;That&apos;s it! You just created an application that recognizes hand drawn images using Deep Learning. Show the app to your friends and family. I&apos;m sure they&apos;ll be quite impressed.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Why and How to learn Programming]]></title><description><![CDATA[Programming is one of the most demanded skills in today's world. And in future, it'll play an even bigger role since digitalization is in…]]></description><link>https://larswaechter.dev/why-and-how-to-learn-programming/</link><guid isPermaLink="false">https://larswaechter.dev/why-and-how-to-learn-programming/</guid><pubDate>Mon, 28 Feb 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Programming is one of the most demanded &lt;a href=&quot;https://startuptalky.com/future-top-skills/&quot;&gt;skills&lt;/a&gt; in today&apos;s world. And in future, it&apos;ll play an even bigger role since digitalization is in full swing. Software is an integral part of our lives and even children already learn how to create it at a young age. So why shouldn&apos;t you too? To outsiders, programming might look like some magic that only the smartest wizards on earth are capable of. But that&apos;s certainly not true. Learning it takes a lot of time, hard work and dedication. But in the end, everybody with the right attitude can learn it.&lt;/p&gt;
&lt;p&gt;While learning programming, you can aim for many different skill levels. One might just want to get a brief overview, do it as a hobby or master it and find his profession in it. Nevertheless, there are many reasons why one should learn how to code and even more ways to accomplish it. In this article I&apos;d like to show you my view of the things. &lt;strong&gt;Why&lt;/strong&gt; you should start and &lt;strong&gt;how&lt;/strong&gt; to go about it.&lt;/p&gt;
&lt;h2&gt;Why&lt;/h2&gt;
&lt;p&gt;So, here are my top 3 reasons why you should learn how to code right now.&lt;/p&gt;
&lt;h3&gt;Mind stretching&lt;/h3&gt;
&lt;p&gt;Bill Gates once said: &quot;Learning to write programs stretches your mind, and helps you think better, creates a way of thinking about things that I think is helpful in all domains.&quot;. At least if you can trust images with wise quotes on them and call them a reliable source. Nevertheless, programming is a skill that teaches you a new way of thinking and problem solving. It improves your problem solving skills and enhances logical thinking. You learn abstraction, to focus on the important things. Even if you don&apos;t become an expert in programming, you&apos;ll profit from knowing the basics. Logical thinking and problem solving are key skills in almost every domain and required for many different kind of jobs.&lt;/p&gt;
&lt;p&gt;Furthermore, there&apos;s also a lot of joy while writing software: solving a problem you were working on for days, fixing that nasty bug and seeing your compiler run successfully, presenting your final work to family, friends and co-workers, developing tools that make the world a better place. Simply letting the imagination run wild. And last but not least, being able to understand the memes on &lt;a href=&quot;https://www.reddit.com/r/ProgrammerHumor/&quot;&gt;r/ProgrammerHumor&lt;/a&gt; of course.&lt;/p&gt;
&lt;h3&gt;Digital Transformation&lt;/h3&gt;
&lt;p&gt;How could one not be amazed by today&apos;s technology? For me, it&apos;s is as breathtaking as scary what technology is capable of and what we achieved with it in the last years. Just take a moment and think about it.&lt;/p&gt;
&lt;p&gt;Digital transformation is changing the world dramatically fast. Almost every day your hear buzzwords like &quot;Cloud Computing&quot;, &quot;Artifical Intelligence&quot;, &quot;Blockchain&quot; or &quot;Big Data&quot; in the news.
There are autonomouse vehicles on the streets, some of which drive better than we humans do. Doctors diagnose diseases like cancer with the help of &lt;a href=&quot;https://www.dkfz.de/en/datascience/machine-learning.html&quot;&gt;Machine Learning&lt;/a&gt;. Computers beat the best chess players with ease. Your Amazon, Netflix and YouTube recommendations know your preferences better than you do. Your habits are all tracked by companies like Meta (Facebook) and Alphabet (Google), whether on smartphones, wearables, voice assistants or any other technical device. You&apos;re online nearly every waking hour, feeding personal data to the algorithms of major tech companies so they can create a digital version of you. No wonder their power exceeds that of most states. It&apos;s ridiculous.&lt;/p&gt;
&lt;p&gt;In today&apos;s world, &lt;a href=&quot;https://www.wired.com/insights/2014/07/data-new-oil-digital-economy/&quot;&gt;data is the new oil&lt;/a&gt;, thanks to the rising number of Internet users, less expensive storage and the increasing CPU power as written in &lt;a href=&quot;https://en.wikipedia.org/wiki/Moore%27s_law&quot;&gt;Moore&apos;s law&lt;/a&gt;. The digital transformation is inevitable and collecting data is already a given.&lt;/p&gt;
&lt;p&gt;All this progress is primarily accomplished by software (and hardware) developed by us humans. Software / Hardware / ML engineers, data scientists, mathematicians, physicists and many more write the code that will run our future and provide the models to predict it. Having at least a small understanding of how this kind of software, models or algorithms in general work, is in my opinion one of the main reasons for learning programming. It&apos;s about building a digital awareness, knowing how your environment works and what technology is capable of nowadays.&lt;/p&gt;
&lt;h3&gt;Job Market&lt;/h3&gt;
&lt;p&gt;Mostly caused by the digital transformation, the worldwide job market is &lt;a href=&quot;https://www.forbes.com/sites/forbestechcouncil/2021/09/09/rising-stars-of-the-tech-world-why-developers-are-job-market-royalty/?sh=401ef6dc8718&quot;&gt;seeking&lt;/a&gt; for talented software engineers, and companies offer great benefits to attract new employees: flexible working hours, home office, high salaries and much more. Tech jobs can be found in almost all industries like: automotive, banking, environment, fashion, health, insurance and public sector.&lt;/p&gt;
&lt;p&gt;Furthermore, your job is safe. It&apos;s very unlikely that you&apos;ll be replaced by someone else in future, be it another employee or an AI. Coding skills are in high demand but not very common, at least not yet. There are too few of us to meet the economy&apos;s needs. That is why it&apos;s not uncommon for companies to apply to the developers these days. You have the free choice.&lt;/p&gt;
&lt;p&gt;Altough a high salary shouldn&apos;t be the only reasons for you to learn how to code. You wouldn&apos;t be happy. Have fun in what you do, especially in your job, because you spend most of your life doing it.&lt;/p&gt;
&lt;h2&gt;How&lt;/h2&gt;
&lt;p&gt;Now that we have discussed the reasons for learning to code, let&apos;s have a look at how to go about it. As I said at the beginning of this post, there are many ways to learn programming: university, school, bootcamps, online courses, self-taught. They all have their pros and cons. The following way is the one I would recommend to a beginner. Here we go.&lt;/p&gt;
&lt;h3&gt;What is programming?&lt;/h3&gt;
&lt;p&gt;First of all, take a moment and think about what programming is at its core, regardless of any programming language. What is it really about and what is a computer&apos;s purpose?&lt;/p&gt;
&lt;p&gt;The concept of programming is largely the same for most of the languages out there, whether you&apos;re learning Python, C, Kotlin, Java or JavaScript: you write a set of instructions (code) that are read and executed sequentially by your machine. You, the instructor, tell the computer what to do and how to behave. Doing so, each written line of code has a certain purpose and effect, whether you&apos;re working on web / desktop apps, microcontrollers or anything else.&lt;/p&gt;
&lt;p&gt;The pool of instructions you can choose from and how they are written depends on your programming language. Nevertheless, the key idea remains the same.&lt;/p&gt;
&lt;p&gt;Source code, especially algorithms, can be visually represented using flowcharts, what makes it much easier for us humans to understand them in many cases. An algorithm is just a collection of instructions with the goal of accomplishing a specific task.&lt;/p&gt;
&lt;p&gt;Let&apos;s have an example. The following algorithm, written in JavaScript, calculates the sum of all numbers from 1 to 10, which is 55, and then prints it.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;let&lt;/span&gt; sum &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;let&lt;/span&gt; i &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; i &lt;span class=&quot;token operator&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; i &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; i &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  sum &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; sum &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; i
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
console&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;sum&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The according flowchart looks as follows:&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 602px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/acff27ab305eb8e66683f012d21ac639/32056/diagram.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 71.51898734177216%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB7ElEQVR42qVTz08aURBeXTCRppJyqIlt/4D2QDyaWHswnEwPGkLhwhXjX8G1NUYPBIzSQ9sj4crJAwmJchATEpBEk4K4uCyQsj/fvl0jvs6jj2bTaol1kskks5PvffN9sxw3JgghE8PabM7dYFxDuk6uMTaIqr5n33nuIRGPxydpvRWElze2fYERooADomlr/wX4B1v+vFB48/3gwPsYkCHDRqOxoKpq8vjkZKfT6ez1er2oU5IHsaJVkqRVhNBlv98/xRiLUD86H3xMPIX8t24kk+EJE/8+hoIgBG3bbsGqTcuyeoqibN7J0NnIAPCoB+liOcU0nAeQrW63G4e6LYpikM26HbMujnDcBEHoBVEU35hVh+KHw+FXoVBo6t6pAULfTMPowm1d9cXWBjMgBvm1Xq8ngc3nXC63DO0ZWHtd13UVWKYCgYA3lUo9AwkSsizvgkn7MPuJG2B8RliokpSggD9kOQEnIsF51AzDEEql0gfaB6AknQPQo0gkMptOp2c1TasC0AVkC9w/5JRq1Ucsa4WY5iLJ513jLC6Xy29Ba59TBgg35PRfpvz+b3+ZwrN0MaDnpmkuZbPZd8VicaVSqbx2GhiLxTxDLArCHOLvuvrR2YCrUViLtNttG86G1i+07/f7n0DxjG7zJ6IahLqMLDQDAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Diagram&quot;
        title=&quot;&quot;
        src=&quot;/static/acff27ab305eb8e66683f012d21ac639/32056/diagram.png&quot;
        srcset=&quot;/static/acff27ab305eb8e66683f012d21ac639/c26ae/diagram.png 158w,
/static/acff27ab305eb8e66683f012d21ac639/6bdcf/diagram.png 315w,
/static/acff27ab305eb8e66683f012d21ac639/32056/diagram.png 602w&quot;
        sizes=&quot;(max-width: 602px) 100vw, 602px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see, the program can be split into smaller parts that even a non-programmer can understand. In total, there are five instructions &lt;code class=&quot;language-text&quot;&gt;sum=0&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;i=1&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;sum=sum+i&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;i=i+1&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;print sum&lt;/code&gt; to execute and one condition to check &lt;code class=&quot;language-text&quot;&gt;i&amp;lt;=10&lt;/code&gt;. This is obviously a fairly simple algorithm. Others can contain hundreds or even thousands of instructions, making them much more complicated.&lt;/p&gt;
&lt;p&gt;You may have noticed that the flowchart and the algorithm it represents work independently of any programming language. You can take the chart and implement its sequence of commands in Python, C or any other language. That&apos;s the key idea that all languages have in common. Focus on getting used to this kind of workflow.&lt;/p&gt;
&lt;p&gt;Now that you have an idea about what programming is, it&apos;s time to introduce you to Karel. He teaches you how to code by following your commands.&lt;/p&gt;
&lt;h3&gt;Karel The Robot&lt;/h3&gt;
&lt;p&gt;Since there are so many similarities between the languages, I don&apos;t recommend you to start with one of the common ones I just mentioned above, even though this might be the conventional way to go. You&apos;d be better off sticking with &lt;a href=&quot;https://en.wikipedia.org/wiki/Karel_(programming_language)&quot;&gt;Karel The Robot&lt;/a&gt;. Karel is an educational programming language developed by the American professor &lt;a href=&quot;https://en.wikipedia.org/wiki/Richard_E._Pattis&quot;&gt;Richard E. Pattis&lt;/a&gt;, that teaches you the core concepts of imperative programming. It does so by allowing you to write instructions to control a robot&apos;s movement on a 2-dimensional map, mostly a maze. In fact, this is what programming is all about: writing clear and precise instructions to let the computer perform a certain action.&lt;/p&gt;
&lt;p&gt;Using Karel, you don&apos;t have to learn complicated syntax first. Its command set is manageable and very easy to understand, even for a beginner, but the functionality is still similar to those of other languages. To quote Eric Roberts&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In sophisticated languages like Java, there are so many details that learning these
details often becomes the focus of the course. When that happens, the much more critical
issues of problem solving tend to get lost in the shuffle. By starting with Karel, you can
concentrate on solving problems from the very beginning. And because Karel encourages
imagination and creativity, you can have quite a lot of fun along the way. (Source: &lt;a href=&quot;https://cs.stanford.edu/people/eroberts/karel-the-robot-learns-java.pdf&quot;&gt;Eric Roberts, p. 1&lt;/a&gt;)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here&apos;s an example of Karel The Robot. The challenge: move forward to the right beeper (green diamond), pick it up, go back to the starting point and do the same thing for the other one. Step by step.&lt;/p&gt;
&lt;p align=&quot;center&quot;&gt;
  &lt;img src=&quot;./karel.gif&quot;&gt;
&lt;/p&gt;
&lt;p&gt;A solution might look as follows:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;void defuseTwoBombs()
{
    defuseBomb();
    turnRight();
    defuseBomb();
    turnAround();
}

void defuseBomb()
{
    moveForwardWhileClear();
    pickBeeper();
    turnAround();
    moveForwardWhileClear();
}

void moveForwardWhileClear() {
    while(frontIsClear()) {
        moveForward();
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The robot moves forward as long as its front is clear (&lt;code class=&quot;language-text&quot;&gt;moveForwardWhileClear&lt;/code&gt;). It picks the beeper up (&lt;code class=&quot;language-text&quot;&gt;pickBeeper&lt;/code&gt;), turns 180° (&lt;code class=&quot;language-text&quot;&gt;turnAround&lt;/code&gt;) and goes back (&lt;code class=&quot;language-text&quot;&gt;moveForwardWhileClear&lt;/code&gt;). These are the instructions listed inside the function &lt;code class=&quot;language-text&quot;&gt;defuseBomb&lt;/code&gt;. Afterwards, the robot turns 90° to the right (&lt;code class=&quot;language-text&quot;&gt;turnRight&lt;/code&gt;) and does the exact same thing again (&lt;code class=&quot;language-text&quot;&gt;defuseBomb&lt;/code&gt;). Pretty cool.&lt;/p&gt;
&lt;p&gt;Obviously, Karel teaches you only the rudimentary basics of coding and problem solving in general. Sooner or later you have to switch to a &quot;real&quot; and more popular programming language.&lt;/p&gt;
&lt;p&gt;There are multiple versions of Karel The Robot out there. I would recommend to check out the one by GitHub user &lt;a href=&quot;https://github.com/fredoverflow/karel&quot;&gt;fredoverflow&lt;/a&gt; which is written in Java. This one includes multiple exercises the user has to solve, like the one from above (defuseTwoBombs). Alternatively, have a look at the web version developed by Stanford Assistant Professor &lt;a href=&quot;https://stanford.edu/~cpiech/karel/ide.html&quot;&gt;Chris Piech&lt;/a&gt; which has some bugs unfortunately.&lt;/p&gt;
&lt;h3&gt;Pick a language&lt;/h3&gt;
&lt;p&gt;Now it&apos;s time to learn a &quot;real&quot; programming language. There are dozens of articles on the Internet about whether you should start with Python, JavaScript or language xyz. Don&apos;t waste your valuable time so much when making a decision. Pick one and stick with it. In the end, it&apos;s not that important which one you choose. The fastest one you can start with is JavaScript. Just press F12 in your browser to open the DevTools and start typing &quot;Hello World&quot; in it. It takes only one keypress. There are also great &lt;a href=&quot;https://geekflare.com/online-code-editors/&quot;&gt;online editors&lt;/a&gt; you can make use of, altough I would rather recommend to use a local setup on your machine.&lt;/p&gt;
&lt;h3&gt;Learn the fundamentals&lt;/h3&gt;
&lt;p&gt;Start with the fundamentals and repeat them everyday: data types, variables, arithmetic, if-conditions, loops, functions and so on. Some of them should look familiar to you from Karel The Robot. Learn the syntax and semantic of your programming language. In the beginning, it&apos;s not about knowing every feature, method or API that it offers. Start easy, learn the basics and take it slow. Future knowledge will build on this.&lt;/p&gt;
&lt;p&gt;Moreover, don&apos;t get stuck in tutorial hell and waste your time watching endless tutorials on YouTube, Udemy or whatsoever where everyone is coding but you. You have to write your own code to learn programming. Try and fail. Make mistakes. If you get stuck on a problem, take a break. I don&apos;t know how many times I was lying in bed, sitting in the train or at the dinner table and the solution just came out of nowhere to my mind. It&apos;s amazing how our brain can solve problems in the background without actively paying attention to them.&lt;/p&gt;
&lt;p&gt;Most important: build a daily habit. Code every day, even if it&apos;s just for a short period of time like 10 or 15 minutes. Repetition is the key to success.&lt;/p&gt;
&lt;h3&gt;Learn the algorithms and data structures&lt;/h3&gt;
&lt;p&gt;Next, learn the algorithms and get used to what I call &quot;computational&quot; or logical thinking. This might be not easy. Take a problem, break it down into smaller ones and solve them step by step. Get used to a sequential workflow. Just as you did for Karel The Robot. Before writing the code, take a sheet of paper, make some sketches, draw a flowchart and try different approaches. When you&apos;re done, pick the next one and include solutions from problems you&apos;ve solved before. Your first solution might not be the most efficient one. That&apos;s okay. Get your code working and improve it afterwards. But please don&apos;t copy solutions that you don&apos;t understand and take them for granted.&lt;/p&gt;
&lt;p&gt;It&apos;s not about learning every algorithm out there for sorting an array, traversing a binary tree or finding the shortest path. Have a look at some existing algorithms and try to implement or even slightly modify them. Give &lt;a href=&quot;https://leetcode.com/&quot;&gt;LeetCode&lt;/a&gt; a try. It&apos;s a great website for doing coding challenges.&lt;/p&gt;
&lt;p&gt;Moreover, get in touch with the most common data structures: Arrays, Lists, Queues, Stacks, Maps, HashTables, Trees. Try to use some of them when working on different problems. I could bet you will not use more than two or three of them in your future workday. Especially trees are rather uncommon.&lt;/p&gt;
&lt;p&gt;In this step, you may also want to take a look at some concepts such as OOP or functional programming, depending on your language.&lt;/p&gt;
&lt;h3&gt;Get back to the roots&lt;/h3&gt;
&lt;p&gt;Get back to the roots. Code without using a heavyweight IDE like IntelliJ or Visual Studio. Get rid of tools like Linters and Prettiers which highlight your code smells and autoformat your code. Get rid of fancy frameworks and libs that act like magical black boxes. Get rid of build tools that take more time building the project than the coding itself. They are unnecessary ballast.&lt;/p&gt;
&lt;p&gt;Don&apos;t get me wrong, all these tools are amazing and I highly encourage you to use them in your later career. But in the beginning, they just distract you from your main goal: learning programming. Add them to your repetoir later on after you&apos;ve learnt the fundamentals.&lt;/p&gt;
&lt;p&gt;Keep in mind that you don&apos;t need much to get started. What you really need is a simple text editor and a compiler / interpreter for your programming language of choice. Above all, you don&apos;t need a +1000€ MacBook with fancy stickers on it, beside you want to fit the clichés. If you want to learn programming by creating the next &lt;a href=&quot;https://www.crysis.com/&quot;&gt;Crysis&lt;/a&gt;, you might need one too.&lt;/p&gt;
&lt;h3&gt;Teach others&lt;/h3&gt;
&lt;p&gt;In my opinion, sharing knowledge is one of the greatest things you can do with it. Schwarzenegger already said: &quot;Help others and give something back&quot;. So share your expertise and new discoveries with others. Both, you and your learning partner, will highly benefit from it. Maybe start your own blog too?&lt;/p&gt;
&lt;p&gt;The programming community is huge, take advantage of that and get into conversations. You can participate in discussions on platforms like &lt;a href=&quot;https://dev.to/&quot;&gt;DEV&lt;/a&gt; or &lt;a href=&quot;https://stackoverflow.com/&quot;&gt;Stackoverflow&lt;/a&gt;, join multiple subs on &lt;a href=&quot;https://reddit.com/&quot;&gt;Reddit&lt;/a&gt; or attend local meetups in your area. In times of the Internet there are endless possibilities.&lt;/p&gt;
&lt;h3&gt;Learn the tools&lt;/h3&gt;
&lt;p&gt;Once you know the fundamentals and some advanced concepts, go ahead and get familiar with tools like: GIT, Linters, IDEAs, Maven / Gradle / Webpack. Be amazed by IntelliJ&apos;s autocompletion and it&apos;s code analyzing capacity. Learn some common used libraries and frameworks for your programming language, but please don&apos;t end up coding dozens of similar CRUD REST-APIs.&lt;/p&gt;
&lt;p&gt;Include these tools into your daily workflow and start working on your first &quot;bigger&quot; project. Make it open source and share it on &lt;a href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt; so other people can contribute and give feedback.&lt;/p&gt;
&lt;h3&gt;Land an internship&lt;/h3&gt;
&lt;p&gt;Finally, after you have learnt the basics, some advanced concepts and tools, go ahead and apply for a software engineering internship near your location and surrond yourself with people that are more experienced than you. Especially when you&apos;re a student. The hands-on experience you gain may be worth much more than any course you&apos;ll ever take.&lt;/p&gt;
&lt;p&gt;With that being said gain as much experience as possible: get in touch with production code, work in an interdisciplinary team, join discussions and code reviews, deploy applications, drop the live database (joke). And one of the most important things: ask questions, lots of questions!&lt;/p&gt;
&lt;p&gt;Landing and internship can be hard, I know. You might have to run through multiple assessment centers, coding interviews / challenges and so on. Don&apos;t be discouraged when you fail your first ones. &lt;a href=&quot;https://www.youtube.com/watch?v=bx3--22D4E4&quot;&gt;Coding interviews are broken&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Last words&lt;/h2&gt;
&lt;p&gt;That&apos;s it. Sounds complicated? Yeah, it is. Don&apos;t let anyone tell you otherwise. It&apos;s no reason why you shouldn&apos;t start right now. Take your time, follow a plan and you&apos;ll make it. I promise. Go for it, you won&apos;t regret it.&lt;/p&gt;
&lt;p&gt;Let me know if this article helped you or not.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Improving Minimax performance]]></title><description><![CDATA[The Minimax algorithm, also known as MinMax, is a popular algorithm for calculating the best possible move a player can player in a zero…]]></description><link>https://larswaechter.dev/minimax-performance-improvements/</link><guid isPermaLink="false">https://larswaechter.dev/minimax-performance-improvements/</guid><pubDate>Mon, 29 Nov 2021 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The &lt;a href=&quot;https://en.wikipedia.org/wiki/Minimax&quot;&gt;Minimax&lt;/a&gt; algorithm, also known as MinMax, is a popular algorithm for calculating the best possible move a player can player in a zero-sume game, like Tic-Tac-Toe or Chess. It makes use of an evaluation-function provided by the developer to analyze a given game board. During the execution Minimax builds a game tree that might become quite large. This causes a very long runtime for the algorithm.&lt;/p&gt;
&lt;p&gt;In this article I&apos;d like to introduce 10 methods to improve the performance of the Minimax algorithm and to optimize its runtime. Some of them have a bigger and some a smaller impact. In the future I&apos;ll try to add new methods. I won&apos;t go into more detail about how the algorithm works. It&apos;s just about optimizing it. Check out the link from above to learn how the algorithm actually works.&lt;/p&gt;
&lt;p&gt;A quick overview of all techniques discussed in this article:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Alpha-Beta Pruning&lt;/li&gt;
&lt;li&gt;Pre-sort moves&lt;/li&gt;
&lt;li&gt;Bitboards&lt;/li&gt;
&lt;li&gt;Transposition Tables&lt;/li&gt;
&lt;li&gt;Board Symmetries&lt;/li&gt;
&lt;li&gt;Reduce possible moves&lt;/li&gt;
&lt;li&gt;Instant win&lt;/li&gt;
&lt;li&gt;Improve .hasPlayerWon() function&lt;/li&gt;
&lt;li&gt;Improve .evaluate() function&lt;/li&gt;
&lt;li&gt;Decrease search depth&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;1. Alpha-Beta Pruning&lt;/h2&gt;
&lt;p&gt;One of the most widely-known improvements is &lt;a href=&quot;https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning&quot;&gt;Alpha-Beta-Pruning&lt;/a&gt;, also known as Alpha-Beta-Cut or Alpha-Beta-Search. This slightly modified version of Minimax can reduce the algorithm&apos;s runtime drastically. The key idea here is to reduce the number of nodes within the game tree by cutting them off. Therefore, two values α and β are passed along the tree. These values represent the worst-case-scenario for each player.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/4a7e11b8a8f9bfa2943ab21afc3b5040/d9ed5/alpha_beta_pruning.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 50.632911392405056%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAYAAAC0VX7mAAAACXBIWXMAAAsTAAALEwEAmpwYAAACMklEQVR42jVR2ZKaUBDl/38oNVVTycOM44xiXABB9p3hiiguCCh90pDk4dTte3o/LYXotBDtOaD2EFJbBn1TDm+ErozxLLciK2f6duQT5gY+7Nsx5j+YO9jNpVKPe1PK0MV7EFK0xDYKPJFSA687w65L2Jc99CKGcz+OiPoaAg/kjCH+H4jz4dSlkJ7wIiBkt9uzTWGyorxY0fVu0BMOVZcdhfGSevbV3Y7/KnnRgs633chxHsd5fds7ON/0fCgYAxHP5VP39GA5n6guBgYOCDhoB9OZomf7LyK4/L8yT/DxIA/DIO3TwbFShZSgiXMO89sLqamPpL9DzTjpUrIMD/hNhVXkQEkCJCzFJg3wtZbhVPvRn+DOaIgB934SUtzXccG9rNOeZENlPVroaQgt8XHgGXdFhoHfuAaC+wmKu8PrbAKVGwzax1QPRSl8XLEtMyGxDnH38BCEC7rdDYTxb7QPF6LYwA8WiNMFjmcNhjWFH8qj37QnkBcvKEqFSwbjyh1reLlthcQHiaqrCTdc9uCllO0b3c4G3RqfdOuLsr1GZz6MaUwpTBWKMoX5D1qsf1LyvaEhZzho87C5sZpLaX2NFd+CnnABXkPzTbzPpzBFCj12oYYO5ts1JvMJzO8IZhZANjW8r+d4Y2zTCCeA9sO52puQrKrYyKZRLj0nX7uO2ASeeJVnYuHaYulYYqZrYqKsxcvnh9CiYOR+rWTxY/ImXj7excy1RA7kdl0dlOJb/wPp1t+tIIxzIAAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Alpha Beta Pruning&quot;
        title=&quot;&quot;
        src=&quot;/static/4a7e11b8a8f9bfa2943ab21afc3b5040/f058b/alpha_beta_pruning.png&quot;
        srcset=&quot;/static/4a7e11b8a8f9bfa2943ab21afc3b5040/c26ae/alpha_beta_pruning.png 158w,
/static/4a7e11b8a8f9bfa2943ab21afc3b5040/6bdcf/alpha_beta_pruning.png 315w,
/static/4a7e11b8a8f9bfa2943ab21afc3b5040/f058b/alpha_beta_pruning.png 630w,
/static/4a7e11b8a8f9bfa2943ab21afc3b5040/40601/alpha_beta_pruning.png 945w,
/static/4a7e11b8a8f9bfa2943ab21afc3b5040/78612/alpha_beta_pruning.png 1260w,
/static/4a7e11b8a8f9bfa2943ab21afc3b5040/d9ed5/alpha_beta_pruning.png 2880w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Have a look at the second row (&lt;code class=&quot;language-text&quot;&gt;3 6 3&lt;/code&gt;). Here, the α value is 6, which is the minimum score that &lt;code class=&quot;language-text&quot;&gt;MAX&lt;/code&gt; will reach after evaluating the first two nodes (&lt;code class=&quot;language-text&quot;&gt;3 6&lt;/code&gt;). When evaluating the third node &lt;code class=&quot;language-text&quot;&gt;MIN&lt;/code&gt; keeps in mind that &lt;code class=&quot;language-text&quot;&gt;MAX&lt;/code&gt; will at least achieve a score of &lt;code class=&quot;language-text&quot;&gt;6&lt;/code&gt;. If &lt;code class=&quot;language-text&quot;&gt;MIN&lt;/code&gt; finds a value that is less than α, here &lt;code class=&quot;language-text&quot;&gt;5&lt;/code&gt;, the other node &lt;code class=&quot;language-text&quot;&gt;8&lt;/code&gt; can be cut off. The reason: no matter what &lt;code class=&quot;language-text&quot;&gt;MIN&lt;/code&gt; chooses, &lt;code class=&quot;language-text&quot;&gt;MAX&lt;/code&gt; will choose the α value &lt;code class=&quot;language-text&quot;&gt;6&lt;/code&gt;. And &lt;code class=&quot;language-text&quot;&gt;MIN&lt;/code&gt; will choose a value that is definitely &amp;#x3C;= &lt;code class=&quot;language-text&quot;&gt;5&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Have a look at the link from above for a more detailed explanation.&lt;/p&gt;
&lt;h2&gt;2. Pre-sort moves&lt;/h2&gt;
&lt;p&gt;Try to pre-sort the list of possible moves starting with the best ones when using Alpha-Beta Pruning. In this case, there&apos;s a higher chance of cutting of nodes within the game tree since the algorithm starts with a high alpha or low beta value at the beginning of each level.&lt;/p&gt;
&lt;h2&gt;3. Bitboards&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Bitboard&quot;&gt;Bitboards&lt;/a&gt; are a way of representing the game board using bits. In this case, each single bit represents one position on the board. Moreover, both players have their own board.&lt;/p&gt;
&lt;p&gt;An example bitboard for Tic-Tac-Toe:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; board &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;
  &lt;span class=&quot;token number&quot;&gt;0b000_000_000&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// Player 1 Board (X)&lt;/span&gt;
  &lt;span class=&quot;token number&quot;&gt;0b000_000_000&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// Player 2 Board (O)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;One of the main advantages of bitboards is that they allow a lot of flexibility in evaluation. Using bitwise opertations like &lt;code class=&quot;language-text&quot;&gt;AND&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;OR&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;XOR&lt;/code&gt; and shifting you can check for winning conditions, play &amp;#x26; validate moves or rotate the game board in a very short time. They are also useful for calculating the board hash, which is used for transposition tables.&lt;/p&gt;
&lt;p&gt;Depending on the complexity of your game bitboards might make a remarkable difference in terms of performance. Check out this &lt;a href=&quot;https://github.com/denkspuren/BitboardC4/blob/master/BitboardDesign.md&quot;&gt;link&lt;/a&gt; to see a Connect Four implementation using bitboards.&lt;/p&gt;
&lt;h2&gt;4. Transposition Tables&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Transposition_table&quot;&gt;Transposition tables&lt;/a&gt; are used to store the result of already analyzed boards. This prevents the algorithm from evaluating the same board multiple times and reading it from a memory, the transposition table, instead.&lt;/p&gt;
&lt;p&gt;Usually, transposition tables are implemented as a &lt;code class=&quot;language-text&quot;&gt;HashMap&lt;/code&gt; where the key is the hashed board. You can either store the transposition table in-memory and build it during the Minimax execution or store it in a non-volatile memory, like a text file for example.&lt;/p&gt;
&lt;p&gt;A transposition table might look as follows:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;8063104835353205054 2 -8534.0 -1
3522504971336218492 1 1082.0 -1
9207316698546002515 5 2705.0 1&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Each single row contains information about:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the board hash&lt;/li&gt;
&lt;li&gt;the played move&lt;/li&gt;
&lt;li&gt;the move&apos;s evaluated score&lt;/li&gt;
&lt;li&gt;the move&apos;s player&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In Minimax, you can search for the current board hash within the transposition table and return the according entry.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;minimax&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;storage&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; game&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token comment&quot;&gt;// recursion anchor ...&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; storedMove &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; storage&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;calcBoardHash&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;storedMove&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; storedMove

  &lt;span class=&quot;token comment&quot;&gt;// evaluation ...&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If not entry was found, the board must first be evaluated. At the end of Minimax you can push the evaluated move to the transposition table right before it&apos;s returned:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;minimax&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;storage&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; game&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; bestMove&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// evaluation ...&lt;/span&gt;
    storage&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;calcBoardHash&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; bestMove&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; bestMove&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;5. Board Symmetries&lt;/h2&gt;
&lt;p&gt;The key idea is that you apply a symmetrie to your current examined board and read its counterpart from the memory, if existing. This reduces the number of board evaluations immensely. Symmetries are very powerful especially in combination with bitboards.&lt;/p&gt;
&lt;p&gt;Depending on your game there are different symmetries that you can make use of. For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Inverting the board&lt;/li&gt;
&lt;li&gt;Rotating the board (and inverting) =&gt; Tic-Tac-Toe, Mill&lt;/li&gt;
&lt;li&gt;Mirroring the board on the x/y axis (and inverting) =&gt; Connect Four, Chess&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With Bitboards you can easily rotate and mirror the board using binary operations. Check out &lt;a href=&quot;https://gist.github.com/larswaechter/9426ac46cfea79cc8ca5f06f0ca6f486&quot;&gt;this&lt;/a&gt; GitHub Gist to see a Bitboard for Tic-Tac-Toe in Kotlin.&lt;/p&gt;
&lt;h3&gt;Inverting the board&lt;/h3&gt;
&lt;p&gt;Tic-Tac-Toe&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1)          2)

X . .       O . .
X O O       O X X
. . .       . . .&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In the first scenario, the best possible move for player &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; is to play position &lt;code class=&quot;language-text&quot;&gt;7&lt;/code&gt; (bottom left). The same applies to player &lt;code class=&quot;language-text&quot;&gt;O&lt;/code&gt; in the second case. If Minimax have already calculated the best possible move for board #1 and it&apos;s stored in a transposition table, you can invert the board in the case of board #2, which gives you board #1, and read the best possible move of board #1 from memory and apply it. Keep in mind that this only applies to player &lt;code class=&quot;language-text&quot;&gt;O&lt;/code&gt; for the second board.&lt;/p&gt;
&lt;h3&gt;Rotating the board&lt;/h3&gt;
&lt;p&gt;Tic-Tac-Toe&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1)          2)

X . .       . X X
X O O       . O .
. . .       . O .&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Again, the best move for player &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; is to play position &lt;code class=&quot;language-text&quot;&gt;7&lt;/code&gt; in the first scenario. The second board is the same as the first one, but rotated by 90° clockwise. This time if Minimax have already evaluated board #1, you can rotate board #2 by 90°, which gives you board #1, and again read the best possible move of board #1 from memory. In this case you have to slightly modify the move: since the board was rotated by 90° clockwise you have to rotate the move 90° counter clockwise. Repeat this procedure for 180° and 270°.&lt;/p&gt;
&lt;p&gt;Moreover, you can combine this method with the inverted board from above.&lt;/p&gt;
&lt;h3&gt;Mirroring the board&lt;/h3&gt;
&lt;p&gt;Connect Four&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;1)                  2)

. . . . . . .       . . . . . . .
. . . . . . .       . . . . . . .
. . . . . . .       . . . . . . .
. X . . . . .       . . . . . X .
. X . O O . .       . . O O . X .
. X O X O . .       . . O X O X .&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here, the best move for player &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; is to play column &lt;code class=&quot;language-text&quot;&gt;2&lt;/code&gt; in the first scenario. The second board is the same as the first one, but mirrored on the center y-axis. This time, after the evaluation of board #1, you can mirror board #2, which gives you board #1, and apply its best move. Don&apos;t forget to to mirror the move as well.&lt;/p&gt;
&lt;p&gt;Once more, you can combine this technique with the inverted board.&lt;/p&gt;
&lt;h2&gt;6. Reduce possible moves&lt;/h2&gt;
&lt;p&gt;Keep in mind that each single move causes a new child node that has to be evaluated recursively. Therefore, it&apos;s simple: a smaller number of possible moves for each board leads to less nodes and evaluations in your game tree. That means: remove unnecessary and irrelevant moves. For example, in Connect-Four, don&apos;t play any moves that will definitely not result in a row of 4 in future. Be careful not to remove any moves that could prevent your opponent from winning.&lt;/p&gt;
&lt;h2&gt;7. Instant win&lt;/h2&gt;
&lt;p&gt;Before evaluating all possible moves you can check whether any of them will result in an instant win for the current player. If that&apos;s the case you can directly return this move and you don&apos;t have to evaluate the other ones.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;minimax&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;game&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token comment&quot;&gt;// recursion anchor ...&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; move &lt;span class=&quot;token keyword&quot;&gt;of&lt;/span&gt; game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;getPossibleMoves&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;doMove&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;move&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;hasPlayerWon&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;currentPlayer&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1_000_000&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; move&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;

  &lt;span class=&quot;token comment&quot;&gt;// evaluation ...&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Furthermore, make sure to return a high score since it&apos;s a win-move.&lt;/p&gt;
&lt;h2&gt;8. Improve .hasPlayerWon() function&lt;/h2&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;.hasPlayerWon()&lt;/code&gt; function checks whether a player has won. It&apos;s commonly used in the recursion anchor, when evaluating the game board. Here, we can optimize two things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Don&apos;t check before a win is possible&lt;/li&gt;
&lt;li&gt;Don&apos;t check both players&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;hasPlayerWon&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;player&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;playedMoves &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;false&lt;/span&gt;
  &lt;span class=&quot;token comment&quot;&gt;// check if the given player has won ...&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;For example, in Tic-Tac-Toe, at least 5 moves must have been played before a player can win. That&apos;s why we immediately return &lt;code class=&quot;language-text&quot;&gt;false&lt;/code&gt; when less than 5 moves were played.&lt;/p&gt;
&lt;p&gt;Moreover, we only have to check whether one player has won, not both. The player who played the last move is the only one who could have won so we don&apos;t have to check the other one.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;minimax&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;nodeHeight&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; game&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token comment&quot;&gt;// recursion anchor&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    nodeHeight &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;||&lt;/span&gt;
    game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isDraw&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;||&lt;/span&gt;
    game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;hasPlayerWon&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;currentPlayer&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;evaluate&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;token comment&quot;&gt;// ...&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here, when calling &lt;code class=&quot;language-text&quot;&gt;game.hasPlayerWon()&lt;/code&gt; we check whether the previous player (the one who played the last move) has won. If player A is stored as &lt;code class=&quot;language-text&quot;&gt;1&lt;/code&gt; and player B as &lt;code class=&quot;language-text&quot;&gt;-1&lt;/code&gt; you can easily switch between them using a negate: &lt;code class=&quot;language-text&quot;&gt;-game.currentPlayer&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;9. Improve .evaluate() function&lt;/h2&gt;
&lt;p&gt;The evaluation function is called dozen of times during the execution of Minimax. That means: improve this function and make it as fast as possible. Combine it with Bitboards and check for a player&apos;s win blazing fast.&lt;/p&gt;
&lt;p&gt;Moreover, there&apos;s no need to dig into the depths of the game tree if your evaluation function returns a score that reflects the board quite well. Just a single descent within the game tree can lead to a much longer runtime.&lt;/p&gt;
&lt;p&gt;Another tip: include the current node height in the evaluation score. Moves that are higher up in the game tree will have a better score this way and the algorithm will pick the one that leads the fastest to a win.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function-variable function&quot;&gt;evaluate&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;nodeHeight&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; score&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// calc score ...&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; score &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; nodeHeight&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;minimax&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;nodeHeight&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; game&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// recursion anchor&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;nodeHeight &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;||&lt;/span&gt; game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isDraw&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;||&lt;/span&gt; game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;hasPlayerWon&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;currentPlayer&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;game&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;evaluate&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;nodeHeight&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// evaluation ...&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;10. Decrease search depth&lt;/h2&gt;
&lt;p&gt;The last option might be the most obvious one: decrease the maximum search depth of the algorithm.
Does your game tree really have to be that deep? Do you have to look 9 or 10 moves ahead? Isn&apos;t a lookahead of 5 enough? Depending on the game, I guess most human players cannot anticipate more than maybe 3 to 4 moves. As I already said above, each single tree level results in a much longer runtime. Think about it.&lt;/p&gt;
&lt;h2&gt;Further resources&lt;/h2&gt;
&lt;p&gt;Last but not least a list with some useful resources.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We blog: &lt;a href=&quot;https://blog.theofekfoundation.org/artificial-intelligence/2015/12/18/minimax-improvements/&quot;&gt;Minimax Improvements&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Chessprogramming: &lt;a href=&quot;https://www.chessprogramming.org/Bitboards&quot;&gt;Bitboards&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Wikipedia: &lt;a href=&quot;https://en.wikipedia.org/wiki/Transposition_table&quot;&gt;Transposition Tables&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Check out my example projects as well:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/larswaechter/connect-four-kotlin&quot;&gt;Connect Four&lt;/a&gt; in Kotlin&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://gist.github.com/larswaechter/9426ac46cfea79cc8ca5f06f0ca6f486&quot;&gt;TTT Bitboard&lt;/a&gt; in Kotlin&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://gist.github.com/larswaechter/595f5f63df3de5579e8dbe47b69ede4e&quot;&gt;Minimax&lt;/a&gt; in Kotlin&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://gist.github.com/larswaechter/2c007c00904822b68331fe26736d92a8&quot;&gt;Zobrist Hashing&lt;/a&gt; in Kotlin&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item><item><title><![CDATA[How I structure my React projects]]></title><description><![CDATA[It's been quite a while since I wrote an article about how I structure my Node.js REST APIs. The article covered the approach of designing a…]]></description><link>https://larswaechter.dev/react-project-structure/</link><guid isPermaLink="false">https://larswaechter.dev/react-project-structure/</guid><pubDate>Sun, 29 Aug 2021 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;It&apos;s been quite a while since I wrote an &lt;a href=&quot;/blog/nodejs-rest-api-structure/&quot;&gt;article&lt;/a&gt; about how I structure my Node.js REST APIs. The article covered the approach of designing a well organized and maintainable folder structure for Node.js applications.&lt;/p&gt;
&lt;p&gt;So today I don&apos;t want to talk about Node.js APIs, but about the architecture of &lt;a href=&quot;https://reactjs.org/&quot;&gt;React&lt;/a&gt; applications and answer the same question from the previous article a second time:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;What should the folder structure look like?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;And again: there’s &lt;strong&gt;no perfect or 100% correct&lt;/strong&gt; answer to this question, but there are tons of other articles discussing this one on the internet too. This folder structure is also partly based on multiple of them.&lt;/p&gt;
&lt;p&gt;One important thing to mention is that React does not really tell you how to organize your project, except the fact that you should avoid too much nesting and overthinking. To be exact they say.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;React doesn’t have opinions on how you put files into folders. That said there are a few common approaches popular in the ecosystem you may want to consider. (&lt;a href=&quot;https://reactjs.org/docs/faq-structure.html&quot;&gt;Source&lt;/a&gt;)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Take a look at the linked source where you can read more about those common approaches. They won&apos;t be further discussed in this article.&lt;/p&gt;
&lt;p&gt;The following structure and architecture is one that has proven maintainable and reliable for me. It might give you a help for designing your own project. Keep in mind that the following architecture is based on a application bootstrapped with &lt;a href=&quot;https://github.com/facebook/create-react-app&quot;&gt;create-react-app&lt;/a&gt; and written in &lt;strong&gt;JavaScript&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Directory: root&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── node_modules
├── public
├── src
├── package.json
└── package-lock.json&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This structure is nothing special and shouldn’t be new to you. It’s actually a basic &lt;a href=&quot;https://github.com/facebook/create-react-app&quot;&gt;create-react-app&lt;/a&gt; setup. The interesting part here is the content of the &lt;code class=&quot;language-text&quot;&gt;src&lt;/code&gt; folder which this article is about.&lt;/p&gt;
&lt;p&gt;So what do we have in here?&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── api
├── components
├── i18n
├── modules
├── pages
├── stores
├── tests
├── utils
├── index.js
├── main.js
└── style.css&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;As you can see the application is primarily split into eight directories. From here on, we&apos;ll go top-down through the directories and examine each one.&lt;/p&gt;
&lt;p&gt;Let’s start with the &lt;code class=&quot;language-text&quot;&gt;api&lt;/code&gt; directory.&lt;/p&gt;
&lt;h2&gt;Directory: src/api&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── api
│   ├── services
│   │   ├── Job.js
│   │   ├── User.js
│   ├── auth.js
│   └── axios.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;api&lt;/code&gt; directory contains all services that take care of the communication between the React application (frontend) and an API (backend). A single service provides multiple functions to retrieve data from or post data to an external service using the HTTP protocol.&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-text&quot;&gt;auth.js&lt;/code&gt; provides functions for authentication and &lt;code class=&quot;language-text&quot;&gt;axios.js&lt;/code&gt; contains an &lt;a href=&quot;https://www.npmjs.com/package/axios&quot;&gt;axios&lt;/a&gt; instance including interceptors for the outgoing HTTP requests and incoming responses. Moreover, the process of refreshing JWTs is handled in here.&lt;/p&gt;
&lt;h2&gt;Directory: src/components&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── components
│   ├── Job
│   │   ├── Description.js
│   │   └── Preview.js
│   └── User
│   │   ├── Card.js
│   │   ├── Create.js
│   │   └── List.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If you&apos;re already familiar with React you should know that it&apos;s mainly component based. The components are actually the heart of every React application. The whole application, at least the presentational view, is built of many small components.&lt;/p&gt;
&lt;p&gt;So what is a component?&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. (&lt;a href=&quot;https://reactjs.org/docs/components-and-props.html&quot;&gt;Source&lt;/a&gt;)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Imagine you have a website like Twitter or Facebook. The large website is made of many smaller pieces (components) that can be Buttons, Inputs or Widgets for example. Those pieces are put together to build ever more complex and larger ones. Each component has its own lifecyle and state management, whereby you can share a component&apos;s state with other ones.&lt;/p&gt;
&lt;p&gt;Components are reused multiple times within the application to save the developer from writing redundant code.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://de.wikipedia.org/wiki/Don%E2%80%99t_repeat_yourself&quot;&gt;Don&apos;t repeat yourself (DRY)&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Splitting the codebase into multiple components is not just a &quot;React thing&quot;. It&apos;s a common pattern in software engineering to simplify the development process and the maintenance later on.&lt;/p&gt;
&lt;p&gt;In React, a component is mostly a simple JavaScript function or a class. Usually, I create a new file for each single component. In some rare cases I group multiple of them (functions or classes) into a single file. Imagine a &lt;code class=&quot;language-text&quot;&gt;UserList.js&lt;/code&gt; component which renders multiple elements of &lt;code class=&quot;language-text&quot;&gt;UserListItem&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token function-variable function&quot;&gt;UserList&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; users &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
  &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;ul&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;users&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;user&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
      &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;UserListItem key&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;userId&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; user&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;/&lt;/span&gt;ul&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token function-variable function&quot;&gt;UserListItem&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token parameter&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; user &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;li&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;name&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;/&lt;/span&gt;li&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here, it makes sense to combine both into one file. Further, &lt;code class=&quot;language-text&quot;&gt;UserListItem&lt;/code&gt; is probably not even used by any other component than &lt;code class=&quot;language-text&quot;&gt;UserList&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Beside the components themselves, you can also add their stylesheets or tests to this directory.&lt;/p&gt;
&lt;h2&gt;Directory: src/i18n&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── i18n
│   ├── de.json
│   └── en.json&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;code class=&quot;language-text&quot;&gt;i18n&lt;/code&gt; stands for &lt;strong&gt;internationalization&lt;/strong&gt; and takes care of the language support of the application. The including JSON files are basically objects containg fixed constants as keys and their associated translations as values.&lt;/p&gt;
&lt;p&gt;Therefore, the keys should be equal for each language file. Only the values (translations) differ from each other. You can easily query those language files later on by writing your own custom hook or component.&lt;/p&gt;
&lt;h2&gt;Directory: src/modules&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── modules
│   ├── logger.js
│   └── session.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This directory includes some global modules that might be used for logging or as wrapper for the browser&apos;s &lt;code class=&quot;language-text&quot;&gt;LocalStorage&lt;/code&gt; for example.&lt;/p&gt;
&lt;h2&gt;Directory: src/pages&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── pages
│   ├── Home
│   │   ├── components
│   │   │   ├── Dashboard.js
│   │   │   └── Welcome.js
│   │   └── index.js
│   ├── Login.js
│   └── Profile.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;pages&lt;/code&gt; directory includes the &lt;code class=&quot;language-text&quot;&gt;react-router-dom&lt;/code&gt; paths accessed while navigating through the application. Here, we collect multiple components into a single larger one to display a complete page view.&lt;/p&gt;
&lt;p&gt;A page might contain its own &lt;code class=&quot;language-text&quot;&gt;component&lt;/code&gt; directory which includes &quot;local&quot; components that are only used on this page. For complex pages with a deep component tree you might want to check out the &lt;a href=&quot;https://reactjs.org/docs/context.html&quot;&gt;React Context API&lt;/a&gt; which makes it much easier to pass props along the tree and to handle a global &quot;page state&quot;.&lt;/p&gt;
&lt;h2&gt;Directory: src/stores&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── stores
│   ├── language.js
│   └── user.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This directory includes all global React states that can be accessed from any component within the application. While &lt;a href=&quot;https://react-redux.js.org/&quot;&gt;Redux&lt;/a&gt; is probably the most popular solution for managing global state I prefer to use &lt;a href=&quot;https://github.com/pmndrs/zustand&quot;&gt;zustand&lt;/a&gt;. It&apos;s very easy to get started with and its API is really straightforward.&lt;/p&gt;
&lt;h2&gt;Directory: src/tests&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── tests
│   ├── language.test.js
│   └── utils.test.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;tests&lt;/code&gt; directory includes tests that do not belong to certain components. This could be tests for the implementation of algorithms for example. Moreover, I validate and compare the keys of the language files I mentioned above to make sure I did not miss any translation for a given language.&lt;/p&gt;
&lt;h2&gt;Directory: src/utils&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── utils
│   ├── hooks
│   │   ├── useChat.js
│   │   ├── useOutsideAlerter.js
│   │   ├── useToast.js
│   ├── providers
│   │   ├── HomeContextProvider.js
│   │   ├── ToastContextProvider.js
│   ├── colors.js
│   ├── constants.js
│   ├── index.js&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here, we have a bunch of utilities like: custom hooks, context providers, constants and helper functions. Feel free to add more stuff here.&lt;/p&gt;
&lt;h2&gt;All together&lt;/h2&gt;
&lt;p&gt;Last but not least a complete overview of the project structure:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;react-project
├── api
│   ├── services
│   │   ├── Job.js
│   │   ├── User.js
│   ├── auth.js
│   └── axios.js
├── components
│   ├── Job
│   │   ├── Description.js
│   │   └── Preview.js
│   └── User
│   │   ├── Card.js
│   │   ├── Create.js
│   │   └── List.js
├── i18n
│   ├── de.json
│   └── en.json
├── modules
│   ├── logger.js
│   └── session.js
├── pages
│   ├── Home
│   │   ├── components
│   │   │   ├── Dashboard.js
│   │   │   └── Welcome.js
│   │   └── index.js
│   ├── Login.js
│   └── Profile.js
├── stores
│   ├── language.js
│   └── user.js
├── tests
│   ├── language.test.js
│   └── utils.test.js
├── utils
│   ├── hooks
│   │   ├── useChat.js
│   │   ├── useOutsideAlerter.js
│   │   ├── useToast.js
│   ├── providers
│   │   ├── HomeContextProvider.js
│   │   ├── ToastContextProvider.js
│   ├── colors.js
│   ├── constants.js
│   ├── index.js
├── index.js
├── main.js
└── style.css&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;That’s it! This is how I structure my React projects. I hope this is a little help for people who don&apos;t know how to structure their React application or didn’t know how to start. Feel free to give any suggestions.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Database seeding in Node.js]]></title><description><![CDATA[In this article I'd like to talk about database seeding using Node.js and MySQL: what it is and how to implement it. You'll notice that it's…]]></description><link>https://larswaechter.dev/nodejs-database-seeding/</link><guid isPermaLink="false">https://larswaechter.dev/nodejs-database-seeding/</guid><pubDate>Sat, 21 Aug 2021 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In this article I&apos;d like to talk about &lt;a href=&quot;https://en.wikipedia.org/wiki/Database_seeding&quot;&gt;database seeding&lt;/a&gt; using Node.js and MySQL: what it is and how to implement it. You&apos;ll notice that it&apos;s actually quite easy and straightforward. For this tutorial I chose MySQL as database system but this procedure should also work with any other one. In this case there might be some small modifications necessary regarding the SQL query execution.&lt;/p&gt;
&lt;p&gt;Let&apos;s start with an explanation of database seeding. &lt;a href=&quot;https://en.wikipedia.org/wiki/Database_seeding&quot;&gt;Source&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Database seeding is the initial seeding of a database with data. Seeding a database is a process in which an initial set of data is provided to a database when it is being installed. It is especially useful when we want to populate the database with data we want to develop in future.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So our goal is to &quot;feed&quot; the database with dummy data on its initialization. This can be very helpful especially during the development process or for onboarding new employees that run the development environment (database) locally on their machine.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;First of all we create a new SQL script that includes the queries for inserting the dummy data. This script will be later executed using Node.js.&lt;/p&gt;
&lt;p&gt;The seeding script: &lt;code class=&quot;language-text&quot;&gt;./db/seeding.sql&lt;/code&gt;&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;sql&quot;&gt;&lt;pre class=&quot;language-sql&quot;&gt;&lt;code class=&quot;language-sql&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;/* Insert admin account */&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;INSERT&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;INTO&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;user&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;email&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; firstname&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; lastname&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; password&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;VALUES&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&apos;admin@email.com&apos;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&apos;John&apos;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&apos;Doe&apos;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; ?&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This SQL command inserts a new data set into the &lt;code class=&quot;language-text&quot;&gt;user&lt;/code&gt; table. The &lt;code class=&quot;language-text&quot;&gt;?&lt;/code&gt; is a placeholder that gets replaced with a variable, the initial password, when calling the script using Node.js. You can add more queries here of course.&lt;/p&gt;
&lt;p&gt;Make sure that the database tables were created before running the script otherwise it&apos;ll fail. Most &lt;a href=&quot;https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping&quot;&gt;ORMs&lt;/a&gt; take care of that.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Next, we write the Node.js script, which is required to establish a database connection and execute the SQL snippet we just created.&lt;/p&gt;
&lt;p&gt;The Node.js script: &lt;code class=&quot;language-text&quot;&gt;./db/index.js&lt;/code&gt;&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;js&quot;&gt;&lt;pre class=&quot;language-js&quot;&gt;&lt;code class=&quot;language-js&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; mysql &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;require&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;mysql2&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; fs &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;require&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;fs&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; bcrypt &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;require&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;bcryptjs&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Load .env variables&lt;/span&gt;
&lt;span class=&quot;token function&quot;&gt;require&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;dotenv&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;config&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Read SQL seed query&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; seedQuery &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; fs&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;readFileSync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;db/seed.sql&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;encoding&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;utf-8&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Connect to database&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; connection &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; mysql&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;createConnection&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;host&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; process&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;env&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;DB_HOST&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;user&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; process&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;env&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;DB_USERNAME&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;password&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; process&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;env&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;DB_PASSWORD&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;database&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; process&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;env&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token constant&quot;&gt;DB_NAME&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token literal-property property&quot;&gt;multipleStatements&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token boolean&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;// IMPORTANT&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

connection&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;connect&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Generate random password for initial admin user&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; psw &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; Math&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;toString&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;36&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;substring&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; hash &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; bcrypt&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;hashSync&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;psw&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

console&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Running SQL seed...&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;// Run seed query&lt;/span&gt;
connection&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;seedQuery&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;hash&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token parameter&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;throw&lt;/span&gt; err
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  console&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;SQL seed completed! Password for initial admin account: &quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; psw&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  connection&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;What happens here?&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Load the environment variables using &lt;code class=&quot;language-text&quot;&gt;dotenv&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Read the SQL snippet&lt;/li&gt;
&lt;li&gt;Connect to the database (MySQL)&lt;/li&gt;
&lt;li&gt;Generate a random password (hashed)&lt;/li&gt;
&lt;li&gt;Execute the SQL snippet&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;At the end the admin password is logged to the console if everything worked fine. Instead of using &lt;code class=&quot;language-text&quot;&gt;dotenv&lt;/code&gt; you can also use &lt;code class=&quot;language-text&quot;&gt;fs.readFileSync&lt;/code&gt; to load your database credentials from any other file.&lt;/p&gt;
&lt;p&gt;If you&apos;re not using MySQL you simply have to modify the database connection setup. I&apos;m sure there&apos;s a npm package for your database system that can handle this.&lt;/p&gt;
&lt;p&gt;Last but not least let&apos;s extend the &lt;code class=&quot;language-text&quot;&gt;package.json&lt;/code&gt; scripts to simplify the execution of the Node script.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;json&quot;&gt;&lt;pre class=&quot;language-json&quot;&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;scripts&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// ...&lt;/span&gt;
    &lt;span class=&quot;token property&quot;&gt;&quot;seed&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;node db/index.js&quot;&lt;/span&gt;
    &lt;span class=&quot;token comment&quot;&gt;// ...&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Now you can run the database seeding with a single command from the terminal: &lt;code class=&quot;language-text&quot;&gt;npm run seed&lt;/code&gt;. That&apos;s it! Your database is filled with dummy data and you can focus on the important stuff.&lt;/p&gt;
&lt;p&gt;There&apos;s also a GitHub repository available including an example application that makes use of database seeding. &lt;a href=&quot;https://github.com/larswaechter/expressjs-api&quot;&gt;Have a look&lt;/a&gt;.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[A decent introduction to Gradient Descent in Python]]></title><description><![CDATA[Gradient Descent is a fundamental element in today’s machine learning algorithms. We use Gradient Descent to update the parameters of a…]]></description><link>https://larswaechter.dev/gradient-descent-introduction-python/</link><guid isPermaLink="false">https://larswaechter.dev/gradient-descent-introduction-python/</guid><pubDate>Mon, 22 Feb 2021 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Gradient Descent is a fundamental element in today’s machine learning algorithms. We use Gradient Descent to update the parameters of a machine learning model and try to optimize it by that. The clue is that the model updates those parameters on its own. This leads to the model making better predictions.&lt;/p&gt;
&lt;p&gt;In the following article we’ll dive into Gradient Descent, and I’ll explain it with the help of an example scenario which we’ll solve using Supervised Learning and Python. We won’t use any ML framework like PyTorch or TensorFlow for that. The complete source code is available at &lt;a href=&quot;https://gist.github.com/larswaechter/c2df0bc9b0f15c64220eb5699b25ddf1&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Supervised Learning&lt;/h3&gt;
&lt;p&gt;Let’s have a look on Wikipedia&apos;s definition for Supervised Learning.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs. (Source: &lt;a href=&quot;https://en.wikipedia.org/wiki/Supervised_learning&quot;&gt;Wikipedia&lt;/a&gt;)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Sounds confusing, but it’s quite easy actually. An example might be good.&lt;/p&gt;
&lt;p&gt;Let’s say you want to make a computer tell you whether a photo is the one of a cat or not. Before the computer is able to tell you whether it’s a cat or not, you have to teach the computer how a photo of a cat looks like. For that, you feed the computer with many photos (input) and the information whether the photo is that one of a cat or not (output). This process is called &lt;strong&gt;training phase&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;When the training phase is completed, you can show your computer a photo of a cat that it has not seen before, and it tells you whether it’s the one of a cat or not. &lt;strong&gt;Artificial Intelligence&lt;/strong&gt;, amazing! For that, your computer uses the function that it just learned before.&lt;/p&gt;
&lt;p&gt;This cat example is a &lt;strong&gt;classification problem&lt;/strong&gt;. Classification is the task of predicting a discrete class &lt;strong&gt;label&lt;/strong&gt; (“cat” and “no cat”). The other type of problem is called &lt;strong&gt;Regression&lt;/strong&gt;, which is the task of predicting a numerical or continuous value. The example below is such a Regression problem.&lt;/p&gt;
&lt;h3&gt;The Scenario&lt;/h3&gt;
&lt;p&gt;Imagine we’re the owner of an amusement park. For organizational reasons we want to know, or at least predict, the number of visitors for the next day. Fortunately, we took some notes about the number of visitors based on the weather in the last season.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 313px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/62ac4faedfc4680ca8737918a0272e4e/80977/table.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 88.60759493670886%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAIAAADUsmlHAAAACXBIWXMAAAsTAAALEwEAmpwYAAABbklEQVR42n2T6ZKDIBCEff9H2+yZuBGMBlDxNiqeiMcSN1Vbm0j6F1XUR8/0DFochwBCz/N8nzrUj+M4SzPGyiiK+p5jhCzrRIOwzPMkTrJLTgihlIZB0PW9RggG0EySJMvSOEnzvGAlkxdt2/K+NwwDE3LJi6aum7ZlrJKPZlmWFwXnXENnxKpmWZZ5npf/GkeBMeZ8WG+XR2nQAJe8lKdpmuY/rbAYbMvuuv736TtdYQCMsqrvndezLNu27UGMi0IaQkh2sw3zzjge+SA2m7rCMr26aTZhwTlC5yhJlbBpmqxWBTZAAPwgUsKu6zSPZd/sR8s8eTRQwjKSesN5XvMXu5cdwkRdNgRFWSmcp/fXN0ycJzBkj6NaNY3isN9j4j4JDBaMbacthm9dJ64alsPYcr7Bun4gjhqW21spNkwMHBhHx/OVsPxxJas2neVuf31+POv56qxckmtgjkuVMPXcpu22055G27LCKFbBP8VmFRj4Jn9BAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Visitors&quot;
        title=&quot;&quot;
        src=&quot;/static/62ac4faedfc4680ca8737918a0272e4e/80977/table.png&quot;
        srcset=&quot;/static/62ac4faedfc4680ca8737918a0272e4e/c26ae/table.png 158w,
/static/62ac4faedfc4680ca8737918a0272e4e/80977/table.png 313w&quot;
        sizes=&quot;(max-width: 313px) 100vw, 313px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Regarding Wikipedia’s definition of Supervised Learning those values are the so-called “example input-output pairs”. The temperatures are the “input” and the number of visitors are the “output”.&lt;/p&gt;
&lt;p&gt;For example, when there was 30 °C outside our park had 620 visitors. These notes are the training data for our ML model. The values in the left column are called features. The ones in the right column are called labels.&lt;/p&gt;
&lt;p&gt;Last but not least the noted data put in a beautiful diagram.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/316e6e243d85c9d20bb3a04a45528b4f/2cefc/weather.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 55.06329113924051%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAIAAADwazoUAAAACXBIWXMAAAsTAAALEwEAmpwYAAAA4UlEQVR42o1S7W7DIAzs+7/k+icaBpfihLSdhM0MTtqs6xeyTpbx+Xwku1prKWWezzn/fB4iyqu7BlVSys6R9wTwPrwfmWUhM5eUphBGxFHxWbiVjDiJrGQRJpoBWodO/R9hTbTn21EI06KsMxDDa+VG82S32NsWZWYehiHGxzTsCE2T8Frcrq2en629yEKLTfEPWT1na324852d+wdTz7pYCO1r9fHUBUmfx7V6qxhaciPr0Z8kpdnieMyKhzjFmPEwEp20Ymi36rEUvpFtkvSjLiwHgP3+63I5X+tbrLX+ApJKcJpRg18DAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Weather&quot;
        title=&quot;&quot;
        src=&quot;/static/316e6e243d85c9d20bb3a04a45528b4f/f058b/weather.png&quot;
        srcset=&quot;/static/316e6e243d85c9d20bb3a04a45528b4f/c26ae/weather.png 158w,
/static/316e6e243d85c9d20bb3a04a45528b4f/6bdcf/weather.png 315w,
/static/316e6e243d85c9d20bb3a04a45528b4f/f058b/weather.png 630w,
/static/316e6e243d85c9d20bb3a04a45528b4f/40601/weather.png 945w,
/static/316e6e243d85c9d20bb3a04a45528b4f/78612/weather.png 1260w,
/static/316e6e243d85c9d20bb3a04a45528b4f/2cefc/weather.png 1400w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Back to our question. How many visitors can we expect to see in our park tomorrow when know that there will be 33 °C at this day? As you can see we have no information about the number of visitors for 33 °C in our table. We have to predict the value. Let’s do it!&lt;/p&gt;
&lt;h3&gt;Linear Regression&lt;/h3&gt;
&lt;p&gt;Linear regression helps us find the “&lt;strong&gt;best fitting straight line&lt;/strong&gt;” that we can place inside the data in of diagram. When we found this line, we can use it to predict other values that are not part of our records, like tomorrow’s number of visitors when there are 33 °C outside.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/916c583c02c2b5aebfbb9eadb023f2d4/2cefc/linear_function.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 55.06329113924051%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAIAAADwazoUAAAACXBIWXMAAAsTAAALEwEAmpwYAAAA5UlEQVR42o2RiQ6DIAyGff/HNHHQiilFmS7hWIV4bdlB/hSFfj1ok3OOMXi/TNPjH3m/KiXhcrOanJi91ozIAN+EwBqsAkqFbmpmaydEZ4zr+4/SwErbmyZjxiNzSpH5NwzINyDhC1wyyzYMpmYWD7HvAnBKk0bbYw20wTHGruuIRjn9lFlKFdXQxW08eg7hW8+qvBBICdvJBd57fiNHKVWeVz7Otxf4NCq3zmMb2FqtsvsIdytuZzh7PzPfq6z1zLMZXG/Ej+RX5NxMNG239xDiAddILxYR27ZdliWVJU+bTivn/ARW7XB0htR+FAAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Linear Function&quot;
        title=&quot;&quot;
        src=&quot;/static/916c583c02c2b5aebfbb9eadb023f2d4/f058b/linear_function.png&quot;
        srcset=&quot;/static/916c583c02c2b5aebfbb9eadb023f2d4/c26ae/linear_function.png 158w,
/static/916c583c02c2b5aebfbb9eadb023f2d4/6bdcf/linear_function.png 315w,
/static/916c583c02c2b5aebfbb9eadb023f2d4/f058b/linear_function.png 630w,
/static/916c583c02c2b5aebfbb9eadb023f2d4/40601/linear_function.png 945w,
/static/916c583c02c2b5aebfbb9eadb023f2d4/78612/linear_function.png 1260w,
/static/916c583c02c2b5aebfbb9eadb023f2d4/2cefc/linear_function.png 1400w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;You might remember from school that a &lt;strong&gt;linear function&lt;/strong&gt; is described as:&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 410px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/5148467456826b81c35691e042cff885/d68e4/linear_equation.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 18.354430379746837%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAECAYAAACOXx+WAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAi0lEQVR42m3PQQsBQRTA8WetJQeLVYpScnEiDpSDnFak5CP4/l/Cf+p/2LJTv2nevNfMexERGbrxvzrI0Vdu3dA4vJv6Rlp12q5eFthhj7UFZ/O15wpvrMwvccHY+JG2L0b+esARGwtS/MQJL3Mf9Ox2izsWzQ5vBlnL2Gm8EgO7mGPmqOGjk0Z9+QOY3webJLQ9DQAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Linear equation&quot;
        title=&quot;&quot;
        src=&quot;/static/5148467456826b81c35691e042cff885/d68e4/linear_equation.png&quot;
        srcset=&quot;/static/5148467456826b81c35691e042cff885/c26ae/linear_equation.png 158w,
/static/5148467456826b81c35691e042cff885/6bdcf/linear_equation.png 315w,
/static/5148467456826b81c35691e042cff885/d68e4/linear_equation.png 410w&quot;
        sizes=&quot;(max-width: 410px) 100vw, 410px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; is the output (visitors) also known as &lt;code class=&quot;language-text&quot;&gt;f(x)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;m&lt;/code&gt; is the slope&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; is the explanatory variable (weather)&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; is the bias&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This equation might be also familiar to you with some other variable names. Using this equation, which represents our line, we can predict the output (&lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt;) for any given input (&lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;) later on.&lt;/p&gt;
&lt;p&gt;In our scenario we’d like to predict the number of visitors (&lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt;) when there are 33 °C (&lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;) outside, so it is &lt;code class=&quot;language-text&quot;&gt;f(33) = y = m * 33 + b&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For this, we have to choose values for &lt;code class=&quot;language-text&quot;&gt;m&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; wisely. Fortunately, the computer will do this for us. They are the learnable parameters inside the model.&lt;/p&gt;
&lt;p&gt;Well, now that we know this equation is used to predict values. Let’s implement this one in Python:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# The model&apos;s output (prediction)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; X &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; w &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Note that we changed the name of the variable &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; to &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;, which means &lt;strong&gt;weight&lt;/strong&gt;. Our goal is that this &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; function tells us the output for any given input variable &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt;. For that, we need to assign values to &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Before we find these values let’s look for a way to measure the quality of our new function. A so-called &lt;strong&gt;loss function&lt;/strong&gt; can do this for us.&lt;/p&gt;
&lt;h3&gt;Loss Function&lt;/h3&gt;
&lt;p&gt;The loss function measures how far a model’s predictions are from its label. In other words: it determines how &lt;strong&gt;good&lt;/strong&gt; or &lt;strong&gt;bad&lt;/strong&gt; our model is.&lt;/p&gt;
&lt;p&gt;Since we’re using linear regression, we don’t have to invent our own loss function. There is already one we can use. This one is called &lt;a href=&quot;https://en.wikipedia.org/wiki/Mean_squared_error&quot;&gt;mean squared error&lt;/a&gt; (MSE).&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/7766320b6558fabb1c0b10ee10709942/3f3b9/mse.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 26.58227848101266%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAFCAYAAABFA8wzAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAl0lEQVR42nXQuwrCQBCF4dmNEpMUBqNFLiIKYqGFNhGs7Hz/N/JM+JXgJfCFYW9zds3Mgn1/r7FSKkllL8vRfPhRR//V0sladtJKwmSFXq6ykrksZCoTpNgaC89ylDsH+4aGRQWHXEjhzR+knTF3Y5+HGTpEYsdRbWzyrhuaniRjPGdNwi0K6vfdwwcjQUniA+nsz/sN9RPc8QXxwQWxzgAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Mean squared error&quot;
        title=&quot;&quot;
        src=&quot;/static/7766320b6558fabb1c0b10ee10709942/f058b/mse.png&quot;
        srcset=&quot;/static/7766320b6558fabb1c0b10ee10709942/c26ae/mse.png 158w,
/static/7766320b6558fabb1c0b10ee10709942/6bdcf/mse.png 315w,
/static/7766320b6558fabb1c0b10ee10709942/f058b/mse.png 630w,
/static/7766320b6558fabb1c0b10ee10709942/3f3b9/mse.png 870w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The function includes four variables &lt;code class=&quot;language-text&quot;&gt;n&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;i&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;y&apos;&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;n&lt;/code&gt; is the number of input-output pairs we have (14)&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;i&lt;/code&gt; is the index for the current pair from our training data we’re looking at&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;y&apos;&lt;/code&gt; is the predicted value from our model which we’ll get from the &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; we declared at the beginning&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; is the actual output value that we got from our training data label&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For each value from our training data this function calculates the &lt;strong&gt;difference&lt;/strong&gt; between the label and the predicted value from &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; and squares the result. All these results are summed up and at the end the mean is taken.&lt;/p&gt;
&lt;p&gt;Now we can use the loss function to determine how good or bad our model is. The smaller the output value of the function is the better is our model, because only few errors were made in this case. A high value implies a worse model on the other hand. So, our goal is to &lt;strong&gt;minimize&lt;/strong&gt; its output because we want as few errors as possible.&lt;/p&gt;
&lt;p&gt;Let’s implement the MSE in Python.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# Calculating the loss using MSE&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here we have four arguments:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; is an Numpy array containing temperaturs (features)&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-text&quot;&gt;Y&lt;/code&gt; is an Numpy array containing number of visitors (labels)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; are used for the &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; function, whose output is equivalent to &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; in the MSE equation. Since &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;Y&lt;/code&gt; are both Numpy Arrays the part &lt;code class=&quot;language-text&quot;&gt;(predict(X, w, b) - Y) ** 2&lt;/code&gt; is executed for each single array element.&lt;/p&gt;
&lt;p&gt;Now we are able to measure how good or bad our model is. Keep in mind that we try to find good fitting values for &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; inside &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For now, let’s measure the loss of our model using the &lt;code class=&quot;language-text&quot;&gt;loss()&lt;/code&gt; function with some random numbers for the weight &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;. To make it easier we will set &lt;code class=&quot;language-text&quot;&gt;b = 0&lt;/code&gt;, so the prediction only depends on &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/d21696a13596831d7e233af407233b85/2cefc/loss_no_bias.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 55.06329113924051%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAIAAADwazoUAAAACXBIWXMAAAsTAAALEwEAmpwYAAAA7klEQVR42n1Ra2+DMAzk//+/fd2kQUjIg7zooIKwHXGHaFIVHdHl7LMNblLaY1xCmJ2bQN7DWuTMxLctNXiHwQNtqzh3xGtIGfreIgeElGVZm3VNuEsZhXCMGaVivpaA3nV6GJxSD+V+X4/O1zBK1H4oQljG9DV0mL0PMOSMQMMj4yx/AjoN/2QeR5vNkTr0/VgMTxNxbouJirEfqTAD4EbfcMKJivW3vDCTH32+W/nx9dl1qu5ZmGkZ18VEnIwbmSu+XB6ZN+9/AOduJ7EWfDYGf85lEcr0H5pCOMhh3vf9Nz9XQlxrbE6QklKqyR+DWWneBQ87CAAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Loss without bias&quot;
        title=&quot;&quot;
        src=&quot;/static/d21696a13596831d7e233af407233b85/f058b/loss_no_bias.png&quot;
        srcset=&quot;/static/d21696a13596831d7e233af407233b85/c26ae/loss_no_bias.png 158w,
/static/d21696a13596831d7e233af407233b85/6bdcf/loss_no_bias.png 315w,
/static/d21696a13596831d7e233af407233b85/f058b/loss_no_bias.png 630w,
/static/d21696a13596831d7e233af407233b85/40601/loss_no_bias.png 945w,
/static/d21696a13596831d7e233af407233b85/78612/loss_no_bias.png 1260w,
/static/d21696a13596831d7e233af407233b85/2cefc/loss_no_bias.png 1400w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;You can see, the loss of model is the smallest when we set &lt;code class=&quot;language-text&quot;&gt;w = ~14&lt;/code&gt;. This position is also called &lt;strong&gt;minimum&lt;/strong&gt;. Humans can identify this spot quite easily when they see the graph. A computer on the other hand can’t do so. Moreover, you don’t always know which number the weight &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; might be close to. What if the minimum had been at &lt;code class=&quot;language-text&quot;&gt;w = 3000&lt;/code&gt;? The scaling on the x-axis would be too small to identify the minimum visually.&lt;/p&gt;
&lt;p&gt;So we need to find a way to tell the computer how to find this spot. For that, &lt;strong&gt;Gradient Descent&lt;/strong&gt; is the right choice.&lt;/p&gt;
&lt;h3&gt;Gradient Descent&lt;/h3&gt;
&lt;p&gt;Gradient Descent is an algorithm for finding a &lt;strong&gt;local minimum&lt;/strong&gt; of a function. In this case, we try to find the minimum of our loss function because at this position the model makes the best &lt;strong&gt;predictions&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In Gradient Descent we choose a random starting point in our graph. From this position we’ll take many steps towards the minimum. But how do we know in which direction (left or right) to go and how big a single step should be?&lt;/p&gt;
&lt;h4&gt;Gradient 1&lt;/h4&gt;
&lt;p&gt;For this, we use the so-called &lt;strong&gt;Gradient&lt;/strong&gt;. The Gradient can actually have two meanings depending on the number of parameters of a function.&lt;/p&gt;
&lt;p&gt;In both cases you can say that the Gradient of a function is calculated with the help of all its &lt;strong&gt;partial derivatives&lt;/strong&gt;. But first, let’s talk about what the Gradient is.&lt;/p&gt;
&lt;h5&gt;One parameter: f(x)&lt;/h5&gt;
&lt;p&gt;If we have a function like &lt;code class=&quot;language-text&quot;&gt;f(x) = 2x+1&lt;/code&gt; that only depends on one parameter (&lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;) the gradient is the &lt;strong&gt;degree of steepness&lt;/strong&gt; of the graph at any given point, also known as &lt;strong&gt;slope&lt;/strong&gt;. Time for an example.&lt;/p&gt;
&lt;p&gt;This is the graph of the random chosen function &lt;code class=&quot;language-text&quot;&gt;f(x) = 2x+1&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/77c67d4b2ec675f68c9cf210d6d0d503/0b533/gradient_example_1.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABs0lEQVR42pVU7ZKCMAzk/V/KZ3DEUQEd/ykgLf2gtIXiLdSreKfnueN00iRLtknGKI7LLGsOB1kUsqqEENwD1uVyyfNcCAlnUXBKuY8yxowxcRxHjAljnNadtd0czjkpJfKGYYxy3vX9LWStvV6vaZpG+BC81hr85kASilBKnetRSal7gtYa5CRJQOZ939tfgFOM4NY6xuxU7wbwQ+WX5Ol5tZROqc/JqEspE8LNmR+Qz2c09jUZ/URvcA8Bf8JZ1zzPORpmHnFvGD7vK8/nhBs4ZSkJ4cMwdI+4V66qyi8DzrIscRZFQUiV5+XpRNHtuq7pBIRw+nw8drlcRoQQyGiaRk1oJrRtQ6kihDWNRBTb4kP+xBViN5tNBAvC+hmmR6JbA1LxKDdhngDlkJ1l2ZNu48nYCq17KQV0hZV8Pyqkte1IhtPv9l/kMKrvlTZ+k+GEZrQnEJ6Mal45lIXRdf+o/IPM+ciH4TfszZsxRtyhBHKU0pTqSZeGE98FOUgNaNsW5N1udx8VxqHUOCQ/F4zn/ajwb5KmWZom222yWiUwPKBqvV7D2O/3ySNQ83g8LhaLL5CCerGA9NbjAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 1&quot;
        title=&quot;&quot;
        src=&quot;/static/77c67d4b2ec675f68c9cf210d6d0d503/0b533/gradient_example_1.png&quot;
        srcset=&quot;/static/77c67d4b2ec675f68c9cf210d6d0d503/c26ae/gradient_example_1.png 158w,
/static/77c67d4b2ec675f68c9cf210d6d0d503/6bdcf/gradient_example_1.png 315w,
/static/77c67d4b2ec675f68c9cf210d6d0d503/0b533/gradient_example_1.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Let’s calculate the Gradient for a given point. For this, we firstly calculate the partial derivatives with respect to &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; since this is our only parameter.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/760890208b585040cf549f469c43782a/87a80/gradient_example_1_equation.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 8.227848101265824%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAACCAYAAABYBvyLAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAUUlEQVR42i3MOQqAQBBE0QpEFFxxXFCQAcXA3PtfzT9aDS/o6qYk6UCHAZX3ByV657v+GZHhwoQNEbN/U89X0HpJhStuFFicB+S+NTgtWnBevxZ6A3naFRgEAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 1 Equation&quot;
        title=&quot;&quot;
        src=&quot;/static/760890208b585040cf549f469c43782a/f058b/gradient_example_1_equation.png&quot;
        srcset=&quot;/static/760890208b585040cf549f469c43782a/c26ae/gradient_example_1_equation.png 158w,
/static/760890208b585040cf549f469c43782a/6bdcf/gradient_example_1_equation.png 315w,
/static/760890208b585040cf549f469c43782a/f058b/gradient_example_1_equation.png 630w,
/static/760890208b585040cf549f469c43782a/40601/gradient_example_1_equation.png 945w,
/static/760890208b585040cf549f469c43782a/87a80/gradient_example_1_equation.png 973w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The result is &lt;code class=&quot;language-text&quot;&gt;2&lt;/code&gt;, what is exactly the slope of the function &lt;code class=&quot;language-text&quot;&gt;f(x)&lt;/code&gt;. Since it’s a linear function, the Gradient is equal to &lt;code class=&quot;language-text&quot;&gt;2&lt;/code&gt; at any given point &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;What if we have non-linear function like &lt;code class=&quot;language-text&quot;&gt;f(x) = (x-3)^2+2&lt;/code&gt;? In this case its graph looks like the following.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/ba8ff38c953a81c9de46a7d8ba1e58c8/0b533/gradient_example_2.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABsElEQVR42p2UgY6qMBBF/f+f8h9cjVExMetmRbZCaQultOAeqfJ8a/Rt3k1Th5m5M9cZwuTt7StJqv3eZJl5fzcfH+ZwMHmujdH7vcjwGqNu0FqlqZKydM7N5/NJWWrnuqbxbesBdzx93wlRZVnedcF7jg/Bk6YU0fZ8Pm82m4lSJd62dfcHhNAKYT4/vwbPxeW9M6ZVCruBvF6vIatA4gNwIgqRSIgeZMG09lJq7PyUTOhwkCF0o1PKNqr4N5lJpSmz6ejJqetLZ4xfkZmtENKYKxkm/L/IZVkySZ4jx92Ac9hOqXWw1jWNk/Ka0zS3gWmCQ2d/Q7QH2YbS/GfWwxkK+tjp2jnPcyFEmqbcx+PxdDrxYmBzF0VBaykLnHle4IzJgKKz2exCRkZVVXVdx3s0yMAgigRr6zGHR3Qtl8sJVt/34QE4SaVzN+A+hHJkJ0nyetoaXeMgRvxyzybu4il5XNUP4KQzs4lbvA/9WdXrzlLK/5RNZ5b0iiyHl715AE7qIpuZR6kjrLWQV6vV01WxHpKYCFWeroqvCT/rB6BqsVhgbLfbHyF67na76XT6DTGDejMq25eLAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 2&quot;
        title=&quot;&quot;
        src=&quot;/static/ba8ff38c953a81c9de46a7d8ba1e58c8/0b533/gradient_example_2.png&quot;
        srcset=&quot;/static/ba8ff38c953a81c9de46a7d8ba1e58c8/c26ae/gradient_example_2.png 158w,
/static/ba8ff38c953a81c9de46a7d8ba1e58c8/6bdcf/gradient_example_2.png 315w,
/static/ba8ff38c953a81c9de46a7d8ba1e58c8/0b533/gradient_example_2.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;You might notice that this graph is similar to the one of our loss function above. Now, we calculate the Gradient for any point in this graph. Again, we firstly calculate the partial derivatives with respect to &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; since this is our only parameter.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/4aa30d5bea07d74364e8e4fc102e762c/2cefc/gradient_example_2_equation.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 6.329113924050632%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAABCAYAAADeko4lAAAACXBIWXMAAAsTAAALEwEAmpwYAAAANUlEQVR42mNgYGBQAmIxIOYDYkEgFgZiNiCWgmJeIJYAYi4gFgJiaSgfxOYBYmUgFoDqUQEAPUwBlMKSijwAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 2 Equation&quot;
        title=&quot;&quot;
        src=&quot;/static/4aa30d5bea07d74364e8e4fc102e762c/f058b/gradient_example_2_equation.png&quot;
        srcset=&quot;/static/4aa30d5bea07d74364e8e4fc102e762c/c26ae/gradient_example_2_equation.png 158w,
/static/4aa30d5bea07d74364e8e4fc102e762c/6bdcf/gradient_example_2_equation.png 315w,
/static/4aa30d5bea07d74364e8e4fc102e762c/f058b/gradient_example_2_equation.png 630w,
/static/4aa30d5bea07d74364e8e4fc102e762c/40601/gradient_example_2_equation.png 945w,
/static/4aa30d5bea07d74364e8e4fc102e762c/78612/gradient_example_2_equation.png 1260w,
/static/4aa30d5bea07d74364e8e4fc102e762c/2cefc/gradient_example_2_equation.png 1400w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see the slope is not the same for each point. Here, it depends on &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;. Let’s say we’re standing at &lt;code class=&quot;language-text&quot;&gt;x = 6&lt;/code&gt; in our graph. What is the Gradient aka slope at this spot? In this case it’s &lt;code class=&quot;language-text&quot;&gt;2*(6–3) = 6&lt;/code&gt;. The red line is the tangent with a slope of &lt;code class=&quot;language-text&quot;&gt;6&lt;/code&gt; at the given point &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/86b739ad4194de67132287a60ca6f467/0b533/gradient_example_2_2.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAACBUlEQVR42o1U227iMBDN//8Uz/uKoJSAWCQouTmOb7HjS0KPEwJt0XYZRfZoPGfmeI4hWf05HpbVeU+qCzttq9NHm2WKUqmUPJ1IWZZKKTGblLL4mzPGrLWr1SqR+0O4FL6oetkGUrvQO+fxDUNPSFuWtO+D9/h8CMEZa6hwzl2v191ul6Ba6HvnvXXOesDiDkMmIepyqcZIDKGCrFuWCxcswGmaJoJzlMWh+27ow7nMcwEKUwRgTUSnjH10FiLyeTIEcZRlLIQbGOxE1oy07P/BmFSec2t7MIttlREFh/MSWEpBCFNqAgdBtabC98F2M5hzjkna+c52NgRHdTgGagzyPcu5Mxo5XdfdBgbpps5+tskfaSuUxp2F8EIG2zA/Hj1oU0oJIXmeYy2Koq5rPAz4WJumQWvWNDWlDanr85k2DSEVTlF0uVxGMGi0bau1nta7gww4OFVta6TQlGpjEAEj8NpsNgm8YRjCkyEIPDr3MCRgrng5eG4hvjbQ3u/3v09bgtdtEIzFhzRO5EWd48AwOm9MBM9pD/Bdqh+GIDpjNlFDrZ0Qdk57SPV7Z/z6YmcOhc3E+VXa6Azl4o0Bni/8DYza06P5YQiiLtTVUlrGui85xhiAt9vtP6WCQEjCRHDhwZhJpMkeUuHfBFv6ZGC1Xq+xHd7e0vd3OPcj9Dwej4vF4hM1p3f5CStpPAAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 2 Slope&quot;
        title=&quot;&quot;
        src=&quot;/static/86b739ad4194de67132287a60ca6f467/0b533/gradient_example_2_2.png&quot;
        srcset=&quot;/static/86b739ad4194de67132287a60ca6f467/c26ae/gradient_example_2_2.png 158w,
/static/86b739ad4194de67132287a60ca6f467/6bdcf/gradient_example_2_2.png 315w,
/static/86b739ad4194de67132287a60ca6f467/0b533/gradient_example_2_2.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Another example. Let’s say we’re right at &lt;code class=&quot;language-text&quot;&gt;x = 4&lt;/code&gt; in the same graph. Here, the Gradient aka slope is &lt;code class=&quot;language-text&quot;&gt;2*(4-3) = 2&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/4b915ee6bcf061d6eea27ec17487ce1b/0b533/gradient_example_3.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAACDUlEQVR42o1T25KiMBDl/3/K5615c3QsUaes1RKEBHIj5Ip7AMWh5ranYmySPunO6U6y+nN8fy3PB1pm/O87O51VlqmqkkrJ04kURaGUEg9IKfJcMMattauXl0TuD+FS+IJEpUOjnQ/OeYyui4Q0RVHFGLzH8CF4Y7wQ3nl/83739pbgtBAjvq1zGMOEc20IjhB1uZTjMlbgopQV0ttG3YxJd7tEcI5jsenmCCFwLpEkUhhX4IWwbWMdq2+3264nCwE/9wlYxFaWsRDitMgYftxq/TsZSuU5tIm+v6bTbRClDBqh3e9kaEsIU2ogBy8rrWsJwxpzJ3POoaR93Nk+gMWhOlxK3xqHeOTEfe/gzEBO0zSRUHuI7B8Y7SFtxXs5O/B5LrRCCfokcPQ9clVVhJA8zzFfr1dKKRoDNua6rhGacUYvWV2UtKajM4BDl8tlT0YaTdNorcd5MuABwyjVUKo/+CAj5LXZbBJYXdeFT+hihCu6IEoZ51u4FNLe7/ffq+09+rs6n/ueHISY8Lzzd2Qohmx5WfY9Pd96kqdSzQCy1rIsCaVjFT9uPkv1deTh+UAOxthUv/9OG+W1FndG5X4is77Z+6a5A1lxbqR0Q4ehpNB8THVC27Ygb7fbeanw8KGzMTAAOEERHA3761KtViv84fZ43P28XKbp+LVbr9cwDodDOgdiHo/HxWLxDyL3d+L7MggdAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 3&quot;
        title=&quot;&quot;
        src=&quot;/static/4b915ee6bcf061d6eea27ec17487ce1b/0b533/gradient_example_3.png&quot;
        srcset=&quot;/static/4b915ee6bcf061d6eea27ec17487ce1b/c26ae/gradient_example_3.png 158w,
/static/4b915ee6bcf061d6eea27ec17487ce1b/6bdcf/gradient_example_3.png 315w,
/static/4b915ee6bcf061d6eea27ec17487ce1b/0b533/gradient_example_3.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The important thing here is that the Gradient &lt;strong&gt;decreases&lt;/strong&gt; more and more the closer we’re at the graph’s minimum. Compare the slope of the upper two graphs at our example points. The second one has a smaller slope because the point is closer to the minimum.&lt;/p&gt;
&lt;p&gt;At the graphs minimum, where &lt;code class=&quot;language-text&quot;&gt;x = 3&lt;/code&gt;, the Gradient is &lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt;. There’s no slope at all at this position as the red tangent shows you.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/3bee08740a6ec05d37c81f44b9a90df8/0b533/gradient_example_4.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB4klEQVR42p1U226bQBDl/3/Kz33IS2rUGOzWSoiB9YL3CnvFOUCNrNC4VQ8jGJ257syKZPvt+PP7ufjFyFm/vqqiUGWp2lYqJd/eKCFEKSVukFJUlWCMW2u3220i94d4Io4rF6J33t1kGCKlmpA2xuA9xIfgjfFCwOqu12ue5wmyhRjdCLsIEIKjVJ1O54kZKe+tUk4I6AbBWZYlgnOkdSuEEDiXaBItzAy8ENn3Y6pbZSHg98dgmMqShRAXkjE3d/H3YEyqqjCbiJqQrhsrQ7kLntu29pOAlIJTypQKMEOEsJ0eFWvGM+c4M5fSx2jn5JjJTUCOm8Gjh9564zzDnMNoMtO0M1SWlIZpiB5ZJpl1kIpSXtdB60spaQGf3w6W86u1eZombV3TsqxwIcqyLoqmqsj7O3RSFBdCRNuyM6FV1dQE5OwMwXmen56S9nIx1uqu6/p+fi8KFwLKZNW96RcfpTWuxo+XlwTdDcMQVgAJZ+wiTrg3YSA4836/f7QqKWXbtn7Cvekf96w454+CZ7NdASQqU0qhzwELjFnu9sPKjLH/bBuVm6Z5FMymy25WAIm8aBszn1td0Pc9gne73ZerwnrghIkgy5erwt8En2wFdJWmKZTD4fDJhJrH43Gz2XwANr938D1MkgwAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Example 4&quot;
        title=&quot;&quot;
        src=&quot;/static/3bee08740a6ec05d37c81f44b9a90df8/0b533/gradient_example_4.png&quot;
        srcset=&quot;/static/3bee08740a6ec05d37c81f44b9a90df8/c26ae/gradient_example_4.png 158w,
/static/3bee08740a6ec05d37c81f44b9a90df8/6bdcf/gradient_example_4.png 315w,
/static/3bee08740a6ec05d37c81f44b9a90df8/0b533/gradient_example_4.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;So, in general we can say that the Gradient tells us whether we are far away from the graph’s minimum or not. The smaller the Gradient is the closer we are to the minimum.&lt;/p&gt;
&lt;p&gt;Okay, but how does that help us? With the help of the Gradient we can minimize the output of our loss function. That’s what our goal is, we want to minimize the loss.&lt;/p&gt;
&lt;p&gt;Let’s say the above graph is the course of our loss function where &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; is the loss and &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; is the weight. We want to find the value of &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; where &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; is the smallest since &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; is the loss, and we want a minimal loss in our model to make better predictions. In the scenario above, that would be at position &lt;code class=&quot;language-text&quot;&gt;x = 3&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;But how do we find this spot &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;? That’s where the Gradient Descent algorithm comes into play.&lt;/p&gt;
&lt;h4&gt;Gradient 2&lt;/h4&gt;
&lt;p&gt;In Gradient Descent we set our &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; (weight) to a random initial value. Let’s say we set &lt;code class=&quot;language-text&quot;&gt;x = 6&lt;/code&gt;. That’s our starting point. In practice this value might be &lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt;. Our function is the same as above.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/83c1b8040daa4b9b30aeb746fd6d93fb/0b533/gradient_descent_1.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABr0lEQVR42p2UjY6iQBCEff+X8h1cjUExMTG7Io4wfwIzDLifjHLeGr3NVSbY1nR1l93EycfHMU3Pu509Hm2S2P3efn4aY7QxdrcTeZ5ba/Ud8FmmpVTOufl8PlHKONc1TQu8vx3Q950Q5zwvui60LacNoSXNGBL85XJZr9cTrRWs9+7xgBC8EPbr6zgwfmBcUfg8p3aDeLVaIdaBxCdAYgqTWIgMzpTyVXUtNXZ+KeZqv5chdCMppY8u/i1mUlnGbDp6cuip9TX4lZjZCiGtvYlRov9LrJRiknyPGncH5LAdZUyoa9c0TspbTtPcB8ZOY+f2jhgPti2l+c1aU6gdCrax061zURRCiCzLeB4Oh9PpxItBzLMsS1pLWUIWRQkZkwFFZ7PZVYyN8/lcVVV8jgEZBNxioa6rMYev+FoulxOivu/DEyBJpXM34PEK59hO0/T9tA2+xkGM+OWebdzFS/G4qh+ApDOziVt8vPqzqvedpZT/aZvOLOmdWA4ve/MESOpim5lHqyPqukacJMnLVbEekpgIVV6uin8TPlZPwNVisSDYbDY/rui53W6n0+k3uCR6FrVJ2ZkAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Descent 1&quot;
        title=&quot;&quot;
        src=&quot;/static/83c1b8040daa4b9b30aeb746fd6d93fb/0b533/gradient_descent_1.png&quot;
        srcset=&quot;/static/83c1b8040daa4b9b30aeb746fd6d93fb/c26ae/gradient_descent_1.png 158w,
/static/83c1b8040daa4b9b30aeb746fd6d93fb/6bdcf/gradient_descent_1.png 315w,
/static/83c1b8040daa4b9b30aeb746fd6d93fb/0b533/gradient_descent_1.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;From there on, we calculate the Gradient for this given starting position &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;. Afterwards, we take a small step leftwards (because we want to reach the minimum) depending on the Gradient’s size.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/ee38bb908faf9efa2b0413d6e41348a9/0b533/gradient_descent_2.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABf0lEQVR42pVT2XKDMAzk//8ueUkfQ6hNCZcP4puZrnHjCbQh6Q6jkWWtJEuiOB7PH6emvLRNM5xODSF9VfWcC4CQlhAKhd8hpahpz1jUYS8gvQ/OOe+8XSRECGGeA2M38ln7FYIQBrdRCwFkDs0ucM7eFee94/x2Kam1JhnhJYSl5yE4k3xW5IxElvKGypHmh+zspHxPOsNZvN4hA0qpsqxxytbuKtnhYJRKHntkrRWl18UzflpbSiY79Cnc68xfXw3nOjbROSm0UsbPIfsU6Dj65tZIndVaY0xoL3LiiOb75anZZ0XOd2kSyNy2V6hoO2MKIdKQcvRY9jiObdsyxiARC1JKCQmyjBDDMGId4IbDMAzTNHVdB1kk17QxWSYLANfHWxCQA5YkY9nzPPvNHi3Am0He2B/1F91umsYY4+6rl5W3RtX3/cb+D3Jd1yj+aeadOaNghN7Yn87595JQSpf/yf9N3t1tjZHslb1PrqoKpT388G+/GWT0DFvw7M3fDRmEGweJS7UAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Descent 2&quot;
        title=&quot;&quot;
        src=&quot;/static/ee38bb908faf9efa2b0413d6e41348a9/0b533/gradient_descent_2.png&quot;
        srcset=&quot;/static/ee38bb908faf9efa2b0413d6e41348a9/c26ae/gradient_descent_2.png 158w,
/static/ee38bb908faf9efa2b0413d6e41348a9/6bdcf/gradient_descent_2.png 315w,
/static/ee38bb908faf9efa2b0413d6e41348a9/0b533/gradient_descent_2.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;How do we know whether we need to move to the left or to the right? In this case the Gradient is &lt;strong&gt;positive&lt;/strong&gt; since there’s a positive slope at this position. So, we know that we have to go leftwards. If we are on a spot that is more left, we have to go rightwards because the slope is &lt;strong&gt;negative&lt;/strong&gt; there.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/9267a5a7b90e55cb6ef7af59abcb3b31/0b533/gradient_descent_3.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAACSUlEQVR42o1U2XKbQBDU//+U31KVt5RtnZBYjiQEiL3vA5RGWHLiI+WBWqZmtnd6p6eYLb/vtg+kKhk5yuJHd6xNdVDGGqV18bxr21ZrLa+mtGqeailEzvnx8XFWLr41z4vjfilk0zVlyr01brfbKaVqRupT2/d9uhgA0QXPFOX8UFWLxWJGFA9DcimEFHzyMYbgfd011plDy379rnJCCG9IOSmiRWssOamuW202MylkjlM+jm+MOWUd7d43nIt925yHIV4MYNsJb73f7c8pF2U5w01GPv+aC44ELqR4Ohxz7l+iKckjGzkEfz6fN2Plj8CX+r3RGmDr4aexrHayEXC8DwAXRfEpGHW0UodTw5SfwJJaS2Xqc7iBhRBIgcoECVdDENIwwVouvYs+RF6L6Cz2eH+lDUmmyulqk48gFOaCyaCkTFLlwHi6pHD0S2VKadd1dV1jbZqGEILBgI+VMaalrkjVkhPrCNnvKWNdd0IWfO/v70cwaBhjrLXTenOwwxorreRaeKUspdY5pMAIvJbL5QzeMAz5nSEIvJIq5CCTGqRGo3LfIwXmoF1+pvMoVc5oB3jBF15EznDXeOnI653/Ax4bxjmGhGviOU3Xba/gm1RvDEFURm/QYK3ROYL5nFKvUn2lsuNUGHqb0y/RRmUoNyqPMywNKY7P32DEp6F5YwjiXKhrlIpcUMudsxNn5xzA6/X6U6nwD8AmdCRaO8DrvUuufyMV/ib4bN4ZWM3nc3x+zufFar3crB5WD2Ux7kTN7XZ7d3f3B1lGc2tXaKWcAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Descent 3&quot;
        title=&quot;&quot;
        src=&quot;/static/9267a5a7b90e55cb6ef7af59abcb3b31/0b533/gradient_descent_3.png&quot;
        srcset=&quot;/static/9267a5a7b90e55cb6ef7af59abcb3b31/c26ae/gradient_descent_3.png 158w,
/static/9267a5a7b90e55cb6ef7af59abcb3b31/6bdcf/gradient_descent_3.png 315w,
/static/9267a5a7b90e55cb6ef7af59abcb3b31/0b533/gradient_descent_3.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Let’s get back to the descent. Now we reached a new spot on our graph, which we again calculate the Gradient for. Then, we take another step leftwards. This time, however, the step we take is slightly &lt;strong&gt;smaller&lt;/strong&gt; than the previous one, because the Gradient decreased as we come closer to the minimum.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/e742ca9a6d07530e5aa1d519d43c7dad/0b533/gradient_descent_4.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABhklEQVR42pVTSXKDMBD0/x+Xgy/4lARjkGUZ0ILRSioNAhdQMThzmGqG6dl1OB6/TwlNz4zSKklonpdZVgohIXnO8rwAEJMoJQkpOe8x7Ado74NzzjtvBw0VQui6wPkjvxC/kCClwe8ehQCyALKDOGcn4Lx3QjzOaWGtiUZ4CWHIRYYw+izIT4lkpR6oHGlGsrON9lVRGikQaYsMads2TQm+RqN3jHD5+aWVcrtkrduiuLXt2A56vZxIkyR28N/PfL1SITRwCI6xln4kwWrUMJIxcczNLSVOVmuNNWG8WiOZr6uHrbmbQsOyIPuhkwhgRGbGboAYO9ZmjO1+uugTo/dl13XNGOOcQyMWtFIKGmTVi6yqGucAN3xUVdU0zf1+hz5E13gxTx0tELjO/4KAHLBE3ZfddZ1f3dEg6BnklX2Od6ZNKTXGuOn0nuCtVZVlubL/g0wIQfEvM2/sGQUj9Mo+xztHUhTF8J783+TN29ZYyVbZ2+Qsy1Da7MG/3TPImBmu4FXPvxJgg3dgW3zvAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Descent 4&quot;
        title=&quot;&quot;
        src=&quot;/static/e742ca9a6d07530e5aa1d519d43c7dad/0b533/gradient_descent_4.png&quot;
        srcset=&quot;/static/e742ca9a6d07530e5aa1d519d43c7dad/c26ae/gradient_descent_4.png 158w,
/static/e742ca9a6d07530e5aa1d519d43c7dad/6bdcf/gradient_descent_4.png 315w,
/static/e742ca9a6d07530e5aa1d519d43c7dad/0b533/gradient_descent_4.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;We repeat this procedure multiple times until we reach, or at least are close to, the graph’s minimum.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/52b88c968a81a5ea3cd27c8756c29965/0b533/gradient_descent_5.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABlElEQVR42pVTXW+DMAzs//9jkybtZZvWvWwqZYHSFMgHJSRO2A5oo7ZaYbsHyzl8jmOb1fPz5n1dJFteFNV6XTBWpmkppQIY44xlcOQZWqs8L4UYfPArWCLvnCNHdrQw3vsQvBBH9pXTFbzSlvzoeQ+xhGdHOGfPjiNyUh63SWZtN5GIksrmSe3pFHMljpjEWh9RufcUxaqx5ecXjenmxEDbtkmS43QivefpodlsXAi26xbExrRZtm/b03OMJbbOrBR2jF++ebcrpDTwQ+/4/rh7/fDBxZgVOo6+uWtMnTXGYExKdZ3pOurfHrZmz6nvY8yVGOfogMTNnO/J+aZpnx4Fe0m++2GQMftQdl3XnHMhBCxywWqtYSHWA1RV1aJWQtY4VFXZNM3hcIBdTaHTxkQ7MUBVVfErFgsC3AFmskPZIQS62aMReDPEN/ylv9Dtoii6caSRv4xZEJdlecP/Q5znOYq/e/PMnFEwUt/wl/7CkmRZNv4S9Lt4drcNRjJX9rw4TVOUdvHD//nNEKNn2IJ7b/4BVHaCynz/eGkAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Descent 5&quot;
        title=&quot;&quot;
        src=&quot;/static/52b88c968a81a5ea3cd27c8756c29965/0b533/gradient_descent_5.png&quot;
        srcset=&quot;/static/52b88c968a81a5ea3cd27c8756c29965/c26ae/gradient_descent_5.png 158w,
/static/52b88c968a81a5ea3cd27c8756c29965/6bdcf/gradient_descent_5.png 315w,
/static/52b88c968a81a5ea3cd27c8756c29965/0b533/gradient_descent_5.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The important thing here is, that the steps are getting &lt;strong&gt;smaller&lt;/strong&gt; with each single step. That’s because our step size depends on the size of the Gradient (slope) at the given position, which is getting smaller and smaller the closer we are to the graph’s minimum. Just as you have seen above.&lt;/p&gt;
&lt;p&gt;Actually, the step size does not only depend on the Gradient’s size. At our stating position (&lt;code class=&quot;language-text&quot;&gt;x = 6&lt;/code&gt;) the Gradient is also &lt;code class=&quot;language-text&quot;&gt;6&lt;/code&gt;. Now imagine we go &lt;code class=&quot;language-text&quot;&gt;6&lt;/code&gt; steps leftwards. In this case we would miss the graph’s minimum and end up too far left. That’s why we have to go a certain proportion of the Gradient.&lt;/p&gt;
&lt;p&gt;This proportion is also called &lt;strong&gt;learning rate&lt;/strong&gt;. During each iteration of our Gradient Descent (when we take a single step) the algorithm multiplies the learning rate by the gradient. The resulting product is called the gradient step: &lt;code class=&quot;language-text&quot;&gt;gradient_step = lr * gradient&lt;/code&gt;. That’s the actual step we take leftwards.&lt;/p&gt;
&lt;p&gt;The learning rate is a value we set on our own. We could use &lt;code class=&quot;language-text&quot;&gt;0.001&lt;/code&gt; for example. A too high learning rate might result in taking too large steps, and we might miss the minimum. If the learning rate is too small, we tend to not reaching the minimum in a given number of iterations.&lt;/p&gt;
&lt;p&gt;This resulting &lt;strong&gt;gradient step&lt;/strong&gt; in each iteration is then subtracted from our current weight, the &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; value: &lt;code class=&quot;language-text&quot;&gt;x = x - gradient_step&lt;/code&gt;. This way our weight becomes step by step closer to the target value: the value where the loss (&lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt;) is the smallest.&lt;/p&gt;
&lt;p&gt;If the gradient_step is negative because the slope is negative, we &lt;strong&gt;add&lt;/strong&gt; the &lt;code class=&quot;language-text&quot;&gt;gradient_step&lt;/code&gt; since minus and minus is plus and go rightwards accordingly.&lt;/p&gt;
&lt;p&gt;Now let’s bring this all together and implement it in Python. Keep in mind that the graph’s &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; value is represented as the weight &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; in our codebase.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# The partial derivatives of &quot;loss&quot; with respect to w and b&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    w_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; X&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; w_gradient

&lt;span class=&quot;token comment&quot;&gt;# Train the model using Gradient Descents algorithm&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; iterations&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; lr&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    w &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;# Initial weight&lt;/span&gt;

    &lt;span class=&quot;token comment&quot;&gt;# Gradient Descents iterations&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;iterations&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        w_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; gradient&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        w &lt;span class=&quot;token operator&quot;&gt;-=&lt;/span&gt; w_gradient &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; lr
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; w&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;As I mentioned earlier, the Gradient is calculated using the partial derivatives of the function with respect to each single parameter. Our function in this case is the loss function (MSE). At the moment we’re just dealing with one parameter &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;. So, we calculate the partial derivative with respect to &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;. You can see the result in &lt;code class=&quot;language-text&quot;&gt;gradient()&lt;/code&gt;. This &lt;a href=&quot;https://mccormickml.com/2014/03/04/gradient-descent-derivation/&quot;&gt;article&lt;/a&gt; might give you a better understanding of how the partial derivatives for the MSE are calculated.&lt;/p&gt;
&lt;p&gt;Since we are just dealing with one parameter until now, we pass &lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt; for &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; when we call &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; in our &lt;code class=&quot;language-text&quot;&gt;gradient()&lt;/code&gt; function. We’ll fix this now.&lt;/p&gt;
&lt;h5&gt;Two parameters: f(x,y)&lt;/h5&gt;
&lt;p&gt;Until now, we assumed that our model only depends on one parameter &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt;, also known as weight &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;. But that’s not the truth actually. If we take a look at the &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; function we can see that its output for a given value &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; depends on the weight &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and the bias &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt;. So we have two parameters.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# The model&apos;s output (prediction)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; X &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; w &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;That means, the graph from above is not correct anymore.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 500px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/52b88c968a81a5ea3cd27c8756c29965/0b533/gradient_descent_5.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 100%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAACXBIWXMAAAsTAAALEwEAmpwYAAABlElEQVR42pVTXW+DMAzs//9jkybtZZvWvWwqZYHSFMgHJSRO2A5oo7ZaYbsHyzl8jmOb1fPz5n1dJFteFNV6XTBWpmkppQIY44xlcOQZWqs8L4UYfPArWCLvnCNHdrQw3vsQvBBH9pXTFbzSlvzoeQ+xhGdHOGfPjiNyUh63SWZtN5GIksrmSe3pFHMljpjEWh9RufcUxaqx5ecXjenmxEDbtkmS43QivefpodlsXAi26xbExrRZtm/b03OMJbbOrBR2jF++ebcrpDTwQ+/4/rh7/fDBxZgVOo6+uWtMnTXGYExKdZ3pOurfHrZmz6nvY8yVGOfogMTNnO/J+aZpnx4Fe0m++2GQMftQdl3XnHMhBCxywWqtYSHWA1RV1aJWQtY4VFXZNM3hcIBdTaHTxkQ7MUBVVfErFgsC3AFmskPZIQS62aMReDPEN/ylv9Dtoii6caSRv4xZEJdlecP/Q5znOYq/e/PMnFEwUt/wl/7CkmRZNv4S9Lt4drcNRjJX9rw4TVOUdvHD//nNEKNn2IJ7b/4BVHaCynz/eGkAAAAASUVORK5CYII=&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Gradient Descent 5&quot;
        title=&quot;&quot;
        src=&quot;/static/52b88c968a81a5ea3cd27c8756c29965/0b533/gradient_descent_5.png&quot;
        srcset=&quot;/static/52b88c968a81a5ea3cd27c8756c29965/c26ae/gradient_descent_5.png 158w,
/static/52b88c968a81a5ea3cd27c8756c29965/6bdcf/gradient_descent_5.png 315w,
/static/52b88c968a81a5ea3cd27c8756c29965/0b533/gradient_descent_5.png 500w&quot;
        sizes=&quot;(max-width: 500px) 100vw, 500px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Here &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; was our loss and &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; the weight (&lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;). Now, we need another dimension for the bias &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; since the loss of our model depends on the values we’ll set for &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That means our loss function has &lt;strong&gt;three axes&lt;/strong&gt; and might look like the following with some random values for the weight and bias. The green cross indicates the graph’s minimum.&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/33819f712d09a606e6b29542ff020b5b/01ccc/loss.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 64.55696202531645%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAANCAIAAAAmMtkJAAAACXBIWXMAAAsTAAALEwEAmpwYAAABY0lEQVR42qWSO0sDQRSFRysfICnEwkKr9CJYWSmIf0A7ES2ihaWV2IngD1DLwFYWgoXYiIWlpWCRhJAmmpCHyWYfM7M7zztOYmXMRsVbDdz5Zs695yDzj0JJDaWUEEJr/ScYDGgpZRzHYRhijCmljLGBD/XDAFoAcK2ZiC2JQxz2KggCQggAJMHdhuA1XHJwpRy2KI2I73lu2/XcgEQUE2x5O87gn0FraUzzevtpZc5ZLN6etCjzrWCmo2ax3mm03U6Hc54gu6vZkFr+fmHtDNU2R+4y63vOedbJlB4O37kMvqr+NjOPuDIyl80dI3dj4nJ2NDWP0juTj9VnJQzVCobCnBOChZZX++4yOpgZH0ujpZvTF2MkizmYobDdhxRSSa64vjjKTk+ltlZ3GWGNZt3u/ueQ2A1VK1Xf8+25kC+8lV+tw5+e/yph9qrneaC79tnAJOUMDU+vxUBDLzzQlxBjzAf6k9R9elxqLQAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Loss&quot;
        title=&quot;&quot;
        src=&quot;/static/33819f712d09a606e6b29542ff020b5b/f058b/loss.png&quot;
        srcset=&quot;/static/33819f712d09a606e6b29542ff020b5b/c26ae/loss.png 158w,
/static/33819f712d09a606e6b29542ff020b5b/6bdcf/loss.png 315w,
/static/33819f712d09a606e6b29542ff020b5b/f058b/loss.png 630w,
/static/33819f712d09a606e6b29542ff020b5b/40601/loss.png 945w,
/static/33819f712d09a606e6b29542ff020b5b/78612/loss.png 1260w,
/static/33819f712d09a606e6b29542ff020b5b/01ccc/loss.png 1399w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In our scenario, where we have a function like this, which depends on two input parameters &lt;code class=&quot;language-text&quot;&gt;x,y&lt;/code&gt; aka &lt;code class=&quot;language-text&quot;&gt;w,b&lt;/code&gt;, the Gradient is a &lt;strong&gt;vector&lt;/strong&gt; that can be interpreted as the “direction and rate of fastest increase”. In other words: it shows the direction of &lt;strong&gt;steepest ascent&lt;/strong&gt; from a given position in our graph.&lt;/p&gt;
&lt;p&gt;Imagine you’re standing in the valley of a mountain and you’re pointing to the top of the mountain with your finger. Your finger is in this case the Gradient. It points to the steepest ascent.&lt;/p&gt;
&lt;p&gt;And the opposite of this direction is the one of the &lt;strong&gt;steepest descent&lt;/strong&gt;. What happens if we follow this direction? We reach the graph’s minimum. The spot where our loss is the smallest for a given &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt;. Using the coordinates at this position for the weight and bias will our model make the best predictions.&lt;/p&gt;
&lt;p&gt;How do we calculate the Gradient when the function has two parameters? Just as above, we calculate the partial derivatives with respect to &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; (weight). Additionally, we do the same with respect to &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; (bias).&lt;/p&gt;
&lt;p&gt;Let’s implement this in Python. We can take over the partial derivatives we calculated more above for &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt;. Moreover, we don’t pass &lt;code class=&quot;language-text&quot;&gt;0&lt;/code&gt; as argument anymore when calling &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt;, but &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# The partial derivatives of &quot;loss&quot; with respect to w and b&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    w_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; X&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    b_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;w_gradient&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b_gradient&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Keep in mind, that the Gradient is a vector. In this case a vector with two elements. That’s why we’re returning two values from &lt;code class=&quot;language-text&quot;&gt;gradient()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Since we have two Gradients from now on, we have to change our &lt;code class=&quot;language-text&quot;&gt;train()&lt;/code&gt; function. Both values &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt; must be updated after each iteration.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# Train the model using Gradient Descents algorithm&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; iterations&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; lr&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    w &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; b &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;# Initial weight and bias&lt;/span&gt;

    &lt;span class=&quot;token comment&quot;&gt;# Gradient Descents iterations&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;iterations&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        w_gradient&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; gradient&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        w &lt;span class=&quot;token operator&quot;&gt;-=&lt;/span&gt; w_gradient &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; lr
        b &lt;span class=&quot;token operator&quot;&gt;-=&lt;/span&gt; b_gradient &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; lr
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;The prediction&lt;/h3&gt;
&lt;p&gt;Finally, we have everything we need to answer the question from the beginning. This is our codebase:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# The model&apos;s output (prediction)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; X &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; w &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; b

&lt;span class=&quot;token comment&quot;&gt;# Calculating the loss using MSE&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;# The partial derivatives of &quot;loss&quot; with respect to w and b&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    w_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; X&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    b_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;mean&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;w_gradient&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b_gradient&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;# Train the model using Gradient Descents algorithm&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; iterations&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; lr&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
    w &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; b &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;token comment&quot;&gt;# Initial weight and bias&lt;/span&gt;

    &lt;span class=&quot;token comment&quot;&gt;# Gradient Descents iterations&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; i &lt;span class=&quot;token keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;iterations&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;:&lt;/span&gt;
        w_gradient&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b_gradient &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; gradient&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        w &lt;span class=&quot;token operator&quot;&gt;-=&lt;/span&gt; w_gradient &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; lr
        b &lt;span class=&quot;token operator&quot;&gt;-=&lt;/span&gt; b_gradient &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; lr
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Well, what was the question again?&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;How many visitors can we expect to see in our park tomorrow when know that there will be 33°C at this day?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;Read the training data&lt;/li&gt;
&lt;li&gt;Train the model&lt;/li&gt;
&lt;li&gt;Make the prediction&lt;/li&gt;
&lt;li&gt;Output&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;python&quot;&gt;&lt;pre class=&quot;language-python&quot;&gt;&lt;code class=&quot;language-python&quot;&gt;&lt;span class=&quot;token comment&quot;&gt;# Load training data into Numpy array&lt;/span&gt;
X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; np&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;loadtxt&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;park.txt&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; skiprows&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; unpack&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token boolean&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;# Train the model&lt;/span&gt;
w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; loss_values &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; train&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;X&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; Y&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; iterations&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; lr&lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;token comment&quot;&gt;# Output&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;\nw=%.8f; b=%.8f&quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Prediction: x=%d =&gt; y=%.2f&quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;33&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; predict&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;33&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; w&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;When our model has finished its training it will set proper values for &lt;code class=&quot;language-text&quot;&gt;w&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;b&lt;/code&gt;. Now we can use those two parameters and predict the output for &lt;code class=&quot;language-text&quot;&gt;x = 33&lt;/code&gt;. We simply call &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt; and pass in the according arguments.&lt;/p&gt;
&lt;p&gt;When we run the Python programm and predict the value we’ll get the following output for the weight, bias and the prediction:&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 481px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/9ff380386b57a76355dafb84cff01783/d024a/prediction.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 17.088607594936708%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAADCAIAAAAcOLh5AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAo0lEQVR42g2NSQ6CMAAA+YjGqGBYpKxdoCu0lSIQAxcv/v8bNpnrzASgwYipaduzshXjJO2Mmdq/P6GnMH5SZbISzttRwJ4NVtoFs9G+P247UlAHTcc7MRq3ED54zLxBKttOeAhTiMooLSrYV4hy/ZrWoyFMu/VZoUsYBz5MxKisw3woWuJX/nxP8gr1mMq8Rgmos6LxLR/qpQbeHszpGp1vjz+GEym83jeGdgAAAABJRU5ErkJggg==&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Prediction&quot;
        title=&quot;&quot;
        src=&quot;/static/9ff380386b57a76355dafb84cff01783/d024a/prediction.png&quot;
        srcset=&quot;/static/9ff380386b57a76355dafb84cff01783/c26ae/prediction.png 158w,
/static/9ff380386b57a76355dafb84cff01783/6bdcf/prediction.png 315w,
/static/9ff380386b57a76355dafb84cff01783/d024a/prediction.png 481w&quot;
        sizes=&quot;(max-width: 481px) 100vw, 481px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see we can expect &lt;strong&gt;~543 visitors&lt;/strong&gt; for the next day. We’re also able to predict the number of visitors for any other day. We just have to change the &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; parameter (degrees) we pass in when calling &lt;code class=&quot;language-text&quot;&gt;predict()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Let’s have a look on how the model improved after each iteration of the trainings phase. Did it improve at all?&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/2cefc/improvement.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 54.43037974683544%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAIAAADwazoUAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAwElEQVR42q1S7Q6DIAz0/Z9T5EugoMPwIe6mWbIs++HcyOVyLb0WAl2tK1H0fvkKREvOtSulssEJ4ZXyUp6FEBRjfpgHTlIGrYNS5+GX5Uezc9Qzi/iK2Vp33fyHOx+T3/ExqY8xL+aeOTDnhDfj3B9CyIATcQgRkET4YLHvyt38/CTRmsnYWY/TaObRgCcp0cJB6DEYe1PaWxfBKFOaUirdtm3ruoJLKa21imb7Qsj5wFifczq2cs4oA0OnlFprd4caaR8rXmGlAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Improvement&quot;
        title=&quot;&quot;
        src=&quot;/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/f058b/improvement.png&quot;
        srcset=&quot;/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/c26ae/improvement.png 158w,
/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/6bdcf/improvement.png 315w,
/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/f058b/improvement.png 630w,
/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/40601/improvement.png 945w,
/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/78612/improvement.png 1260w,
/static/a1e00bbfbb02c25a3ce7aaa65d48daf4/2cefc/improvement.png 1400w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you can see the loss was very high at the beginning. That’s where the model was the worst but improved the fastest. Afterwards, the improvement became less and less after each iteration. At the end the loss decreased slower since the Gradients decreased.&lt;/p&gt;
&lt;p&gt;Remember the linear function from the beginning that describes our model? This function looks as follows now:&lt;/p&gt;
&lt;p&gt;&lt;span
      class=&quot;gatsby-resp-image-wrapper&quot;
      style=&quot;position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; &quot;
    &gt;
      &lt;a
    class=&quot;gatsby-resp-image-link&quot;
    href=&quot;/static/25e3e15622b3471732a2fbaa74284919/d0c0e/linear_function_final.png&quot;
    style=&quot;display: block&quot;
    target=&quot;_blank&quot;
    rel=&quot;noopener&quot;
  &gt;
    &lt;span
    class=&quot;gatsby-resp-image-background-image&quot;
    style=&quot;padding-bottom: 10.126582278481013%; position: relative; bottom: 0; left: 0; background-image: url(&apos;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAACCAYAAABYBvyLAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAWklEQVR42i3OOQqAQBBE0Q7EJRMM3BAncAYERUEMDFwOYOD9T+MPKnhJU0W1mZlHhg4xNnwIGHHhRKtcjgQ3Diyo8GCHvQo0KvRYNVDAYdY9UibFhFJDtR4bfsAhBURv8e7wAAAAAElFTkSuQmCC&apos;); background-size: cover; display: block;&quot;
  &gt;&lt;/span&gt;
  &lt;img
        class=&quot;gatsby-resp-image-image&quot;
        alt=&quot;Linear function final&quot;
        title=&quot;&quot;
        src=&quot;/static/25e3e15622b3471732a2fbaa74284919/f058b/linear_function_final.png&quot;
        srcset=&quot;/static/25e3e15622b3471732a2fbaa74284919/c26ae/linear_function_final.png 158w,
/static/25e3e15622b3471732a2fbaa74284919/6bdcf/linear_function_final.png 315w,
/static/25e3e15622b3471732a2fbaa74284919/f058b/linear_function_final.png 630w,
/static/25e3e15622b3471732a2fbaa74284919/d0c0e/linear_function_final.png 715w&quot;
        sizes=&quot;(max-width: 630px) 100vw, 630px&quot;
        style=&quot;width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;&quot;
        loading=&quot;lazy&quot;
        decoding=&quot;async&quot;
      /&gt;
  &lt;/a&gt;
    &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;It is used to predict values. It’s the heart of our machine learning model. The cool thing here is that the machine learned by itself to set proper values for &lt;code class=&quot;language-text&quot;&gt;x&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;y&lt;/code&gt; with the help of the training data from the beginning. Magic!&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;That’s it! I hope this article helped you to better understand Gradient Descent in Python. You can find the complete source code at &lt;a href=&quot;https://gist.github.com/larswaechter/c2df0bc9b0f15c64220eb5699b25ddf1&quot;&gt;GitHub&lt;/a&gt; with some extra functions to create the diagrams from this article.&lt;/p&gt;
&lt;p&gt;The code and my knowledge is mostly based on the book &quot;&lt;a href=&quot;https://pragprog.com/titles/pplearn/programming-machine-learning/&quot;&gt;Programming Machine Learning&lt;/a&gt;&quot; by Paolo Perrotta. You should definitely check it out.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Zobrist Hashing]]></title><description><![CDATA[Zobrist hashing, named for its inventor Albert Zobrist, is a technique to represent game board positions, like from chess or Go, as hash…]]></description><link>https://larswaechter.dev/zobrist-hashing/</link><guid isPermaLink="false">https://larswaechter.dev/zobrist-hashing/</guid><pubDate>Sun, 02 Aug 2020 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Zobrist_hashing&quot;&gt;Zobrist hashing&lt;/a&gt;, named for its inventor Albert Zobrist, is a technique to represent game board positions, like from chess or Go, as hash value. It&apos;s mainly used with &lt;a href=&quot;https://en.wikipedia.org/wiki/Transposition_table&quot;&gt;transposition tables&lt;/a&gt;, a special kind of hash table that is indexed by a board position and used to avoid analyzing the same board position more than once.&lt;/p&gt;
&lt;h3&gt;What it&apos;s good for&lt;/h3&gt;
&lt;p&gt;In game theory there are algorithms like &lt;a href=&quot;https://en.wikipedia.org/wiki/Minimax&quot;&gt;Minimax&lt;/a&gt; or &lt;a href=&quot;https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning&quot;&gt;AlphaBeta&lt;/a&gt; that are used to analyze board positions and find the best possible move in the given situation. This might be applied to games like Chess, Go or tic-tac-toe.&lt;/p&gt;
&lt;p&gt;These algorithms take a given starting position and simulate the further course of the game with all possible moves for each player. With the help of an evaluation method, that is prescribed by the developer, the algorithm can calculate a score in each game situation. Based on this score the algorithm knows how good or bad a position is or a move that has led to this position. Ideally, the outpout of such an algorithm is the best possible move with it&apos;s calculated score.&lt;/p&gt;
&lt;p&gt;One problem is that it might take a very long time to calculate the best possible move, especially for games like chess. That&apos;s because game like chess has a huge game tree. A game tree is a directed graph whose nodes are positions in a game and whose edges are moves. Algorithms like Minimax builds such a graph and traverse it to find the best possible move.&lt;/p&gt;
&lt;p&gt;With the help of transposition tables it&apos;s possible to speed up these algorithms. Transposition tables act like a cache that store already analyzed board positions. While building up a game tree you mostly come across the same board position more than once. Without a transposition table you have to re-analyze the board position each time. So once the algorithm evaluated a position it stores the result in the transposition table to avoid this behavior. The next time the algorithm comes across this position it can take the result from the transposition table.&lt;/p&gt;
&lt;p&gt;All in all: Transposition tables are used within the algorithms to avoid analyze the same position multiple times.&lt;/p&gt;
&lt;p&gt;Mostly, transposition tables are implemented as a HashMap where the key is a board position in string representation. So regarding to a board position it&apos;s possible to store some information about it, like the best move.&lt;/p&gt;
&lt;p&gt;This is where the &lt;strong&gt;Zobrist hash&lt;/strong&gt; comes up: Zobrist hashing is a way to represent a given board position as an (unique) hash value. This hash is used within the transposition table to map information, like the best move, to the board and make it accessible.&lt;/p&gt;
&lt;p&gt;So the following paragraph describes how a Zobrist hash works and how it&apos;s calculated. Tic-tac-toe is taken as example game here. At the end of this post you&apos;ll find an implementation in Kotlin.&lt;/p&gt;
&lt;h3&gt;How it works&lt;/h3&gt;
&lt;p&gt;Zobrist hashing works with a bunch of &lt;code class=&quot;language-text&quot;&gt;xor&lt;/code&gt; operations of random generated numbers, called keys. We break this down into two parts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Generating the keys&lt;/li&gt;
&lt;li&gt;Calculating the hash&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Generating the keys&lt;/h4&gt;
&lt;p&gt;First of all, we have to generate keys according to the following scheme:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;For every available board cell and every possible game character in one of these cells, we generate a random number.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This might sound a little bit confusing but it&apos;s actually quite easy. Let&apos;s have a look at our example, tic-tac-toe:&lt;/p&gt;
&lt;p&gt;In a tic-tac-toe board, there are 9 available cells. In each of one of these cells there can be placed 2 different game characters: &lt;code class=&quot;language-text&quot;&gt;X&lt;/code&gt; or &lt;code class=&quot;language-text&quot;&gt;O&lt;/code&gt;. So according to above&apos;s quote we have to generate 18 (9*2) random numbers.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;cell  |   player 1 (X)  |   player 2 (O)
------------------------------------------
0     |      44532      |      72217
1     |      90195      |      10291
2     |      81410      |      65932
3     |      36721      |      91854
...&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In practice, most of the time 64 bit numbers, e.g. of data type &lt;code class=&quot;language-text&quot;&gt;Long&lt;/code&gt;, are used as random numbers. This reduces the risk of collisions while calculating the hashes later on.&lt;/p&gt;
&lt;h4&gt;Calculating the hash&lt;/h4&gt;
&lt;p&gt;Now, after the keys were generated it&apos;s possible to calculate the Zobrist hash of a given board position:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Take the previously generated random number of each cell where a game character is placed in and combine them per &lt;code class=&quot;language-text&quot;&gt;xor&lt;/code&gt; operation.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Again, it&apos;s easier than it might sound. Let&apos;s have an example.&lt;/p&gt;
&lt;p&gt;Before we begin with that a quick note: The cells of our tic-tac-toe game are ordered like this: from 0 to 8.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;0 1 2
3 4 5
6 7 8&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Okay, now it&apos;s time for an example. Have a look at the following board position:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;X . O
X . .
. . .

Player 1 (X) in cells: 0, 3
Player 2 (O) in cells: 2&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The players played in the following cells:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Player 1: 0, 3&lt;/li&gt;
&lt;li&gt;Player 2: 2&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Finally, we can calculate the Zobrist hash for this position: We take the random numbers / keys for these cells from above and combine them per &lt;code class=&quot;language-text&quot;&gt;xor&lt;/code&gt; operation. The order of the operations does not matter:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;    44532 (cell #0 player 1)
XOR 65932 (cell #2 player 2)
XOR 36721 (cell #3 player 1)
---------
  = 74505 (Zobrist hash)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We successfully calculated the Zobrist hash for the game position: &lt;code class=&quot;language-text&quot;&gt;74505&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Now, this hash can be used to store the board position inside the transposition table. In this case, the calculated hash value is used as key.&lt;/p&gt;
&lt;h4&gt;Reusing the hash&lt;/h4&gt;
&lt;p&gt;A huge advantage of this procedure is that it&apos;s not necessary to calculate the hash completely new after a move was played: We can take the key of the cell where the new move is played and combine it with the already existing Zobrist hash.&lt;/p&gt;
&lt;p&gt;Assuming we have the same position as above:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;X . O
X . .
. . .

=&gt; 74505 (Zobrist hash)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Now, player O plays his move in cell #1, even though it&apos;s a bad one:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;X O O
X . .
. . .&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Again we&apos;d like to calculate the Zobrist hash for the newly created board position. We use the old hash &lt;code class=&quot;language-text&quot;&gt;74505&lt;/code&gt; and combine it again per &lt;code class=&quot;language-text&quot;&gt;xor&lt;/code&gt; operation with the key of the new played cell (#1):&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;    74505 (old Zobrist hash)
XOR 10291 (cell #1 player 2)
---------
  = 68410 (new Zobrist hash)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Reusing the old hash to calculate a new one after a move was played makes it very efficient for traversing a game tree.&lt;/p&gt;
&lt;p&gt;Moreover, it&apos;s quite easy do undo a move: we use the newly created Zobrist hash and combine it with key of the cell we&apos;d like to undo. Let&apos;s undo player&apos;s 2 last move in cell #1 from above.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;    68410 (new Zobrist hash)
XOR 10291 (cell #1 player 2)
---------
  = 74505 (Zobrist hash after undo last move)


Resulting position:
X . O
X . .
. . .&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The Zobrist hash, &lt;code class=&quot;language-text&quot;&gt;74505&lt;/code&gt;, equals the one in the beginning, before the move of player 2 was played.&lt;/p&gt;
&lt;p&gt;Last but not least an example Zobrist hashing &lt;a href=&quot;https://gist.github.com/larswaechter/2c007c00904822b68331fe26736d92a8&quot;&gt;implementation&lt;/a&gt; in Kotlin for tic-tac-toe. Check it out.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Building a Stack Class in Java]]></title><description><![CDATA[A stack is a fundamental data structure in programming. It behaves like a data container where new items are added to the top of the stack…]]></description><link>https://larswaechter.dev/java-build-stack/</link><guid isPermaLink="false">https://larswaechter.dev/java-build-stack/</guid><pubDate>Thu, 06 Feb 2020 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A stack is a fundamental data structure in programming. It behaves like a data container where new items are added to the top of the stack and you only have access to last one added (most top item).&lt;/p&gt;
&lt;p&gt;A definition by &lt;a href=&quot;https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html&quot;&gt;Oracle&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Stack class represents a last-in-first-out (LIFO) stack of objects. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Today, we try to recreate this data structure in Java with our own generic class and interface. The class is generic in order to store different data types. It should provide the following six methods:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;push (to add a new item to the top)&lt;/li&gt;
&lt;li&gt;pop (to remove the most top item)&lt;/li&gt;
&lt;li&gt;peek (to get the most top item)&lt;/li&gt;
&lt;li&gt;isEmpty (to check whether the stack is empty)&lt;/li&gt;
&lt;li&gt;size (to get the size of the stack)&lt;/li&gt;
&lt;li&gt;search (to search for objects)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Interface&lt;/h3&gt;
&lt;p&gt;Let’s start with the interface for our stack. The interface specifies which methods have to be implemented inside the stack class. We declare the six methods I just mentioned before.&lt;/p&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;&amp;lt;T&gt;&lt;/code&gt; construct marks the interface as generic. In this case &lt;code class=&quot;language-text&quot;&gt;T&lt;/code&gt; can be any data type. For example &lt;code class=&quot;language-text&quot;&gt;Integer&lt;/code&gt; or &lt;code class=&quot;language-text&quot;&gt;String&lt;/code&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;interface&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Stackable&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;peek&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token keyword&quot;&gt;boolean&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;Object&lt;/span&gt; o&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;Class&lt;/h3&gt;
&lt;p&gt;As next, we create the stack class. Here we need two private attributes: &lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;value&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; is a reference to the item that is located below the current instance in the stack order (the underlying item). This results in a recursive implementation.&lt;/p&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;value&lt;/code&gt; attribute contains the value that the current instance of stack stores. It can be any data type.&lt;/p&gt;
&lt;p&gt;Moreover, there are multiple constructors we need later on. Since the class is generic we need here the &lt;code class=&quot;language-text&quot;&gt;&amp;lt;T&gt;&lt;/code&gt; construct as well.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;implements&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Stackable&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; previous&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

	&lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

	&lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
		&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

	&lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; previous&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
	    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; previous&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
		&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: push&lt;/h4&gt;
&lt;p&gt;This method pushes a new item onto the top of the stack. Therefore, we set the current instance of stack to our previous one and store the new value.&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; references now to our old stack instance.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: pop&lt;/h4&gt;
&lt;p&gt;This method removes the item at the stack’s top and returns its value.&lt;/p&gt;
&lt;p&gt;First of all we store the current value in a temporary variable because it gets overwritten and we need to return it later.&lt;/p&gt;
&lt;p&gt;Afterwards, we set the current &lt;code class=&quot;language-text&quot;&gt;value&lt;/code&gt; to the one from our &lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; stack item. Moreover, we reference the current &lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; attribute to the &lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; item of the underlying item.&lt;/p&gt;
&lt;p&gt;At the end, we return the removed value.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IllegalArgumentException&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;Stack is empty&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; top &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; top&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: peek&lt;/h4&gt;
&lt;p&gt;This method looks at the value of the item at the top of the stack and returns it. Here we just need to return &lt;code class=&quot;language-text&quot;&gt;value&lt;/code&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;peek&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: isEmpty&lt;/h4&gt;
&lt;p&gt;This method tests if the stack is empty. Since the last stack item has no reference to another (underlying) item, we just need to check if the &lt;code class=&quot;language-text&quot;&gt;previous&lt;/code&gt; item is &lt;code class=&quot;language-text&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;boolean&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous &lt;span class=&quot;token operator&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: size&lt;/h4&gt;
&lt;p&gt;This method returns number of items in our stack. Here, we recursively count until the last item is reached.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: search&lt;/h4&gt;
&lt;p&gt;This method returns the 1-based position where an item is on the stack. Therefor, we loop over all our stack items and increase a counter until the one that equals the target item is reached. Last but not least we return the counter.&lt;/p&gt;
&lt;p&gt;If there is no match, &lt;code class=&quot;language-text&quot;&gt;-1&lt;/code&gt; is returned.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;Object&lt;/span&gt; o&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; count &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; stack &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;!&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt; stack &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;equals&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;o&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; count&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
        count&lt;span class=&quot;token operator&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;Method: toString&lt;/h4&gt;
&lt;p&gt;This method is used to represent the Stack as String.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token annotation punctuation&quot;&gt;@Override&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;toString&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;previous &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot; &amp;lt;- &quot;&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value &lt;span class=&quot;token operator&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;null&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;valueOf&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;value&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;Try it out&lt;/h2&gt;
&lt;p&gt;Let’s create a new instance of our &lt;code class=&quot;language-text&quot;&gt;Stack&lt;/code&gt; class and try it out.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;java&quot;&gt;&lt;pre class=&quot;language-java&quot;&gt;&lt;code class=&quot;language-java&quot;&gt;&lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; stack &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Stack&lt;/span&gt;&lt;span class=&quot;token generics&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;token class-name&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;    &lt;span class=&quot;token comment&quot;&gt;// true&lt;/span&gt;

stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isEmpty&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;    &lt;span class=&quot;token comment&quot;&gt;// false&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;       &lt;span class=&quot;token comment&quot;&gt;// 4&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;peek&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;       &lt;span class=&quot;token comment&quot;&gt;// 16&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;printl&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;         &lt;span class=&quot;token comment&quot;&gt;// 16&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;peek&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;       &lt;span class=&quot;token comment&quot;&gt;// 7&lt;/span&gt;

&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;   &lt;span class=&quot;token comment&quot;&gt;// -1&lt;/span&gt;
&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;    &lt;span class=&quot;token comment&quot;&gt;// 2&lt;/span&gt;
&lt;span class=&quot;token class-name&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;out&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;stack&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token number&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;    &lt;span class=&quot;token comment&quot;&gt;// 1&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;hr&gt;
&lt;p&gt;That’s it! &lt;a href=&quot;https://gist.github.com/larswaechter/5ee39c4b4d874f0280951b6ac5a40ace&quot;&gt;Here&lt;/a&gt; you can find a GitHub Gist including the complete code.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[Path aliases with TypeScript in Node.js]]></title><description><![CDATA[Some days ago I included path aliases in my TypeScript Node.js projects. Since they make the code look much cleaner in my opinion I like to…]]></description><link>https://larswaechter.dev/nodejs-ts-path-aliases/</link><guid isPermaLink="false">https://larswaechter.dev/nodejs-ts-path-aliases/</guid><pubDate>Wed, 06 Feb 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Some days ago I included path aliases in my TypeScript Node.js projects. Since they make the code look much cleaner in my opinion I like to show you how to setup these in a project.&lt;/p&gt;
&lt;h2&gt;The problem&lt;/h2&gt;
&lt;p&gt;In Node.js (or TS/JS in general) you can import single modules into your code.
This might look the following:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;javascript&quot;&gt;&lt;pre class=&quot;language-javascript&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; User &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;../../user/model&quot;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; Article &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;../../article/model&quot;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; Cache &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;../../../../cache&quot;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; MongoDB &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;../../../../mongodb&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Noticed these dots (&apos;../&apos;) to access upper modules?&lt;/p&gt;
&lt;p&gt;The problem we have here is that the deeper your project tree is the more &apos;../&apos; are required to access modules in higher layers. Actually, this doesn&apos;t look very beautiful to be honest. Fortunately we can change that.&lt;/p&gt;
&lt;p&gt;The solution: &lt;strong&gt;path aliases&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;What are path aliases?&lt;/h2&gt;
&lt;p&gt;In TypeScript you can avoid these &quot;bad&quot; looking imports with the help of path aliases. With path aliases you can declare aliases that map to a certain absolute path in your application.&lt;/p&gt;
&lt;p&gt;Here a quick example:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;javascript&quot;&gt;&lt;pre class=&quot;language-javascript&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; User &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;@modules/user/model&quot;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; Article &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;@modules/article/model&quot;&lt;/span&gt;

&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; Cache &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;@services/cache&quot;&lt;/span&gt;
&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; MongoDB &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;@services/mongodb&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In this case our two aliases are&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;@modules that maps to &apos;./src/rest/modules&apos;&lt;/li&gt;
&lt;li&gt;@services that maps to &apos;./src/services&apos;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Setup&lt;/h2&gt;
&lt;p&gt;Let&apos;s get into it and setup some path aliases. Note that I won&apos;t explain how to setup a TypeScript project in Node.js. I assume that you did this already.&lt;/p&gt;
&lt;p&gt;Imagine we have the following project structure:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;folder structure
└───src
   │
   └───rest
   │   │
   │   └───modules
   │   │   │
   │   │   └───article
   │   │   │
   │   │   └───user
   │   │
   │   │   server.ts
   │
   │
   └───services
   │   │    cache.ts
   │   │    mongodb.ts
   │
   │   index.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;Step 1: Update tsconfig.json&lt;/h3&gt;
&lt;p&gt;First of all, we have to declare the path aliases in our tsconfig file&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;json&quot;&gt;&lt;pre class=&quot;language-json&quot;&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;token property&quot;&gt;&quot;baseUrl&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;./src&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;token property&quot;&gt;&quot;paths&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token property&quot;&gt;&quot;@modules/*&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;rest/modules/*&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token property&quot;&gt;&quot;@services/*&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;services/*&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Now, you can use the new path aliases for module imports in your application. There occur any errors in your IDE (in my case VSC) or when you compile the code.&lt;/p&gt;
&lt;p&gt;However, we are not done yet. When you try compile the TS code into JS you won&apos;t see any errors. But as soon as you run your compiled JS code you will get an error:&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;Error: Cannot find module &apos;@modules/user&apos;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;That&apos;s because JS can&apos;t resolve the modules for the declared path aliases.&lt;/p&gt;
&lt;h3&gt;Step 2: Install module-alias package&lt;/h3&gt;
&lt;p&gt;Next, we&apos;ll install an npm package called &lt;a href=&quot;https://www.npmjs.com/package/module-alias&quot;&gt;module-alias&lt;/a&gt;&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;npm i --save module-alias&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This module registers the path aliases in the compiled JS files. Therefor we need to make some changes to our package.json:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;json&quot;&gt;&lt;pre class=&quot;language-json&quot;&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;token property&quot;&gt;&quot;_moduleAliases&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token property&quot;&gt;&quot;@modules&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;dist/rest/modules&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;token property&quot;&gt;&quot;@services&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;dist/services&quot;&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Note that &apos;dist&apos; is the folder where the compiled JS files are located.&lt;/p&gt;
&lt;p&gt;Last but not least we have to register the path aliases in our application.
Add the following line at the top of your startup file:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;javascript&quot;&gt;&lt;pre class=&quot;language-javascript&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;module-alias/register&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Finally, when you compile and execute the code you shouldn&apos;t see any import errors.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/Aionic-Apps/aionic-core/tree/master&quot;&gt;Here&lt;/a&gt; you can find some examples for path aliases in a side project I&apos;m currently working on.&lt;/p&gt;</content:encoded></item><item><title><![CDATA[How I structure my Node.js REST APIs]]></title><description><![CDATA[When I started using Node.js for building REST APIs on the server side, I struggled a lot with the same question over and over again: What…]]></description><link>https://larswaechter.dev/nodejs-rest-api-structure/</link><guid isPermaLink="false">https://larswaechter.dev/nodejs-rest-api-structure/</guid><pubDate>Wed, 03 Oct 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When I started using &lt;a href=&quot;https://nodejs.org/en/&quot;&gt;Node.js&lt;/a&gt; for building REST APIs on the server side, I struggled a lot with the same question over and over again:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;What should the folder structure look like?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Obviously there’s &lt;strong&gt;no perfect or 100% correct&lt;/strong&gt; answer to this question but after reading some articles regarding this topic, I found a Node.js folder structure and architecture that fit my needs quite well. So today I’d like to show you how I structure and organize my Node.js REST APIs.&lt;/p&gt;
&lt;p&gt;I also published a GitHub &lt;a href=&quot;https://github.com/larswaechter/expressjs-api&quot;&gt;repository&lt;/a&gt; including an example application which you can use as template for your own project.&lt;/p&gt;
&lt;p&gt;One thing to mention is that I use &lt;a href=&quot;https://expressjs.com/de/&quot;&gt;Express.js&lt;/a&gt; as web-framework and &lt;a href=&quot;https://typeorm.io/#/&quot;&gt;TypeORM&lt;/a&gt; as an ORM. It shouldn&apos;t be that hard to apply this folder structure to other frameworks.&lt;/p&gt;
&lt;p&gt;The architecture is mostly &lt;strong&gt;component based&lt;/strong&gt; what makes it much easier to request only the data we really need. For example we have a &lt;code class=&quot;language-text&quot;&gt;User&lt;/code&gt; component that contains all information about users.&lt;/p&gt;
&lt;p&gt;Let&apos;s start with the &lt;code class=&quot;language-text&quot;&gt;root&lt;/code&gt; directory.&lt;/p&gt;
&lt;h2&gt;Directory: root&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── db
├── dist
├── logs
├── node_modules
├── src
├── docker-compose.yml
├── Dockerfile
├── gulpfile.js
├── LICENSE
├── package.json
├── package-lock.json
├── README.md
├── tsconfig.json
└── tslint.json&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The root directory is nothing special and shouldn’t be new to you. It’s actually a basic Node.js setup including some config files for linting, Docker and more.&lt;/p&gt;
&lt;p&gt;The really interesting part here is the content of the &lt;code class=&quot;language-text&quot;&gt;src&lt;/code&gt; folder which this article is about. So what do we have in here?&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── components
│   ├── middleware
│   ├── routes.ts
│   └── server.ts
├── config
├── services
├── test
└── app.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;From here on, we&apos;ll go top-down through the files / directories and I&apos;ll examine each one. Let’s start with the &lt;code class=&quot;language-text&quot;&gt;api&lt;/code&gt; directory, the most important part and heart of the application.&lt;/p&gt;
&lt;h2&gt;Directory: src/api&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── components
│   ├── middleware
│   ├── routes.ts
│   └── server.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This directory includes all REST-API related files like components, the Express server instance and more.&lt;/p&gt;
&lt;h2&gt;Directory: src/api/components&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── components
│   │   ├── auth
│   │   ├── user
│   │   ├── user-invitation
│   │   ├── user-role
│   │   ├── helper.ts
│   │   └── index.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here we have the heart of our component based Node API. Each component has its own &lt;strong&gt;routes&lt;/strong&gt;, &lt;strong&gt;controller&lt;/strong&gt;, &lt;strong&gt;model&lt;/strong&gt;, &lt;strong&gt;repository&lt;/strong&gt;, &lt;strong&gt;policies&lt;/strong&gt;, &lt;strong&gt;tests&lt;/strong&gt; and &lt;strong&gt;templates&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Let’s step into the &lt;code class=&quot;language-text&quot;&gt;User&lt;/code&gt; component and have a look.&lt;/p&gt;
&lt;h3&gt;Directory: src/api/components/user&lt;/h3&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── components
│   │   ├── user
│   │   │   ├── services
│   │   │   │   └── mail.ts
│   │   │   ├── templates
│   │   │   │   ├── confirmation.html
│   │   │   ├── controller.ts
│   │   │   ├── model.ts
│   │   │   ├── policy.json
│   │   │   ├── repository.ts
│   │   │   ├── routes.ts
│   │   │   └── user.spec.ts
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;As you can see a component consists of the files I just mentioned before. Most of them represents a &lt;strong&gt;single class&lt;/strong&gt; that is exported. Of course, you can add here more component specific stuff.&lt;/p&gt;
&lt;p&gt;Since I have multiple components and their classes have the same structure most of the time, I also create &lt;strong&gt;interfaces&lt;/strong&gt; that are implemented in the classes. This helps me to keep the components’ structure straight.&lt;/p&gt;
&lt;p&gt;Moreover, we have the &lt;code class=&quot;language-text&quot;&gt;services&lt;/code&gt; directory here which includes local component services like &lt;code class=&quot;language-text&quot;&gt;mail&lt;/code&gt; for example. Those interhite from the global services.&lt;/p&gt;
&lt;p&gt;The &lt;code class=&quot;language-text&quot;&gt;templates&lt;/code&gt; directory includes mail HTML templates for the given component. For dynamically rendering HTML code I highly recommend &lt;a href=&quot;https://www.npmjs.com/package/ejs&quot;&gt;ejs&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;controller.ts&lt;/h4&gt;
&lt;p&gt;The controller class handles incoming requests and sends the response data back to the client. It uses the &lt;code class=&quot;language-text&quot;&gt;repository&lt;/code&gt; class to interact with the database. Request validation happens via middleware few steps before&lt;/p&gt;
&lt;p&gt;A shortened example:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserController&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; repo&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; UserRepository &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserRepository&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;readUser&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
    req&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Request&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    res&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Response&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
    next&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; NextFunction
  &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;Response &lt;span class=&quot;token operator&quot;&gt;|&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; userID &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; req&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;params

      &lt;span class=&quot;token keyword&quot;&gt;const&lt;/span&gt; user&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; User &lt;span class=&quot;token operator&quot;&gt;|&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;undefined&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;repo&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;read&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
        where&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
          id&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;+&lt;/span&gt;userID&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;

      &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; res&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;json&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;user&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;err&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;model.ts&lt;/h4&gt;
&lt;p&gt;The model represents the database model for its component. In my case it’s a &lt;a href=&quot;https://typeorm.io/&quot;&gt;TypeORM&lt;/a&gt; class. Mostly it’s used by the &lt;code class=&quot;language-text&quot;&gt;repository&lt;/code&gt; classes.&lt;/p&gt;
&lt;h4&gt;policy.json&lt;/h4&gt;
&lt;p&gt;This json file includes the access rights for each user-role for the given component. It&apos;s part of a &lt;a href=&quot;https://de.wikipedia.org/wiki/Access_Control_List&quot;&gt;access control list&lt;/a&gt; based system.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;json&quot;&gt;&lt;pre class=&quot;language-json&quot;&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;Admin&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token property&quot;&gt;&quot;resources&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;user&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token property&quot;&gt;&quot;permissions&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;*&quot;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;token property&quot;&gt;&quot;User&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;token property&quot;&gt;&quot;resources&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;user&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token property&quot;&gt;&quot;permissions&quot;&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;read&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;repository.ts&lt;/h4&gt;
&lt;p&gt;The repository class acts like a wrapper for the database. Here we read and write data to the database. Furthermore, we can implement caching for example.&lt;/p&gt;
&lt;p&gt;You can import the &lt;code class=&quot;language-text&quot;&gt;repository&lt;/code&gt; class into any other file and query the data for this component from the database. Moreover, it prevents us from writing redundant code since we don&apos;t have to rewrite the SQL statements multiple times.&lt;/p&gt;
&lt;p&gt;Since most component repositories need the same basic access methods like &lt;code class=&quot;language-text&quot;&gt;readAll&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;read&lt;/code&gt;, &lt;code class=&quot;language-text&quot;&gt;save&lt;/code&gt; and &lt;code class=&quot;language-text&quot;&gt;delete&lt;/code&gt; I use a generic parent class that includes all these methods. This saves a lot of code.&lt;/p&gt;
&lt;p&gt;See &lt;a href=&quot;https://github.com/larswaechter/expressjs-api/blob/main/src/api/components/helper.ts&quot;&gt;AbsRepository&lt;/a&gt; for the implementation.&lt;/p&gt;
&lt;h4&gt;routes.ts&lt;/h4&gt;
&lt;p&gt;Here we define the API &lt;strong&gt;endpoints&lt;/strong&gt; for the corresponding component and assign the &lt;code class=&quot;language-text&quot;&gt;controller&lt;/code&gt; methods to them. Moreover we can add more stuff like&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;authorization (e.g. JWT)&lt;/li&gt;
&lt;li&gt;permission checking (ACL)&lt;/li&gt;
&lt;li&gt;request body validation&lt;/li&gt;
&lt;li&gt;component specific middleware in here.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A shortened Example:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;ts&quot;&gt;&lt;pre class=&quot;language-ts&quot;&gt;&lt;code class=&quot;language-ts&quot;&gt;&lt;span class=&quot;token keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserRoutes&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;implements&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;IComponentRoutes&lt;span class=&quot;token operator&quot;&gt;&amp;lt;&lt;/span&gt;UserController&lt;span class=&quot;token operator&quot;&gt;&gt;&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; name&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token builtin&quot;&gt;string&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;user&quot;&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; controller&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; UserController &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;UserController&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;readonly&lt;/span&gt; router&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; Router &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token function&quot;&gt;Router&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  authSerivce&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; AuthService

  &lt;span class=&quot;token function&quot;&gt;constructor&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;defaultStrategy&lt;span class=&quot;token operator&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; PassportStrategy&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;authSerivce &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;AuthService&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;defaultStrategy&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;initRoutes&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;token function&quot;&gt;initRoutes&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token operator&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;router&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;
      &lt;span class=&quot;token string&quot;&gt;&quot;/:userID&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;authSerivce&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isAuthorized&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;authSerivce&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;hasPermission&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;name&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;token string&quot;&gt;&quot;read&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token function&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token string&quot;&gt;&quot;userID&quot;&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;isNumeric&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;authSerivce&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;validateRequest&lt;span class=&quot;token punctuation&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;token keyword&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;controller&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;readUser
    &lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;token punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;user.spec.ts&lt;/h4&gt;
&lt;p&gt;This is the test file for testing the component and its endpoints. You can read more about testing this architecture &lt;a href=&quot;/blog/nodejs-rest-api-testing/&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Directory: src/api/middleware&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── middleware
│   │   ├── compression.ts
│   │   └── logging.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This folder includes all the API’s global middlewares like &lt;strong&gt;compression&lt;/strong&gt;, request &lt;strong&gt;logging&lt;/strong&gt; etc.&lt;/p&gt;
&lt;h2&gt;File: src/api/routes.ts&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── routes.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here we register all component and middleware routes. Those ones are used from the &lt;code class=&quot;language-text&quot;&gt;server&lt;/code&gt; class later on.&lt;/p&gt;
&lt;h2&gt;File: src/api/server.ts&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── api
│   ├── server.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here we declare everything required for the Express.js server:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;import middlware&lt;/li&gt;
&lt;li&gt;import routes&lt;/li&gt;
&lt;li&gt;error handling&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Later on, we can import the &lt;code class=&quot;language-text&quot;&gt;server&lt;/code&gt; class for unit tests as well.&lt;/p&gt;
&lt;h2&gt;Directory: src/config&lt;/h2&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── config
│   ├── globals.ts
│   ├── logger.ts
│   └── policy.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This directory includes the API&apos;s configuration files. This could be for example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;global variables&lt;/li&gt;
&lt;li&gt;logger config&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.npmjs.com/package/acl&quot;&gt;ACL&lt;/a&gt; permission&lt;/li&gt;
&lt;li&gt;SMTP config&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Feel free to put any &lt;strong&gt;config-related&lt;/strong&gt; files in here.&lt;/p&gt;
&lt;h2&gt;Directory: src/services&lt;/h2&gt;
&lt;p&gt;This directory contains global services we might need for &lt;strong&gt;authorization&lt;/strong&gt;, sending &lt;strong&gt;mails&lt;/strong&gt;, &lt;strong&gt;caching&lt;/strong&gt;, or &lt;strong&gt;helper&lt;/strong&gt; methods for example.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
├── services
│   ├── auth
│   │   ├── strategies
│   │   │   ├── base.ts
│   │   │   └── jwt.ts
│   │   └── index.ts
│   ├── mail.ts
│   ├── redis.ts
│   └── utility.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;auth&lt;/h3&gt;
&lt;p&gt;Here we setup things like our app&apos;s passport strategies and define authorization methods.&lt;/p&gt;
&lt;h3&gt;helper.ts&lt;/h3&gt;
&lt;p&gt;The helper class contains helper methods for &lt;strong&gt;hashing&lt;/strong&gt;, &lt;strong&gt;UUIDs&lt;/strong&gt; and so on.&lt;/p&gt;
&lt;h3&gt;mail.ts&lt;/h3&gt;
&lt;p&gt;This service is used for sending &lt;strong&gt;mails&lt;/strong&gt; and rendering the templates of the components. Again, I recommend the &lt;code class=&quot;language-text&quot;&gt;renderFile&lt;/code&gt; function of &lt;a href=&quot;https://www.npmjs.com/package/ejs&quot;&gt;ejs&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Directory: src/test&lt;/h2&gt;
&lt;p&gt;This directory includes a test factory for running the component tests.
You can read more about it &lt;a href=&quot;/nodejs-rest-api-testing&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;File: src/app.ts&lt;/h2&gt;
&lt;p&gt;This is the startup file of our application. It initializes the database connection and starts the express server.&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
└───src
    │   app.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;All together&lt;/h2&gt;
&lt;p&gt;Last but not least a complete overview of the project structure:&lt;/p&gt;
&lt;div class=&quot;gatsby-highlight&quot; data-language=&quot;text&quot;&gt;&lt;pre class=&quot;language-text&quot;&gt;&lt;code class=&quot;language-text&quot;&gt;expressjs-api
src/
├── api
│   ├── components
│   │   ├── auth
│   │   ├── user
│   │   │   ├── services
│   │   │   │   └── mail.ts
│   │   │   ├── templates
│   │   │   │   ├── confirmation.html
│   │   │   │   └── invitation.html
│   │   │   ├── controller.ts
│   │   │   ├── model.ts
│   │   │   ├── policy.json
│   │   │   ├── repository.ts
│   │   │   ├── routes.ts
│   │   │   └── user.spec.ts
│   │   ├── user-invitation
│   │   ├── user-role
│   │   ├── helper.ts
│   │   └── index.ts
│   ├── middleware
│   │   ├── compression.ts
│   │   └── logging.ts
│   ├── routes.ts
│   └── server.ts
├── config
│   ├── globals.ts
│   ├── logger.ts
│   └── policy.ts
├── services
│   ├── auth
│   │   ├── strategies
│   │   │   ├── base.ts
│   │   │   └── jwt.ts
│   │   └── index.ts
│   ├── mail.ts
│   ├── redis.ts
│   └── utility.ts
├── test
│   └── factory.ts
└── app.ts&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;That’s it! I hope this is a little help for people who don&apos;t know how to organize their Node.js application or didn’t know how to start. I think there are still many things you can do better or in a more efficient way, so feel free to share your own Node.js folder structure with me!&lt;/p&gt;
&lt;p&gt;If you&apos;re interested in writing unit tests for Node.js REST APIs have a look at this &lt;a href=&quot;/nodejs-rest-api-testing&quot;&gt;article&lt;/a&gt;. I also published a GitHub repository including an example application. &lt;a href=&quot;https://github.com/larswaechter/expressjs-api&quot;&gt;Have a look&lt;/a&gt;.&lt;/p&gt;</content:encoded></item></channel></rss>