<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicola Massarenti on Medium]]></title>
        <description><![CDATA[Stories by Nicola Massarenti on Medium]]></description>
        <link>https://medium.com/@nicola-massarenti?source=rss-41a5d63158a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4U20ZlhavS6hZVutIhN5ug.jpeg</url>
            <title>Stories by Nicola Massarenti on Medium</title>
            <link>https://medium.com/@nicola-massarenti?source=rss-41a5d63158a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:44:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicola-massarenti/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pair programming with ChatGPT — an unexpected path]]></title>
            <link>https://nicola-massarenti.medium.com/pair-programming-with-chatgpt-an-unexpected-path-7e5d1e81b393?source=rss-41a5d63158a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e5d1e81b393</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Nicola Massarenti]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 07:32:25 GMT</pubDate>
            <atom:updated>2023-01-25T07:32:25.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pair programming with ChatGPT — an unexpected path</h3><p><em>Originally published to </em><a href="https://nicolamassarenti.com/blog/pair-programming-chatgpt/"><em>nicolamassarenti.com</em></a></p><p>ChatGPT is out there and everyone is talking about it. I have read tons of posts regarding how to write prompts, what prompt is going to give you <strong>the</strong> secret strategy for the business… yada yada yada…</p><p>My story, here, is not about prompt engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5JXy8R3FxY6lol2mwriOw.png" /><figcaption>Image generated by DALL-E 2</figcaption></figure><p>It’s about one unexpected outcome, about how, for the first time, I felt like I was getting help from a Senior peer: someone who understood my problem, someone located remotely (because I was chatting with him), someone that had more experience than me in Linux, someone I could learn from.</p><h3><strong>The problem</strong></h3><p>My OS is Linux Ubuntu. My shell is <a href="https://fishshell.com/">fish</a> and I love it (check out my <a href="https://github.com/nicolamassarenti/dotfiles">dotfiles</a>). It allows the creation of functions (a.k.a. aliases) very easily.</p><p>My <em>note-taking tool</em> is <a href="https://obsidian.md/">Obsidian</a>, an open-source software for building the second brain (it’s also where I’m drafting this blog post).</p><p>On Ubuntu, I run the Obsidian app by running an AppImage, a format for distributing software on Linux. An AppImage file contains the software and all the dependencies you need to run the app. This means that to run the file you only type one command:</p><pre>./path/to/file.AppImage.</pre><p>Well, running obsidian via AppImage implies the following steps:</p><ul><li>Opening a terminal — typing: <em>CTRL+T</em></li><li>Running the AppImage — typing: <em>./path/to/AppImage</em></li><li>Keeping the terminal open to keep the process up and running — the main problem, because I often do some house-cleaning and close all the pending processes and terminals</li></ul><p>This means that I should repeat these three steps at least once a day. Every day…. This had to be automated!</p><h3><strong>What I wanted to do</strong></h3><p>My initial goal was to create a <em>fish</em> function that allowed me to type <em>obsidian</em> and, in turn, run the app image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Z5FtoSfDZTJ79Ir6OWCd8A.png" /></figure><p>This creates the following function (located in <em>~/.config/fish/functions/obsidian.fish</em>):</p><pre>function obsidian --wraps=/opt/obsidian/Obsidian-1.1.9.AppImage --description &#39;alias obsidian=/opt/obsidian/Obsidian-1.0.3.AppImage&#39;<br>  /opt/obsidian/Obsidian-1.0.3.AppImage $argv; <br>end</pre><p>However, this partially solved my problem. I had to keep the terminal up and running. This is what the terminal was printing while Obsidian was running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2iJ4C-Ci2VCvPo0kpgzzw.png" /></figure><p>So I thought: I just have to redirect the logs to <em>/dev/null</em> and it’s done! I can close or use the terminal for other stuff! Great!</p><p>At this point, I wanted a quick result since (I thought) I knew what was the path to follow. So, I decided to ask ChatGPT to solve the problem. I asked:</p><blockquote>write a fish function that runs a detached appImage at path “/opt/obsidian/Obsidian-1.1.9.AppImage”</blockquote><p>Great! I got the solution:</p><pre>function run-obsidian<br>    nohup /opt/obsidian/Obsidian-1.1.9.AppImage &gt; /dev/null 2&gt;&amp;1 &amp;<br>end</pre><p>I modified the <em>.fish</em> file and tested the new function: obsidian was opened and the process was detached, but when I closed the terminal, obsidian was closed too!</p><p>Fair enough… With some disappointment, I wrote to ChatGPT:</p><blockquote>the process should be alive even if I kill the terminal</blockquote><p>And here happened the unexpected! Here I was suggested a new path, something I knew could be used for such use cases but for a lack of experience I never considered. Here I learned something new, without searching for it.</p><h3><strong>What I discovered it was possible</strong></h3><p>ChatGPT now shared an unexpected solution. It said that if I wanted to have the process running even if I logged out of the system, I had to use <em>systemd</em> service manager.</p><p>This is the service file generated:</p><pre># Create a new service file<br>sudo nano /etc/systemd/user/obsidian.service<br><br># Add the following content to the file<br>[Unit]<br>Description=Obsidian AppImage<br><br>[Service]<br>ExecStart=/opt/obsidian/Obsidian-1.0.3.AppImage<br>Restart=always<br><br>[Install]<br>WantedBy=default.target</pre><p>And, I could use the following commands to enable and start the service:</p><pre>systemctl --user enable obsidian.service<br>systemctl --user start obsidian.service</pre><p>This was my reaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*fQkDDJJmBojrXc9HLchKew.png" /><figcaption>Speechless</figcaption></figure><p>I was stunned. This <strong>kind of interaction</strong> it’s exactly what a person expects from a Senior colleague. I <strong>felt enriched</strong> by the answer. It was great.</p><p>Now, I had to automate the setup. I asked:</p><blockquote>create a script that automates the generation of the file, the setup of systemctl, and that runs the latest version of the AppImage among those in the folder. Make it fish-compliant</blockquote><p>This was the output:</p><pre>#!/usr/bin/env fish<br><br># Edit this line to specify the path to your AppImages<br>set APPIMAGE_PATH &#39;/opt/obsidian&#39;<br><br># Edit this line to specify the service name<br>set SERVICE_NAME &#39;obsidian&#39;<br><br># Find the latest AppImage<br>set appimage (find $APPIMAGE_PATH -name &quot;Obsidian-*.AppImage&quot; | sort -r | head -n 1)<br><br># Create the service file<br>sudo sh -c &quot;echo &#39;[Unit]\nDescription=Obsidian AppImage\n\n[Service]\nExecStart=$appimage\nRestart=always\n\n[Install]\nWantedBy=default.target&#39; &gt; /etc/systemd/user/$SERVICE_NAME.service&quot;<br><br># Reload the systemd configuration<br>systemctl --user daemon-reload<br><br># Enable the service<br>systemctl --user enable $SERVICE_NAME.service<br><br># Start the service<br>systemctl --user start $SERVICE_NAME.service</pre><p>and it was done. Wow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e5d1e81b393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a website using GitHub Pages, Google Domains and Hugo]]></title>
            <link>https://nicola-massarenti.medium.com/how-to-create-a-website-using-github-pages-google-domains-and-hugo-209020c9f299?source=rss-41a5d63158a------2</link>
            <guid isPermaLink="false">https://medium.com/p/209020c9f299</guid>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Nicola Massarenti]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 08:13:58 GMT</pubDate>
            <atom:updated>2023-01-16T14:01:17.531Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s early 2023, and I’ve resigned from my full-time well-paid job to start a new journey as a freelancer. The first thing to do is to open a website that allows me to share thoughts, projects, and blog posts and be a reference for my clients.</p><p>There are tons of options. I must keep into account that:</p><ul><li>I have very little time available</li><li>I have limited knowledge of front-end technologies</li><li>I need a personal website deployed as soon as possible</li></ul><p>In the next sections, I’ll bring you on the journey of deploying a no-cost, minimal-effort and blog-friendly website on a custom domain (in my case, it’s <a href="https://nicolamassarenti.com/">nicolamassarenti.com</a>.</p><p><em>Originally posted </em><a href="https://nicolamassarenti.com/blog/create-a-website-github-google-domains/"><em>here</em></a></p><h3><strong>Technologies</strong></h3><p>If you’re like me and not a front-end/full-stack developer you’ll be overwhelmed by the options. To name a few, you’ll have to choose among:</p><ul><li>Spend time and learn a new technology</li><li>Use a no-code platform</li><li>Create a static site</li><li>Create a dynamic site</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGLlnwW1QDwasXj45CfMsA.png" /></figure><p>In the beginning, I was considering developing the website with Vue.js, which is easy to use and has an active community. I already know it a bit: in the past, I created a few dashboards (with vue.js and bootstrap), some login pages, and some upload pages. It would have been too much of an effort. It would have required a few days of coding, my design (colours, font, etc) would have been poor and, most importantly, there was the risk of falling into the rabbit hole of learning. I couldn’t take this effort: I needed a website as soon as possible.<br>On the other side, there was React, a popular framework with a steep learning curve. It may have been a good choice, but again, no time. I had to move on.</p><p>The second option was to use some no-code platforms such as <a href="http://www.squarespace.com/">Squarespace</a> or <a href="http://wix.com/">Wix</a>, which have the following drawbacks:</p><ul><li>they’re not free</li><li>I would be limited to the design they offer… Yes, I know, there are A LOT of templates... But hey, I am a developer, and I want to have freedom 😃</li><li>I would be dependent forever on a specific vendor</li></ul><p>So, I ended up choosing the third option: building a website using a framework for static websites. After some googling, I stumbled upon<a href="https://gohugo.io/">hugo</a>, which provides many themes, and supports Markdown and content organization through the use of taxonomies (e.g., categories, tags). One of the coolest themes I stumbled upon is <a href="https://github.com/adityatelange/hugo-PaperMod">PaperMod</a>, a minimal theme suited for a blog. The documentation wasn’t great and it didn’t seem straightforward to change the homepage.</p><p>So I did a deeper search and came across <a href="https://hugoloveit.com/">LoveIt</a>, a theme similar to PaperMod, with better documentation, recent commits and an easy way of customizing the home page.</p><p>Once I chose the website, it was time for the interesting part: <strong>developing.</strong></p><h3><strong>How to create a website</strong></h3><p>First of all, you have to install hugo . The link to the installation guide is <a href="https://gohugo.io/installation/">here</a>.</p><p>Then, create your project.</p><pre>hugo new site my-website<br>cd my-website<br>git init #initializing the folder as a repository</pre><p>Now install the theme. The straightforward way is to add the theme repository as a sub-module.</p><pre>git submodule add https://github.com/dillonzq/LoveIt.git themes/LoveIt</pre><h3>Customization</h3><p>The configurations are stored in the file config.toml. You can check my configurations <a href="https://github.com/nicolamassarenti/nicolamassarenti.github.io/blob/main/config.toml">here</a>.</p><p><strong>Favicons</strong></p><p>I used <a href="https://raw.githubusercontent.com/nicolamassarenti/nicolamassarenti.github.io/main/assets/images/NicolaMassarenti.jpg">this</a> picture and generated the different formats using <a href="https://realfavicongenerator.net/">realfavicongenerator</a> .</p><p><strong>Skeleton structure</strong></p><p>Setting up the skeleton (menu bar, header, footer) is fairly simple.</p><pre><br># Menu config<br>[menu]<br>  [[menu.main]]<br>    weight = 1<br>    identifier = &quot;blog&quot;<br>    pre = &quot;&quot;<br>    post = &quot;&quot;<br>    name = &quot;Blog&quot;<br>    url = &quot;/blog/&quot;<br>    title = &quot;The blog&quot;<br>  [[menu.main]]<br>    weight = 2<br>    identifier = &quot;about&quot;<br>    pre = &quot;&quot;<br>    post = &quot;&quot;<br>    name = &quot;About&quot;<br>    url = &quot;/about/&quot;<br>    title = &quot;The about page&quot;<br><br>[params]<br>  # site default theme [&quot;auto&quot;, &quot;light&quot;, &quot;dark&quot;]<br>  defaultTheme = &quot;dark&quot;<br>  # public git repo url only then enableGitInfo is true<br>  gitRepo = &quot;https://github.com/nicolamassarenti/nicolamassarenti.com&quot;<br>  #  which hash function used for SRI, when empty, no SRI is used<br>  # [&quot;sha256&quot;, &quot;sha384&quot;, &quot;sha512&quot;, &quot;md5&quot;]<br>  fingerprint = &quot;&quot;<br>  #  date format<br>  dateFormat = &quot;02/01/2006&quot;<br>  # website title for Open Graph and Twitter Cards<br>  title = &quot;Nicola Massarenti&#39;s website&quot;<br>  # website description for RSS, SEO, Open Graph and Twitter Cards<br>  description = &quot;The personal website of Nicola Massarenti&quot;<br>  # website images for Open Graph and Twitter Cards<br>  images = [&quot;/logo.png&quot;]<br><br>  # Header config<br>  [params.header]<br>    # desktop header mode [&quot;fixed&quot;, &quot;normal&quot;, &quot;auto&quot;]<br>    desktopMode = &quot;auto&quot;<br>    # mobile header mode [&quot;fixed&quot;, &quot;normal&quot;, &quot;auto&quot;]<br>    mobileMode = &quot;auto&quot;<br>    #  Header title config<br>    [params.header.title]<br>      # URL of the LOGO<br>      logo = &quot;&quot;<br>      # title name<br>      name = &quot;Nicola Massarenti&quot;<br>      # you can add extra information before the name (HTML format is supported), such as icons<br>      pre = &quot;&quot;<br>      # you can add extra information after the name (HTML format is supported), such as icons<br>      post = &quot;&quot;<br>      #  whether to use typeit animation for title name<br>      typeit = false<br><br>  # Footer config<br>  [params.footer]<br>    enable = true<br>    #  Custom content (HTML format is supported)<br>    custom = &#39;&#39;<br>    #  whether to show Hugo and theme info<br>    hugo = false<br>    #  whether to show copyright info<br>    copyright = true<br>    #  whether to show the author<br>    author = true<br>    # Site creation time<br>    since = 2023<br>    # ICP info only in China (HTML format is supported)<br>    icp = &quot;&quot;<br>    # license info (HTML format is supported)<br>    license = &#39;&lt;a rel=&quot;license external nofollow noopener noreffer&quot; href=&quot;https://creativecommons.org/licenses/by-nc/4.0/&quot; target=&quot;_blank&quot;&gt;CC BY-NC 4.0&lt;/a&gt;&#39;</pre><p>It sets the menu, the footer and the header configurations. There are two sections: blog, which contains my articles, and about, a page with my work experiences.</p><p><strong>Home Page</strong></p><p>To set up the home page is necessary to save the avatar in the folder assets/images. The configurations are:</p><pre>  [params.home]<br>    rss = 10<br>    [params.home.profile]<br>      enable = true<br>      gravatarEmail = &quot;&quot;<br>      avatarURL = &quot;/images/NicolaMassarenti.jpg&quot;<br>      title = &quot;Nicola Massarenti&quot;<br>      subtitle = &quot;Freelance AI/ML Engineer&quot;<br>      typeit = true<br>      social = true<br>      disclaimer = &quot;&quot;<br>    [params.home.posts]<br>      enable = false<br>      paginate = 6<br>      defaultHiddenFromHomePage = false<br><br>  [params.social]<br>    GitHub = &quot;https://github.com/nicolamassarenti&quot;<br>    Linkedin = &quot;https://www.linkedin.com/in/nicola-massarenti/&quot;<br>    Telegram = &quot;@nicolamassarenti&quot;<br>    Medium = &quot;https://medium.com/@nicola-massarenti&quot;<br>    ORCID = &quot;https://orcid.org/0000-0002-8882-4252&quot;<br>    Email = &quot;nicola.massarenti@gmail.com&quot;<br>    RSS = true # </pre><h3>Setting up CI/CD</h3><p>Setting up the <strong><em>CI/CD</em></strong> on GitHub is fast: you can automate your deployments by using the default action for hugo applications. The yml is provided by GitHub and is the following:</p><pre># Sample workflow for building and deploying a Hugo site to GitHub Pages<br>name: Deploy Hugo site to Pages<br><br>on:<br>  # Runs on pushes targeting the default branch<br>  push:<br>    branches: [&quot;main&quot;]<br><br>  # Allows you to run this workflow manually from the Actions tab<br>  workflow_dispatch:<br><br># Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages<br>permissions:<br>  contents: read<br>  pages: write<br>  id-token: write<br><br># Allow one concurrent deployment<br>concurrency:<br>  group: &quot;pages&quot;<br>  cancel-in-progress: true<br><br># Default to bash<br>defaults:<br>  run:<br>    shell: bash<br><br>jobs:<br>  # Build job<br>  build:<br>    runs-on: ubuntu-latest<br>    env:<br>      HUGO_VERSION: 0.108.0<br>    steps:<br>      - name: Install Hugo CLI<br>        run: |<br>          wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb \<br>          &amp;&amp; sudo dpkg -i ${{ runner.temp }}/hugo.deb<br>      - name: Install Dart Sass Embedded<br>        run: sudo snap install dart-sass-embedded<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>        with:<br>          submodules: recursive<br>      - name: Setup Pages<br>        id: pages<br>        uses: actions/configure-pages@v2<br>      - name: Install Node.js dependencies<br>        run: &quot;[[ -f package-lock.json || -f npm-shrinkwrap.json ]] &amp;&amp; npm ci || true&quot;<br>      - name: Build with Hugo<br>        env:<br>          # For maximum backward compatibility with Hugo modules<br>          HUGO_ENVIRONMENT: production<br>          HUGO_ENV: production<br>        run: |<br>          hugo \<br>            --minify \<br>            --baseURL &quot;${{ steps.pages.outputs.base_url }}/&quot;<br>      - name: Upload artifact<br>        uses: actions/upload-pages-artifact@v1<br>        with:<br>          path: ./public<br><br>  # Deployment job<br>  deploy:<br>    environment:<br>      name: github-pages<br>      url: ${{ steps.deployment.outputs.page_url }}<br>    runs-on: ubuntu-latest<br>    needs: build<br>    steps:<br>      - name: Deploy to GitHub Pages<br>        id: deployment<br>        uses: actions/deploy-pages@v1</pre><h3><strong>Setting up GitHub Pages and Google Domains</strong></h3><p>First of all, you have to enable GitHub Pages for your profile by going to your <strong><em>profile settings</em></strong> and enabling Pages. Then you have to <a href="https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site#configuring-an-apex-domain">configure an apex domain</a>, add your desired custom domain and save the configurations.</p><p>Now it’s time to move to Google Domains and click on <strong><em>Manage</em></strong> to the website you want to use as a custom domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*VPtl8szHzNLIbBXdDQReXA.png" /></figure><p>Then, add the Host Name records as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4h5QwwyQvpH6-gMBwo8RQw.png" /></figure><h3><strong>Conclusions</strong></h3><p>The process of creating a website can be daunting, especially if you have limited time and knowledge of front-end technologies. However, as demonstrated in this post, it is possible to create a professional, blog-friendly website with minimal effort by using a framework for static websites such as Hugo and a suitable theme. By following the steps outlined in this post, you can have your own website up and running in no time and for free.</p><p>I hope you found this post helpful and informative. If you have any questions or comments, please don’t hesitate to leave them below or to reach out to me on my <a href="https://www.linkedin.com/in/nicola-massarenti/?locale=en_US">LinkedIn account</a>.</p><p>I would love to hear from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209020c9f299" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-end Machine Learning — Machine Learning Model]]></title>
            <link>https://nicola-massarenti.medium.com/end-to-end-machine-learning-machine-learning-model-f1004897347d?source=rss-41a5d63158a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1004897347d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Nicola Massarenti]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 06:44:38 GMT</pubDate>
            <atom:updated>2021-04-04T10:34:20.037Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>End-to-end Machine Learning — Machine Learning Model</strong></h3><p>This article is the third in a series of articles on how to build an end-to-end machine learning pipeline for a chatbot AI that relies on a user-defined knowledge base. You can read about the description of the use case and the other articles in the series <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058">here</a>.</p><p>In this article, you will read about the machine learning model, based on BERT, and how to execute a training job on the Google AI Platform.</p><p>You can explore the code at my <a href="https://github.com/nicolamassarenti/model-bert-faqclass">GitHub</a> repository.</p><h3><strong>The framework</strong></h3><p>The panorama of frameworks and packages available to design and build machine learning models is extremely rich: Tensorflow, Pytorch, scikit-learn, Caffe, Spark ML, Ludwig, etc.</p><p>The framework I have used to build the machine learning model designed to learn multilingual F.A.Q.s with user-defined special keywords is <a href="https://www.tensorflow.org/">Tensorflow</a>, one of the most-used frameworks. It allows easy definition of custom neural networks as well as usage of standard estimators and, in addition, it allows easy setup of distributed training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q11Nci6MUreV-lB6" /></figure><h3><strong>Transformer and BERT</strong></h3><p>BERT [1] stands for <strong>B</strong>idirectional <strong>E</strong>ncoder <strong>R</strong>epresentations from <strong>T</strong>ransformers: the model that in 2018 took the scientific and professional natural language processing (NLP) community by storm. The key technical innovation is that BERT applies bidirectional training of Transformer [2], another key architecture that was published the year before, to model languages. In contrast, previous methodologies tried to look at a text sequence either from left to right or combined left-to-right and right-to-left training. BERT shows that bidirectional training of Transformers allows the model to grasp a deeper understanding and sense of a language context and flow than single-direction language models. The tests resulted in new state-of-the-art results on eleven natural language processing tasks.</p><p>But let’s start with the basics: the Transformer. It’s a model that uses neither Convolutional Neural Networks [3] (CNNs) nor Recurrent Neural Networks [3] (RNNs) in its structure, but just the attention mechanisms. The main reason behind passing over these well known models is that RNNs aren’t easily parallelizable while the CNNs require a lot of layers to catch long-term dependencies in the sequential structure of the data, not always succeeding in the attempt. Hence the NLP scientific community required a new autoregressive model able to produce outputs that depend not only on the input, but also on previous outputs and this is where the <em>attention mechanism </em>came in to help.</p><p>Let’s consider the <em>basic attention mechanism </em>in <em>Figure 1:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*ZcFez2cACjuLAn8-" /><figcaption><em>Figure 1: basic attention mechanism</em></figcaption></figure><p>The blocks denoted by <em>A</em>s are the input sequences and, in general, can be connected if you are using a RNN; while blocks denoted by <em>B</em>s are analogous and represent the output sequences. Here you can immediately notice the autoregressive behavior of this architecture: the second input <em>A</em> requires the previous output <em>B.</em> The equations that describe the mechanism are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*B-5W1Ac8Ya1Thc3STqeBFw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*RHlo3ozpxu5CkLXz" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/0*lOTYSKgFTcI-F7wy" /></figure><p>where <em>i</em> stands for the <em>i</em>-th decoder’s timestep and <em>u</em> is the <em>u</em>-th encoder’s. The latter two equations refer to the softmax layer computing probabilities and a weighted sum layer whereas the first is a bit more complex: it states that the relationship between</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/37/0*5eUcApXtmNEJ9wAj" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/45/0*c_xYtQTHPy9kubU7" /></figure><p>can be expressed as an element-wise product (<em>dot-product attention</em>) or as the outcome of a neural network (<em>additive attention</em>).</p><p>In the paper “<em>Attention is all you need” </em>[2], which introduced the Transformer, you’ll probably see the diagram shown in <em>Figure 2.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*l0ZeGWccjVSjNoea" /><figcaption><em>Figure 2: attention mechanism</em></figcaption></figure><p>Well… It’s not rocket science, but it’s certainly not intuitive. If you consider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/0*7qi-1ObiTxYkQib0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/0*Qu7BXM-acmcK4hKc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/61/0*uwaRVY4fJoYVPeD0" /></figure><p>we return to the situation illustrated in <em>Figure 1. </em>Indeed in the paper they expressed the dot-product attention as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/0*VXGEY9SN-lo4u4zs" /></figure><p>where <em>Q, K </em>and <em>V </em>stand for <em>Query</em>, <em>Key</em> and <em>Value</em> respectively, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/16/0*8O5_nup3zFYc-TOh" /></figure><p>is the dimension of the queries and keys.</p><p>This is a naïve approach to the attention mechanism because we are not considering it in combination with any other deep learning structure, but nonetheless the output is generated in an autoregressive manner. In addition, when the queries, keys and values come from the same sequence we call this the <em>self-attention layer</em>.</p><p>The full architecture of the Transformer is depicted in <em>Figure 3.</em> The main difference with other models is that the Transformer is entirely based on attention mechanisms and point-wise fully connected layers for both the encoder and the decoder. Both modules are thus cheaper in computational terms than any other competitor with similar test scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*PNG9l3CvaecWwVbR" /><figcaption><em>Figure 3: Transformer architecture</em></figcaption></figure><p>The Transformer is composed of 4 main components: the <em>Input-Output</em>, the <em>Positional Encoding, </em>the <em>Encoder </em>and the <em>Decoder</em>.</p><p>The <em>Input-Output</em> component is made up by the sentences encoded using <em>byte-pair</em> encoding [4], so the input of the Transformer is the sequence split into the sub-words, called <em>tokens</em>, as well as the output, with the only difference that at training time they act as labels. With this procedure our tokenized version of the words results in a sequence of vectors, each having a size equal to 512. Thus the whole sentence is now a matrix of real numbers.</p><p><em>Positional Encoding</em>, instead, was originally introduced in [5] and is a way of dealing with sequential data when neither recurrency nor temporal information is available due to the lack of RNNs or CNNs.</p><p>The <em>Encoder</em> structure is shown in <em>Figure 4.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*ysNyhU_cV6M7kWvx" /><figcaption><em>Figure 4: the Transformer encoder</em></figcaption></figure><p>The encoder is a stack of N=6 layers, each of which is composed of two sub-layers: a <em>multi-head attention mechanism </em>and a <em>fully-connected feed forward net</em>, plus <em>residual connections</em> [6] on both stages, followed by a <em>layer normalization</em> [7] procedure. The output of the encoder can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*hDiVSxnJFaYBtIUP" /></figure><p>where every layer in the encoder has dimension 512 and only the vector from the last layer is sent to the decoder.</p><p>The encoder <em>multi-head attention mechanism </em>is a generalization of the <em>basic attention mechanism </em>analyzed before. Previously, the vector was analyzed into a subspace of fixed dimension, but what if we could jointly use information from different representation subspaces at different positions? Well, multi-head attention does exactly this. You can think of it as dot-product attention computed by blocks, with each representation having a different size. As can be seen in <em>Figure 5, </em>after the computation of the normal <em>dot-products</em>, all the different <em>h </em>representations are concatenated and projected again. In the paper “<em>Attention is all you need” </em>they took <em>h=8, </em>with all of the scaled dot-product attention mechanisms having a projection size of 64 elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*APPY1Vv6Jesyx8Ri" /><figcaption><em>Figure 5: multi-head attention</em></figcaption></figure><p><em>Residual connections</em> [6] are used to solve the problem facing deep learning models, where the more layers they have, the more difficult it is to effectively do training. To deal with this issue, the idea is to feed the deeper layers of an untouched copy of data coming from the previous layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/0*ONSea5myFnoF7c3T" /><figcaption><em>Figure 6: residual connections</em></figcaption></figure><p>The <em>layer normalization</em>, instead, has the objective of speeding up the training of the neural network by reducing time for convergence. Differently from <em>batch normalization, </em>here the goal is to extract statistical information within each single pass before the nonlinearity takes place.</p><p>The <em>Decoder</em> resembles the <em>Encoder</em>: it’s made up of a stack of 6 layers but, in contrast to the <em>Encoder</em> that had 2 sub-layers, the <em>Decoder </em>sub-layers are <em>multi-head attention, fully-connected layers </em>and <em>masked multi-head attention </em>(apart from the common <em>residual connections </em>and <em>layer normalization</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*13PdzOdibnthmz1K" /><figcaption><em>Figure 7: the Transformer decoder</em></figcaption></figure><p>The <em>masked multi-head attention</em> is responsible for the <em>masked casual attention</em>, that is the mechanism that hides the features that belong to future states of the sequence. Thanks to this strategy, the decoder is both <em>autoregressive</em> and <em>causal</em>, that means that the generation of the current state is then not conditioned in any way by future states.</p><p>Now that we have understood how the Transformer works, it’s time to go deeper into BERT. BERT’s goal is to generate a language model: for this reason, compared to the Transformer architecture explained earlier, BERT only uses the encoder mechanism. The Transformer encoder learning mechanism is indeed bidirectional: it reads the input sequentially, left-to-right and right-to-left, allowing the model to learn the context of a word based on all of its surroundings. This architecture allows BERT to be trained for <em>Masked Language Model </em>(MLM) and <em>Next Sentence Prediction </em>(NSP) tasks.</p><p>The authors presented two BERT models: denoting with L the number of layers (i.e. Transformer blocks), with H the hidden size and A the number of <em>self-attention</em> heads, BERT <em>BASE </em>had (L=12, H=768, A=12) with a total number of 110M parameters while BERT <em>LARGE </em>had (L=24, H=1024, A=16), resulting in 340M parameters.</p><p>In order to make BERT suitable for a variety of down-stream tasks, the authors decided to structure the inputs to represent unambiguously a single sentence and a pair of sentences (e.g. a question and an answer). As explained previously, the Transformer requires the input sentence to be represented as tokens. In particular, BERT requires the sentence to be divided into tokens and to have the special token <em>[CLS]</em> at the beginning of the sequence and the special token <em>[SEP] </em>at the end. The sentence pairs are differentiated in two ways: first, the special token <em>[SEP] </em>is added between the two sentences; second, it’s added a learned embedding to every token indicating whether it belongs to sentence A or sentence B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*Zag8GRodc6CQLfcS" /><figcaption><em>Figure 8: BERT inputs</em></figcaption></figure><p>The Masked Language Model task requires some of the tokens from the input to be randomly masked during training, with the objective being for the model to predict the original vocabulary id of the masked work based only on its context. Unlike left-to-right language model pre-training, the MLM objective enables the representation to consider both the left and the right contexts, allowing the pre-training of a deep bidirectional Transformer.</p><p>To train BERT MLM the authors masked 15% of the words in each sequence, replacing them with the token <em>[MASK]</em>. The prediction is obtained by adding a final softmax (classification) layer on top of the Transformer encoder and computing the probabilities over the vocabulary.</p><p>Training for the Next Sentence Prediction task is fundamental for downstream tasks such as <em>Question Answering (QA) </em>and <em>Natural Language Inference (NLI).</em> Specifically, the training is performed in such a way that when choosing the sentences <em>A</em> and <em>B</em> for each pre-training example, 50% of the time <em>B</em> is actually the sentence that follows <em>A </em>(labeled as <em>isNext)</em> and 50% of the time a sentence is randomly chosen from the corpus (labeled as <em>notNext).</em> As shown in <em>Figure 9</em>, <em>C</em> is used for <em>next sentence prediction.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dH8lQXIbO58FXL05" /><figcaption><em>Figure 9: BERT pre-training and fine tuning</em></figcaption></figure><p><em>Figure 9 </em>also shows the <em>pre-training</em> and the <em>fine-tuning </em>procedures. While<em> pre-training</em> follows the standard procedures and involves the <em>BookCorpus (</em>800M words) and the <em>English Wikipedia </em>(2.5B words), the <em>fine-tuning</em> is straightforward thanks to the <em>self attention</em> mechanism in the Transformer. In contrast with the methodologies preceding the publication of BERT that encoded text pairs before applying bidirectional cross attention, BERT unifies the two stages, encoding a concatenated text pair with self-attention, including bidirectional cross attention between two sentences. Hence, for each task, all that is necessary is to plug-in the inputs and the outputs and to fine-tune all the parameters end-to-end. The<em> fine-tuning</em> procedure, compared to <em>pre-training, </em>is inexpensive.</p><h3><strong>The model</strong></h3><p>The aim of the model is to interpret sentences written in multiple languages, such as Italian, English, French, German and Dutch, and to return the result of a classification prediction. Specifically, the model must manage sentences that could eventually contain business specific keywords: these are words with a very specific meaning in the context of the business that is (probably) not known to the model, or the keyword itself has never been seen during BERT training, hence will not be present in the model vocabulary.</p><p>For these reasons, since retraining the whole BERT model is impractical, a system must be implemented to drive the model towards the correct classification, especially when the sentence contains a keyword. <em>Code snippet A</em> shows the model summary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdce2d4a476dcf297e7c6b6fced6c419/href">https://medium.com/media/fdce2d4a476dcf297e7c6b6fced6c419/href</a></iframe><p>As you can see, transfer learning is applied on BERT: its weights are non trainable and hence is used <em>out of the box.</em> After BERT there are two convolutional layers that generate a vector of 70 features that are concatenated with the vector of inputs with the sentence encoding respect to the keywords. The resulting vector is finally used for the classification by means of a softmax layer.</p><h3><strong>Package structure</strong></h3><p>The package structure is depicted in <em>Code snippet 1: </em>it is organised with the objective of separating the application logic for data transformation to the model definition and implementation as much as possible.Specifically, the file <em>configurations.py</em> is responsible for setting the program configurations <em>(</em>loading them from <em>config.yml)</em> while the module <em>connectors</em> defines the client connector to Google Firestore and the locations for Google Cloud Storage. The <em>datasetHandler</em> defines the object that is responsible for managing the data flow from the format received by the database to the one that is most suited for the application and defines the training, validation and test sets. The module <em>model</em> creates the machine learning model and contains the preprocessor, the object in charge of preprocessing the input examples in the format required by BERT. Finally, the file <em>training.py</em> is responsible for orchestrating the flow of data, both executing the training and testing model performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78b6dc251972c6622da619abdf7c6af4/href">https://medium.com/media/78b6dc251972c6622da619abdf7c6af4/href</a></iframe><h3><strong>The dataset handler</strong></h3><p>The dataset handler has the objective of managing the transformations of data format and of creating the training, validation and test sets. <em>Code snippet 2 </em>shows a section of dataset handler function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0957bcb15ee934d447074e3eaab7d650/href">https://medium.com/media/0957bcb15ee934d447074e3eaab7d650/href</a></iframe><p>The first step is about data management: the keyword data format is changed from the one obtained by the component connecting to Firestore, a dictionary with several unused keys, to a plain and simple list of all the keywords defined in the database.</p><p>Supervised training requires a dataset composed of pairs of examples and labels: while training, the model performs the predictions and updates its parameters with respect to the prediction errors. For this reason, DatasetHandler manages data conversion and associates each training example with the corresponding label.</p><p>The keywords, instead, are business-specific words whose meanings are probably unknown to the model, or the word could just be missing from the model vocabulary. It is important to properly handle this detail for two reasons. Firstly, if we don’t manage unknown keywords, when the string is preprocessed the unknown words are replaced with the special token ‘[UNK]’. Secondly, let’s suppose that the keyword is known to BERT, but that during its training the model learned that the meaning is different from the one intended by the business. In such a case, we need to make the model understand that the keywords are linked to a subset of training examples. Hence, the inputs are enriched with features with that objective: for each training example a categorical tensor is generated that maps whether the example contains the keyword. This vector will be used in the tailing neural network used for classification.</p><p>Now, we still have to split the dataset and create the training, validation and test sets: <em>Code snippet 3 </em>depicts these steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b777dfbfe6a39eb1f5a3ed2f53c44947/href">https://medium.com/media/b777dfbfe6a39eb1f5a3ed2f53c44947/href</a></iframe><h3><strong>The model implementation</strong></h3><p>As described in “<em>The model</em>” section, BERT requires the corpus to be preprocessed . Thanks to Tensorflow Hub, it’s possible to download the wrapper and easily execute the preprocessing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/462668a175fe57ca767594a926681582/href">https://medium.com/media/462668a175fe57ca767594a926681582/href</a></iframe><p>The implementation of the model is fairly simple. First, we have to download the pre-trained model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/896c5285c677db1ee6b40e3eab1a3f6b/href">https://medium.com/media/896c5285c677db1ee6b40e3eab1a3f6b/href</a></iframe><p>Then the custom deep learning model is defined by detailing the inputs and then using the Keras functional API to define the model structure. The first block is the BERT layer, from which is taken only the pooled output, a vector of dimension equal to 768, which is injected into a series of 2 dense layers with batch normalization. The output of the second dense layer is then concatenated to the input features mapping the keywords in the training examples. Finally, the resulting classification is obtained by means of a <em>softmax</em> activation function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/737933fd0bdf50a5a3e778bad31e82c2/href">https://medium.com/media/737933fd0bdf50a5a3e778bad31e82c2/href</a></iframe><p>The <em>train</em> function, responsible for training the model, is shown in <em>Code snippet 7.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da65e2e4925164359add298ee2ffb336/href">https://medium.com/media/da65e2e4925164359add298ee2ffb336/href</a></iframe><h3><strong>Putting it all together</strong></h3><p>Now that we have defined all the steps and the logic we need to put everything together by orchestrating the objects and the functions. After loading the configurations defined in a YAML file the model object, the preprocessor and the dataset handler are created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/238916cc37a65800ead3ac8f698cdd61/href">https://medium.com/media/238916cc37a65800ead3ac8f698cdd61/href</a></iframe><p>The dataset handler then transforms the data retrieved from the database, preprocesses the corpus and creates the training, validation and test sets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/024ecafdd65167bda75b443d9ea0dbec/href">https://medium.com/media/024ecafdd65167bda75b443d9ea0dbec/href</a></iframe><p>Finally, the model is built, trained and its performance is tested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e22bbbf57aa965fb8e94cdec970b2ca/href">https://medium.com/media/0e22bbbf57aa965fb8e94cdec970b2ca/href</a></iframe><h3><strong>The deployment</strong></h3><p>The model training is executed on Google AI Platform Training, a service specifically designed and optimized for training machine learning models. As depicted in the Dockerfile shown in <em>Code snippet 11, </em>the package is wrapped in a docker container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb0c2ada7365c605730c77cf364a476/href">https://medium.com/media/3bb0c2ada7365c605730c77cf364a476/href</a></iframe><p><em>Code snippet 12</em> is responsible for building the docker container and pushing it to the Google Container Registry, a repository of docker containers associated with the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e710e7797b3823bd95ba071117238e1b/href">https://medium.com/media/e710e7797b3823bd95ba071117238e1b/href</a></iframe><p>Once it is pushed to the Google Container Registry we are ready to run the deployment with Google Cloud Run. The script is shown in<em> Code snippet 16</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/517a270bc75d67c4897b06af999457cd/href">https://medium.com/media/517a270bc75d67c4897b06af999457cd/href</a></iframe><h3><strong>Conclusion</strong></h3><p>We have seen how to design and implement a deep learning model. We have also examined how to build a container for the training application, how to push it to Google Container Registry, and how to execute training on the Google AI Platform.</p><p>If you are interested in the description of the use case and the other articles in this series, click <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058">here</a>.</p><h3><strong>References</strong></h3><p>[1] Devlin, Jacob, et al. “Bert: Pre-training of deep bidirectional transformers for language understanding.” arXiv preprint arXiv:1810.04805 (2018).</p><p>[2] Vaswani, Ashish, et al. “Attention is all you need.” arXiv preprint arXiv:1706.03762 (2017).</p><p>[3] Goodfellow, Ian, et al. Deep learning. Vol. 1. №2. Cambridge: MIT press, 2016.</p><p>[4] Britz, Denny, et al. “Massive exploration of neural machine translation architectures.” arXiv preprint arXiv:1703.03906 (2017).</p><p>[5] Gehring, Jonas, et al. “Convolutional sequence to sequence learning.” International Conference on Machine Learning. PMLR, 2017.</p><p>[6] He, Kaiming, et al. “Deep residual learning for image recognition.” Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.</p><p>[7] Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. “Layer normalization.” arXiv preprint arXiv:1607.06450 (2016).</p><p>[Transformer images] <a href="https://ricardokleinklein.github.io/2017/11/16/Attention-is-all-you-need.html">https://ricardokleinklein.github.io/2017/11/16/Attention-is-all-you-need.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1004897347d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Machine Learning — Dashboard backend]]></title>
            <link>https://nicola-massarenti.medium.com/end-to-end-machine-learning-dashboard-backend-9f832949d591?source=rss-41a5d63158a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f832949d591</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Nicola Massarenti]]></dc:creator>
            <pubDate>Wed, 24 Mar 2021 05:31:00 GMT</pubDate>
            <atom:updated>2021-03-24T05:31:00.301Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>End-to-End Machine Learning — Dashboard backend</strong></h3><p>This article is the second of a series of articles on how to build an end-to-end machine learning pipeline for a chatbot AI that relies on a user-defined knowledge base. You can read about the description of the use case and the other articles in the series <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058">here</a>.</p><p>In this article you will read about the dashboard backend, the development details and how to deploy the package to Google Cloud Run, a highly scalable service for containerized applications.</p><p>You can explore the code at my <a href="https://github.com/nicolamassarenti/be-dashboard-bert-faqclass">GitHub</a> repository.</p><p><em>Disclaimer: I’m still a beginner at Golang and the software explained in this article is not complete and contains flaws that need to be solved to produce a real production application. If you are interested in extending the functionalities of this code or if you have any constructive criticism or feedback, please get in touch!</em></p><h4><strong>The technological stack and the design pattern</strong></h4><p>The backend is developed in <a href="https://golang.org/">Go</a><strong>, </strong>an open source programming language developed by Google.</p><p>The code is structured as detailed by Uncle Bob’s <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a> design pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*NWd4NCVHCzyPMKfU" /><figcaption>Figure 1: Clean architecture dependency rule</figcaption></figure><p>Uncle Bob’s Clean Architecture is based on the separation of concerns by the division of software into four main layers. They are described below from the inner to the outer circles:</p><ul><li><em>Entities: </em>encapsulate the enterprise business rules. The entities can be structures, functions or objects with methods. Entities are independent from the application and are software that implement concepts shareable with other enterprise use cases.</li><li><em>Use cases: </em>encapsulate the application specific business rules. Use cases manage data conversion and data flow to and from the entities.</li><li><em>Interfaces: </em>the layer that converts the data from the use cases and entities layer to the format required by some external source such as the database or the web.</li><li><em>Infrastructure: </em>the layer that is composed of frameworks, specific tools and drivers such as the database.</li></ul><p>The separation of concerns is enforced by the <em>dependency rule</em>: the dependencies of the modules must only point inwards. This means that the inner circles must know nothing about the outer circles: no module, no variable, no structure, no framework, no database or interface of any of the outer circles can be referenced by the respective inner circles. One question arises: why all this overhead? Because this software architecture allows us to completely decouple the business logic from the tools, the technologies from the core business concepts, ending up with a decoupled system with a clear separation of concerns.</p><p>With clean architecture and the dependency rule, if everything is respected, the software will be truly testable both with and without UI, database, web server or other external elements and it will be independent from frameworks, UI, databases and external actors. In addition, this architecture allows easy scaling and updating of the functionalities of the application. In general, the introduction of new functionalities or the modification of those already implemented shouldn’t imply the complete restructuring of the software or modifying the implementation of, for example, object <em>B,</em> if <em>B </em>is not the target of the intervention. Well, clean architecture and the dependency rule allows us to build software that goes in this direction: decoupling software allows us to be quick and effective in testing and updating code functionalities.</p><p>The following implementation took inspiration from both from Uncle Bob’s <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">article</a> and from the great Manuel Kissingler’s <a href="https://manuel.kiessling.net/2012/09/28/applying-the-clean-architecture-to-go-applications/">blog post</a>, from which this project and article take inspiration. Here you will read about my implementation of the backend for the bert-faqclass project and about the deployment on Google Cloud Run.</p><p>But first things first: let’s begin with the entities.</p><h4><strong>The Entities</strong></h4><p>The entities capture the domain concepts. The bert-faqclass project is built around two entity (domain) concepts that are at the root of the use case: the FAQs, because they are the elements that the AI has to learn, and the keywords, because they are context specific and, generally, unknown to the user.</p><p>The entity structures defined in the <em>domain</em> module are shown in <em>Code snippet 1:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d5ab403ce4c75a74b01322455249b41/href">https://medium.com/media/8d5ab403ce4c75a74b01322455249b41/href</a></iframe><p>In addition to the structs, there are operations that can be executed with the FAQs and the keywords, like adding or deleting a new FAQ. The interfaces of the operations are defined in the domain layer and will be implemented by the outer layers. The interfaces defined in the domain layer are shown in <em>Code snippet 2</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cc7a1c415b4ff2bf5ac673821b71d8c/href">https://medium.com/media/6cc7a1c415b4ff2bf5ac673821b71d8c/href</a></iframe><p><em>FaqRepository</em> and <em>KeywordsRepository</em> are interfaces: there is no reference to the technology nor the algorithms of the implementations as those belong to the interface layer that links the application to the database. This is how the <em>dependency rule</em> affects the software: an abstract interface does not refer to anything in the outer layer, its implementation is defined and injected by one of the outer layers that, in this case, is the use cases layer.</p><p>Taking inspiration from Manuel Kissingler’s <a href="https://manuel.kiessling.net/2012/09/28/applying-the-clean-architecture-to-go-applications/">blog post</a>, let’s clear out the three w-s of the interfaces: where it is used, where its interface is and where its implementation is. <em>FaqRepository </em>and <em>KeywordRepository</em> interfaces belong to the entities layer, are used by the use cases layer and the implementations belong to the interfaces layer.</p><h4><strong>The Use Cases</strong></h4><p>Use cases implement the application logic and must depend only on the functions, objects and structures of the use cases layer and of the domain layer. In addition, since we want to decouple each of the layers from the others, use cases modules redefine objects defined in inner modules to make them compliant with use cases needs. <em>Code snippet 3 </em>shows <em>use cases</em> structures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a861eaceacd8e5a91cf539d9b395edab/href">https://medium.com/media/a861eaceacd8e5a91cf539d9b395edab/href</a></iframe><p>Here the use cases <em>Faq </em>and the <em>Keyword</em> structs are identical to those of the domain layer. One question naturally arises: why should we define another struct, identical to the one of the inner circle layer that, as stated by the dependency rule, could be “legally” imported? Well, because we want decoupled software! Indeed, even though this example does not require us to define a struct different to that of the domain layer, in general it’s good practice to decouple data: our application could evolve and we may be required to create new properties to develop our application logic in ways that are different from business logic (shared by all the business applications): the domain layer is application independent, while use cases are application specific.</p><p>The use cases package also defines the <em>Logger</em> interface<em>. </em>Here we declare only the functions that we expect the logger to have, the implementation will be in charge of one of the outer layers. This way the application is agnostic with respect to the technology, the drivers, the frameworks and the implementation of the logger: we could easily change it by creating a new logger with these methods, no code is involved in the “switch” other than the logger itself.</p><p>Here two other structs are also defined that point to the domain layer: <em>KnowledgeBaseInteractor </em>and <em>KeywordsInteractor</em>. These are the structures that wrap the loggers (that, in this case, are the same object) and the Repository handlers whose interfaces are defined in the domain layer and implemented in the interfaces layer.</p><p>Now let’s analyse the implementation of the FaqRepository, defined in the domain layer as an interface, shown in <em>Code snippet 4:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/355508b2d1b35e40cc019148beb56a79/href">https://medium.com/media/355508b2d1b35e40cc019148beb56a79/href</a></iframe><p>As stated by Uncle Bob, the role of use cases is just to develop the application logic and to orchestrate data flow from interfaces to the domain, and vice-versa. In <em>Code snippet 4</em> it can easily be noticed that the use cases layer just acts as a mediator between domain and interfaces layer: it moves things, orchestrates the logic and changes data formats.</p><p>The use cases layer also manages data flow for keywords. As an example, the use case function <em>Keywords()</em>, responsible for returning all the keywords, is shown in <em>Code snippet 5:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b765443ec4827b0737acad936736e23/href">https://medium.com/media/9b765443ec4827b0737acad936736e23/href</a></iframe><h4><strong>The Interfaces</strong></h4><p>Interfaces are a set of adapters that modify the data formats of the use cases and domain layers to those requested by some external agent, such as a database or the web. All the logic for data management for the external agent must be restricted to this layer: no code from the circles within this one should know anything at all about anything from the circles surrounding this layer. Indeed, if in the future we want to change the database from NoSQL to SQL, by respecting the dependency rule we will only have to update the interfaces and the drivers; the use cases’ and the domain software will get no updates because they knew nothing about the database and no dependencies from external circles existed.</p><p>In this layer are also defined the interfaces for the logger: the implementation doesn’t belong to this layer because the technology/drivers belong to the infrastructure layer. The definition of the interfaces are shown in <em>Code snippet 6.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8b971bcb39e4d6b9e188efa189fec6/href">https://medium.com/media/5c8b971bcb39e4d6b9e188efa189fec6/href</a></iframe><p>The backend must be accessible from the web: the interfaces layer handles the software to manage the interactions with the web. The web service module for the keywords and the knowledge base are more or less the same: they orchestrate web requests, make use of use cases APIs and define the answers for web requests. <em>Code Snippet 7</em> shows the types defined for the web service in the interfaces layer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f71f59d50279f03c30c4a0677ed6ff1/href">https://medium.com/media/1f71f59d50279f03c30c4a0677ed6ff1/href</a></iframe><p>Here you can notice how injection is used to handle dependencies: <em>KnowledgeBaseInteractor</em> and <em>KeywordsInteractor</em> are interfaces that are injected with use cases which are defined in the entities layer. One important benefit in applying the dependency rule is, as an example, that <em>KnowledgeBaseInteractor </em>could be easily mocked in the unit tests, which makes the web service handler testable in isolation, thus we could test only the behaviour of the web service handler itself.</p><p><em>Code snippet 8 </em>shows the web service functions to manage keywords APIs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94529704b4b2484174e4a2f2488e9155/href">https://medium.com/media/94529704b4b2484174e4a2f2488e9155/href</a></iframe><p>Each web service method implements some very basic logic: they log the request, check if the query parameters are in the expected format, set the C.O.R.S. header, access use cases functions and finally build the answers. Indeed, they don’t do much and this is the point! Interfaces, if they are implemented as stated by Clean Architecture principles, just transport and translate data between layers, making the REST request unrecognizable to other layers.</p><p>Now that we have a working business domain, the orchestration of the use cases and an accessible entry point for web requests, we only need to implement the algorithms to make the software capable of saving data somewhere, which, in this case, is a database. This is done by creating the concrete implementations of the abstract repository interfaces of our domain and use cases layers. The implementation of the repository is indeed a matter for the interfaces layer because it’s an intermediation between the low-level point of view of outer infrastructure layer and the high-level business oriented point of view of the inner layers.</p><p>Once again we need to make sure that we don’t violate the dependency rule: the implementation of the repositories will depend on the infrastructure software that connects our application to Google’s Firestore NoSQL database. It’s not that the repository software is not aware that it’s using a NoSQL database. It’s rather that it implements only the high-level logic, translates data from/to the infrastructure and use cases layers, and ignores all the low-level operations required to “speak” with the database, such as instantiating the client, holding timeouts and so on and so forth. Therefore, our repository will take care of all the high-level operations and will be kept in the dark about all those nasty infrastructural details. Once again, the repository code for the knowledge base and the keywords is more or less the same and, to avoid replicating lists of boringly identical codes, in <em>Code snippet 9</em> is shown only the implementation of knowledge base repositories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09e050da77b2098d3434aaee5341eb67/href">https://medium.com/media/09e050da77b2098d3434aaee5341eb67/href</a></iframe><p>Up to now we have defined only the implementation of the repositories but we don’t yet have a handler at our disposal. Well, no worries, it’s easy: <em>Code snippet 10 </em>comes in to help: here all the handlers required by the software are defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6827203c0e9dd7ded334ce6e1ea6874/href">https://medium.com/media/d6827203c0e9dd7ded334ce6e1ea6874/href</a></iframe><h4><strong>The Infrastructure</strong></h4><p>Finally, we are ready to discuss the very outer layer, the infrastructure layer. As explained in the chapter<em> “The technological stack and the design pattern”</em>, this layer is about the low-level, often the driver/client dependent logic, software of our application. Our application requires this layer for two reasons: the logger is application dependent, indeed, it uses an external package called <a href="http://github.com/sirupsen/logrus">logrus</a>, and the database connection requires low-level logic.</p><p>Let’s start with <em>Code snippet 11</em>, which implements the logger:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca6001ef17e946d8e4090e8a946452f/href">https://medium.com/media/1ca6001ef17e946d8e4090e8a946452f/href</a></iframe><p>The low-level infrastructural code required to manage Firestore connections is depicted in <em>Code snippet 12</em>. Here, there is no implementation of application and business logic: the data received and returned by this implementation is in a very basic format; a <em>map[string]interface.</em> This is because the responsibility for changing data format<em> </em>belongs to the inner interface layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea04baa69e9e35cc5921e3fed742b0ef/href">https://medium.com/media/ea04baa69e9e35cc5921e3fed742b0ef/href</a></iframe><h4><strong>Putting it all together</strong></h4><p>Now that we have all the pieces, it’s just a matter of putting things together. We have to deal with some construction work because of our use of the dependency rule. The repositories must be injected with the db handlers and, in turn, the interactors must be injected into the web service handler. Finally, the http server must be started. <em>Code snippet 13</em> shows these steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbea753043b87efe049e71a2d661d557/href">https://medium.com/media/dbea753043b87efe049e71a2d661d557/href</a></iframe><p><strong>The deployment</strong></p><p>The backend is deployed using Google Cloud Run. In order to use this service, it is necessary to build a container and the technology used is Docker. The Dockerfile is shown in <em>Code snippet 14</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a0aed5860027f907e5e923e560ac11e/href">https://medium.com/media/9a0aed5860027f907e5e923e560ac11e/href</a></iframe><p>The docker container is created by means of a build stage and a production stage. Given the definition of the Dockerfile, <em>Code snippet 15</em> is responsible for building the docker container and pushing it to the Google Container Registry, a repository of docker containers associated with the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29948cdcb43c8c97d53a6002adebd535/href">https://medium.com/media/29948cdcb43c8c97d53a6002adebd535/href</a></iframe><p>Once it is pushed to Google Container Registry we are ready to run the deployment with Google Cloud Run. The script is shown in<em> Code snippet 16</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7718a9b997cae794848b7f4704de95a8/href">https://medium.com/media/7718a9b997cae794848b7f4704de95a8/href</a></iframe><p><strong>Conclusions</strong></p><p>We have seen how to build a backend for a very simple application in Golang, where the code architecture is built according to Clean Architecture principles and follows the dependency rule. We have also examined how to build a container for the web application, how to push it to Google Container Registry, and how to deploy it with Google Cloud Run.</p><p>If you are interested in the description of the use case and the other articles in this series, click <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f832949d591" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-end Machine Learning — Dashboard frontend]]></title>
            <link>https://nicola-massarenti.medium.com/end-to-end-machine-learning-dashboard-frontend-4b8bf6645d9?source=rss-41a5d63158a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b8bf6645d9</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Nicola Massarenti]]></dc:creator>
            <pubDate>Tue, 16 Mar 2021 20:17:27 GMT</pubDate>
            <atom:updated>2021-03-16T20:17:27.105Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>End-to-end Machine Learning — Dashboard frontend</strong></h3><p>This article is the first of a series of articles on how to build an end-to-end machine learning pipeline for a chatbot AI that relies on a user-defined knowledge base. You can read about the description of the use case and the other articles in the series <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058">here</a>.</p><p>In this article, you will read about the dashboard frontend, the development details, and how to deploy the package to Google Cloud Run, a highly scalable service for containerized applications.</p><p>You can explore the code at my <a href="https://github.com/nicolamassarenti/fe-dashboard-bert-faqclass">GitHub</a> repository.</p><h4><strong>Technological framework: Vue.js</strong></h4><p>The frontend has been developed by making use of <a href="https://vuejs.org/">Vue.js</a>, a progressive javascript framework for front end development.</p><p>Why Vue.js? Because it’s easy to use! Being a progressive framework, it saves you time and effort.</p><p>Two main Vue.js components are the <em>views </em>and the <em>components</em>. The <em>views </em>are used from <a href="https://router.vuejs.org/">Vue Router</a> when switching between web pages as they generally function as pages, while the <em>components</em> are usually reusable elements and are generally used by the <em>views.</em></p><p>The router defined for the dashboard frontend is depicted in <em>Code snippet 1</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b889235e21cc43bcc10ff4d2c11feacb/href">https://medium.com/media/b889235e21cc43bcc10ff4d2c11feacb/href</a></iframe><h4><strong>Dashboard homepage</strong></h4><p>The dashboard homepage is the first page the user lands on. It is located at path <em>“/”</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkIn9X8hi_3lDQ-u1f-NmA.png" /><figcaption><em>Figure 1: Home page</em></figcaption></figure><p>It is composed of a routing bar and a simple welcome message followed by three cards: one for the Knowledge Base (KB) page, one for the keywords page, and one for the training panel page.</p><p>The three cards are located in a single row and are contained in four bootstrap columns. Consider, for example, the card linking to the KB page shown in <em>Figure 2</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teNoe_ohm0b769lTbHPrVQ.png" /><figcaption><em>Figure 2: Home page cardS detail</em></figcaption></figure><p>The code that made this card possible is shown in <em>Code snippet 2</em>,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f83c009fe6b511b12b86e11aea716596/href">https://medium.com/media/f83c009fe6b511b12b86e11aea716596/href</a></iframe><p>where, when clicked, the router changes the view to the one corresponding to the path “<em>/kb”</em> that, as shown in <em>Code snippet 1</em>, corresponds to the Knowledge Base view.</p><p>The other cards are not shown here but the logic is the same as that shown in <em>Code snippet 2.</em></p><h4><strong>Knowledge Base View</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIsfFHkA88MrCOfJgj8M3g.png" /><figcaption><em>Figure 3: knowledge base view</em></figcaption></figure><p><em>KBView, </em>the Knowledge Base view, is the page that gives the user an overview of all the FAQs. By clicking on one of the three buttons associated with each FAQ, the admin user can change the training status (whether a FAQ is used for training or not), access the details of a FAQ, or delete a FAQ. It is located at the path “<em>/kb”</em>.</p><p>The javascript code is shown in <em>Code snippet 3</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30e20b2729115492b73d384c57f776da/href">https://medium.com/media/30e20b2729115492b73d384c57f776da/href</a></iframe><p>As can be seen, when the page is mounted four listeners are activated:</p><ol><li><em>createNewFaq:</em> associated with the component <em>CreateFaqComponent, </em>used for creating a new FAQ</li><li><em>deleteFaq:</em> associated with the event of deleting a FAQ</li><li><em>changeTrainingStatus</em>: associated with the event of changing the training status of a FAQ</li><li><em>faqDetails: </em>associated with the user request to see the details of a FAQ</li></ol><p>These listeners are deactivated before the <em>KBView</em> page is destroyed because of a change of view (if you want to know more about Vue.js lifecycle you can read <a href="https://www.digitalocean.com/community/tutorials/vuejs-component-lifecycle">this</a> article). It is important to destroy the listeners because they are no longer needed after changing view and, also, because otherwise an error like “<em>Navigating to current location (“/faq/new”) is not allowed”, name: “NavigationDuplicated</em>” would occur.</p><p>The event <em>createNewFaq</em> is created by component <em>CreateFaqComponent</em>, that in <em>KBView</em> is the button located at the top-right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*4gAAKciP3iFtsWuOCIvWjw.png" /><figcaption><em>Figure 4: CreateFaqComponent with hover activated</em></figcaption></figure><p>The code of <em>CreateFaqComponent </em>is shown in <em>Code snippets 4 </em>and <em>5</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc8095dab9d3d0b7717accbfe126fdf/href">https://medium.com/media/8fc8095dab9d3d0b7717accbfe126fdf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f0ba38a966ea535c3033efe2ff41c5a/href">https://medium.com/media/6f0ba38a966ea535c3033efe2ff41c5a/href</a></iframe><p>The events <em>deleteFaq, changeTrainingStatus, </em>and<em> faqDetails</em> are generated by the <em>FaqPreviewComponent</em>, which is a component that previews a FAQ and emits the events managed by <em>KBView. </em>The Knowledge Base view shows the FAQs by means of code shown in<em> Code snippet 6</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ce5debcebc15556e7b6668283f3c9d/href">https://medium.com/media/e4ce5debcebc15556e7b6668283f3c9d/href</a></iframe><p>The detail of a <em>FaqPreviewComponent</em> is shown in <em>Figure 5</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgdSvGmvyA4VWCG4KYIjOg.png" /><figcaption><em>Figure 5: FaqPreviewComponent</em></figcaption></figure><p>and the buttons associated to each <em>FaqPreviewComponent </em>are shown in <em>Figure 6</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*pagtAoCJSTkRd0RDmvpAWg.png" /><figcaption><em>Figure 6: event buttons of FaqPreviewComponent</em></figcaption></figure><ul><li>Button 1: creates the event <em>ChangeTrainingStatus</em>. It is active (green) if the FAQ is used for training the machine learning model, otherwise is inactive (grey).</li><li>Button 2: creates the event <em>DeleteFaq</em>, used for deleting the FAQ</li><li>Button 3: creates the event <em>FaqDetails</em>. When pressed shows all the details (training phrases, answers) of the FAQ by changing view to <em>FaqDetailView</em></li></ul><p>The logic with which the events are managed is shown schematically in <em>Figure 7</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*OKN18t1UuwE7z5aSMyKZTA.png" /><figcaption>Figure 7: KBView events logic</figcaption></figure><p>All the atomic requests are managed at the level of <em>KBView </em>by means of the event listeners. With this strategy, only the KBView<em> </em>component is responsible for the requests instead of enabling each of the <em>FaqPreviewComponent</em>s to send REST requests to the backend.</p><h4><strong>FAQ Detail View</strong></h4><p><em>FaqDetailView </em>is responsible for showing all the details of a specific FAQ. It is located at path “<em>/faq?id=&lt;ID&gt;”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbDBhRsER-X4zmx-whViig.png" /><figcaption>Figure 8: FaqDetailView</figcaption></figure><p>This view is composed of four main components:</p><ul><li><em>MainQuestionComponent</em>: Located on the top-left side of the page. Responsible for editing the definition of the main question.</li><li><em>FaqCommandsComponent:</em> Located on the top-right side of the page. Its functionalities are similar to those of <em>KBView</em>: changing training status, and deleting and saving the FAQ.</li><li><em>SwitcherComponent:</em> Located below the <em>MainQuestionComponent</em>. A switch that allows the training examples or the answers to be displayed.</li><li><em>FaqLanguageExamplesComponent-</em>s: One for each language managed by the chatbot. Each component is associated with only one language, contains a set of training examples in that language, and allows the deletion and addition of examples. In addition, it is possible to hide the training examples by clicking on the eye icon on the top-right side of the component.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAa272TGmH3ThcxnTclJ3Q.png" /><figcaption>Figure 9: Detail of the training examples, with the set of italian training examples hidden</figcaption></figure><p>The html code for the <em>FaqDetailView </em>is depicted in <em>Code snippet 7</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd1b542a50feddc071f674cdf90cf941/href">https://medium.com/media/dd1b542a50feddc071f674cdf90cf941/href</a></iframe><p>Similarly to the event handling logic described in the <em>KBView section</em>, for this view there is also a single point of creation for REST requests.</p><h4><strong>Keywords</strong></h4><p>Keywords are displayed in <em>KeywordsView, </em>a component that has the sole objective of allowing the user to create, edit or delete keywords. The view is displayed in <em>Figure 10:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pNAx43PaI7LXkthG" /><figcaption>Figure 10: Keywords view</figcaption></figure><p>Similarly to <em>KBView</em>, in <em>KeywordsView </em>there exists the component <em>CreateKeywordComponent </em>located at the top-right side of the page, responsible for creating a new Keyword.</p><p>Each keyword is contained in a <em>KeywordComponent</em> that allows the user to modify or delete the keyword it is associated to. Additionally, for <em>KeywordsView</em>, all the logic for REST request is managed at the level of the view by means of the event handlers that intercept the tokens emitted by the <em>KeywordsComponent</em>s.</p><h4><strong>Deployment</strong></h4><p>The front end is deployed using Google Cloud Run, an highly scalable service for containerized applications.</p><p>In order to use this service it is necessary to build a container and the technology used is Docker. The docker file is shown in <em>Code snippet 8</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa340e62fda575e9945c05cac42dbf80/href">https://medium.com/media/fa340e62fda575e9945c05cac42dbf80/href</a></iframe><p>The docker container is created in two stages: a build stage and a production stage. In the first, the application is created and the required packages are installed; in the latter, instead, nginx is used to serve the pages.</p><p>Given the definition of the Dockerfile, <em>Code snippet 9</em> is responsible for building the docker container and pushing it to the Google Container Registry, a repository of docker containers associated with the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaa3c51cdbc8b604707c4c25364d8b21/href">https://medium.com/media/eaa3c51cdbc8b604707c4c25364d8b21/href</a></iframe><p>Once it is pushed to Google Container Registry we are ready to run the deployment with Google Cloud Run. The script is shown in<em> Code snippet 10</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/758a9fe71228e418fc95a4585cdf45c3/href">https://medium.com/media/758a9fe71228e418fc95a4585cdf45c3/href</a></iframe><p>Once the script has been executed, Google will manage 100% of the traffic and the scalability of the application.</p><h4><strong>Conclusions</strong></h4><p>We have seen how to use Vue.js to develop a simple dashboard front end and how to manage the events to have a single point of responsibility for REST requests. We have also examined how to build a container for the web application, how to push it to Google Container Registry, and how to deploy it with Google Cloud Run.</p><p>If you are interested in the description of the use case and the other articles in this series, click <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b8bf6645d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Machine Learning — bert-faqclass]]></title>
            <link>https://nicola-massarenti.medium.com/end-to-end-machine-learning-bert-faqclass-81fd07d24058?source=rss-41a5d63158a------2</link>
            <guid isPermaLink="false">https://medium.com/p/81fd07d24058</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deeplearing]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Nicola Massarenti]]></dc:creator>
            <pubDate>Tue, 16 Mar 2021 20:13:56 GMT</pubDate>
            <atom:updated>2021-04-01T07:02:58.672Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>End-to-End Machine Learning — The Intro</strong></h3><p>This article is the introduction to a series of articles on how to build an end-to-end machine learning pipeline for a chatbot AI that relies on a user-defined knowledge base.</p><p>This article contains an overview of the use case for this project. If you would like to skip to a specific section, please click the appropriate link below.</p><ol><li>Dashboard front-end: <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-dashboard-frontend-4b8bf6645d9">click here</a></li><li>Dashboard back-end: <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-dashboard-backend-9f832949d591">click here</a></li><li>Deep learning model: <a href="https://nicola-massarenti.medium.com/end-to-end-machine-learning-machine-learning-model-f1004897347d">click here</a></li></ol><p><em>Note: this is intended to be a proof-of-concept (p.o.c.): there are still huge areas for improvement and many interesting features that might be added. If you are interested in extending the functionalities of this project, please feel free to contact me!</em></p><h4><strong>The Why</strong></h4><p>The motivation behind the development of this project is mainly driven by curiosity: I wanted to learn a new programming language (golang, used for the dashboard backend) as well as develop a solution that involved machine learning and other different technologies.</p><p>With such goals in mind, I decided to develop a NLP (natural language processing) oriented project, to code from scratch both the front- and backends of the solution and, while doing so, to explore programming languages, frameworks, and software architectures not yet known to me.</p><h4><strong>The Use Case</strong></h4><p>The bert-faqclass project has been developed with the aim of building a machine learning end-to-end solution. Its AI is able to answer in detail questions written in multiple languages and to manage context specific concepts characterised by words not natively known to the AI.</p><p>The key feature of the project is that the admin of the chatbot can control the knowledge base (KB) of the AI and define a set of business-related context keywords, with keyword meanings strictly dependent on the business for which the KB has been defined. The knowledge base is composed of a set of FAQs. Each FAQ is defined in several languages using a set of semantically similar training examples and their respective answers.</p><p>The architecture of the deep learning model adapts both to the number of FAQs and to the keywords automatically, without requiring human intervention.</p><p>The KB is retrieved during the training of the model. <a href="https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/3">BERT multilingual</a> was the base model chosen to undergo transfer learning on a custom network that is able to classify the input sentence into one of the knowledge base FAQs.</p><p>The architecture of the solution is depicted in <em>Figure 1</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*pZ11LlzwbowzKxmdz4ZDSw.png" /><figcaption>Figure 1: software architecture</figcaption></figure><p>As can be seen, there are three main macro-components:</p><ul><li>Dashboard</li><li>MLOps</li><li>Chatbot</li></ul><h4><strong>Dashboard</strong></h4><p>The dashboard allows the KB admin to manage the FAQs, the examples, and the keywords known to the AI. The dashboard is the tool that allows the KB to be managed by the KB admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBWQ6Ev1MEy2hXdKUu0JfQ.jpeg" /></figure><p>The dashboard is composed of a <em>front-end</em> and a <em>back-end</em>. The front-end serves the webpages to the user. The back-end is responsible for all CRUD (Create, Replace, Update, and Delete) operations, and manages the connections to Firestore, a Google Cloud Platform (GCP) No-SQL database that contains the FAQs and their training examples, answers, and keywords. The dashboard also allows the invocation of the model training.</p><p>Both components are served with Google Cloud Run, a highly scalable service for the deployment of containerized applications.</p><h4><strong>MLOps</strong></h4><p>MLOps includes the functions for training a new model, saving it, and serving it to make predictions. The GCP component used for these operations is AI Platform training and prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8YOT-eR-xG4ntL3CMWA8Xw.png" /></figure><p>The machine learning model architecture is parametric with respect to the number of keywords and FAQs. Once the model is successfully trained, the model is saved in Google Cloud Storage.</p><h4><strong>Chatbot</strong></h4><p>The Chatbot component is concerned with the interactions with the user. It is composed of a front-end, which serves the pages to the user, and a backend, which manages the logic of the conversation and which connects to AI Platform prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L09uOV4KNs_J6lA1klZRZw.png" /></figure><p>In the following articles you will gain a better understanding of the solution and of the development choices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81fd07d24058" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>