<?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 Team Datatonic on Medium]]></title>
        <description><![CDATA[Stories by Team Datatonic on Medium]]></description>
        <link>https://medium.com/@mlteamdt?source=rss-31d0e4dc6e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4CcyxS4vn9yd4SSo2anNZA.png</url>
            <title>Stories by Team Datatonic on Medium</title>
            <link>https://medium.com/@mlteamdt?source=rss-31d0e4dc6e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:50:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mlteamdt/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[Configuring Cloud Build to use Static External IP Addresses]]></title>
            <link>https://blog.montrealanalytics.com/configuring-cloud-build-to-use-static-external-ip-addresses-bb3f80b9ce15?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb3f80b9ce15</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ip-address]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cloud-build]]></category>
            <category><![CDATA[google-cloud]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 10:14:29 GMT</pubDate>
            <atom:updated>2023-02-16T10:14:29.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6C8YgRDp5rgDC4mj" /></figure><p><strong>Authors: </strong><a href="https://www.linkedin.com/in/kumail-kermalli-583540138/"><strong>Kumail Kermalli, DevOps Engineer</strong></a><strong> and </strong><a href="https://www.linkedin.com/in/pooladkhay/"><strong>Mohammad Pooladkhay, DevOps Engineer</strong></a></p><h4><strong>Background</strong></h4><p><a href="https://cloud.google.com/build">Cloud Build</a> is Google Cloud’s serverless CI/CD platform. First launched in 2016, it allows users to execute builds in a fully-managed environment. Each build is made up of a series of steps and each runs in a specified Docker container. This allows a degree of customisation, as users can choose to use either <a href="https://github.com/GoogleCloudPlatform/cloud-builders">Pre-Built Images</a> or create their own to run their jobs on.</p><p>In 2021, an additional layer of customisation was added with the launch of <a href="https://cloud.google.com/build/docs/private-pools/private-pools-overview">“Private Pools”</a>. This allowed the setup of dedicated worker pools to execute a build, with the ability to access resources in a Virtual Private Cloud (VPC) network. Other useful customisation options include an increase in the number of concurrent builds allowed, greater machine type choice and the ability to disable access of your private pool to the public internet.</p><p>However, a key functionality that is not available in Cloud Build (at the time of writing, February 2023) is the ability to set a static external IP address to your build, even if it is running in a private pool. This would be extremely useful for some users as it would allow them to whitelist worker pool addresses in external providers they may need to access for builds.</p><p>Unfortunately, a Serverless VPC Connector and/or Cloud NAT cannot be used here due to private worker pools being located in a Google-owned Virtual Private Cloud network called the service producer network, peering into a project VPC (see Figure 1). Whilst Google does provide a <a href="https://support.google.com/a/answer/10026322?hl=en">list of external IP addresses</a> Google Cloud resources use, whitelisting all of them is impractical.</p><h4><strong>Introduction</strong></h4><p>Adding the native ability to assign an external IP address to Cloud Build is a <a href="https://issuetracker.google.com/issues/197128153">feature request</a> on Google’s Issue Tracker, so we may see this implemented in the near- to mid-term. However, in the interim, an alternative solution is needed. <strong>Read on to learn how to assign a static external IP address to a Cloud Build instance through the use of a proxy server hosted on Google Compute Engine.</strong></p><p>The aim is to prevent Cloud Build instances from directly reaching out to the public internet over IP addresses we do not know the range of. Instead, a VM with a static IP address will act as their Proxy Server and all the communications between the VM and Build instances will be via private IP addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Jjugu4UC4ZS1FdeINQsCQ.png" /><figcaption>Fig 1: Connecting our Cloud Build instance to an external static IP address</figcaption></figure><h4><strong>Tutorial</strong></h4><p><strong>TLDR;</strong> Assuming you already have a VPC network and required IAM permissions:</p><ol><li>Enable the Cloud Build and the Service Networking APIs</li><li>Create a VPC network (if you don’t already have one)</li><li>Allocate a named IP range in your VPC network</li><li>Create a private connection to the service producer network</li><li>Create a new Worker Pool</li><li>Create a subnetwork for the VM</li><li>Allocate a Static IP address to be added to the VM</li><li>Create a VM instance</li><li>Set up an HTTP Proxy Server on the VM</li><li>Add Firewall Rules allowing Ingress Traffic to the Proxy only via its private IP address</li><li>Instruct Cloud Build instances to use the VM’s private IP address as Proxy</li></ol><p>If you wish to use the Google Cloud Console or gcloud CLI to achieve the goal, the process is well documented on both the <a href="https://cloud.google.com/build/docs/private-pools/set-up-private-pool-to-use-in-vpc-network">Networking</a> and <a href="https://cloud.google.com/build/docs/private-pools/create-manage-private-pools">Cloud Build</a> components as well as <a href="https://cloud.google.com/compute/docs/instances/create-start-instance">VM instances</a>. In this tutorial, we will demonstrate how to use Terraform to implement the above steps.</p><p>Source code is available at <a href="https://github.com/teamdatatonic/blog-cloud-build-static-ip">https://github.com/teamdatatonic/blog-cloud-build-static-ip</a> with comments indicating each step inside the main.tf file.</p><ol><li><strong>Enabling the Cloud Build and the Service Networking APIs</strong></li></ol><pre>resource &quot;google_project_service&quot; &quot;enable_cloud_build&quot; {<br>  project = var.project_id<br>  service = &quot;cloudbuild.googleapis.com&quot;<br>  disable_dependent_services = true<br>}<br>resource &quot;google_project_service&quot; &quot;enable_service_networking&quot; {<br>  project = var.project_id<br>  service = &quot;servicenetworking.googleapis.com&quot;<br>  disable_dependent_services = true<br>}</pre><p><strong>2. Creating a VPC network</strong></p><p>Almost every resource in Google Cloud requires a VPC network to be added to.</p><pre>resource &quot;google_compute_network&quot; &quot;vpc_network&quot; {<br> project                 = var.project_id<br> name                    = var.vpc_network_name<br> auto_create_subnetworks = false<br> mtu                     = 1460<br>}</pre><p><strong>3. Allocating a named IP range In your VPC network</strong></p><p>We need to allocate a named private IP range so that we can later use it to peer our VPC network to the VPC network where Cloud Build Private Pools reside (Service Producer Network).</p><p>Cloud Build reserves the IP range 192.168.10.0/24 for the Docker bridge network. When allocating the IP ranges for resources in your project, Google recommends selecting a range outside of 192.168.10.0/24 in cases when Cloud Build builders access these resources.</p><pre>resource &quot;google_compute_global_address&quot; &quot;named_private_ip&quot; {<br> provider      = google-beta<br> name          = var.named_private_ip_name<br> project       = var.project_id<br> purpose       = &quot;VPC_PEERING&quot;<br> address_type  = &quot;INTERNAL&quot;<br> network       = google_compute_network.vpc_network.name<br> address       = var.named_private_ip<br> prefix_length = 24<br>}</pre><p><strong>4. Creating a private connection to the service producer network</strong></p><p>This will create a private connection between our VPC network and Google’s own VPC network where our private worker pool will be hosted, i.e., the service producer network, using the private IP range we just allocated.</p><p>This step depends on the last step since we have referenced <strong>named_private_ip</strong>’s name.</p><pre>resource &quot;google_service_networking_connection&quot; &quot;service_producer_connection&quot; {<br> network                 = &quot;projects/${var.project_id}/global/networks/${google_compute_network.vpc_network.name}&quot;<br> service                 = &quot;servicenetworking.googleapis.com&quot;<br> reserved_peering_ranges = [google_compute_global_address.named_private_ip.name]<br>}</pre><p><strong>5. Creating a new Worker Pool</strong></p><p>When creating a worker pool, we want to prevent the Cloud Build instances from directly reaching out to the public internet and instead proxy all of their traffic through a Proxy server that we will host on a VM instance.</p><p>To achieve this, we set <strong>no_external_ip</strong> to <strong>true</strong> so that the instances won’t have direct access to the public internet. Then, we set the <strong>peered_network</strong> to our VPC network in which we created a private connection to the service producer network.</p><p>Finally, we need to make sure that the creation of the Worker Pool happens after the connection to the Service Producer Network by explicitly adding the <strong>depends_on</strong>.</p><pre>resource &quot;google_cloudbuild_worker_pool&quot; &quot;private_worker_pool&quot; {<br> name     = var.private_worker_pool_name<br> location = var.region<br> project  = var.project_id<br> worker_config {<br>   disk_size_gb   = 100<br>   machine_type   = &quot;e2-medium&quot;<br>   no_external_ip = true<br> }<br> network_config {<br>   peered_network = &quot;projects/${var.project_id}/global/networks/${google_compute_network.vpc_network.name}&quot;<br> }<br> depends_on = [google_service_networking_connection.service_producer_connection]<br>}</pre><p><strong>6. Creating a subnetwork for the VM</strong></p><p>We need a subnetwork with a private range that we define so that later we can assign a private IP address from that range to the VM by which Build instances will communicate with the VM.</p><pre>resource &quot;google_compute_subnetwork&quot; &quot;proxy_subnet&quot; {<br> name                     = &quot;${google_compute_network.vpc_network.name}-proxy-subnet&quot;<br> ip_cidr_range            = var.vm_subnet_range<br> network                  = google_compute_network.vpc_network.name<br> region                   = var.region<br> private_ip_google_access = false<br> project                  = var.project_id<br>}</pre><p><strong>7. Allocating a Static IP address to be added to the VM</strong></p><p>This will be the public IP address for the Cloud Build instances.</p><pre>resource &quot;google_compute_address&quot; &quot;static_ip&quot; {<br> name         = var.static_ip_name<br> project      = var.project_id<br> region       = var.region<br> address_type = &quot;EXTERNAL&quot;<br> network_tier = &quot;STANDARD&quot;<br>}</pre><p><strong>8. Creating a VM instance</strong></p><p>This VM will be our Proxy Server. Cloud Build instances talk to it via its private IP then it proxies their requests to the destination.</p><p>Keep in mind that VM’s specs should be adjusted to meet your requirements and <strong>var.vm_ip_address</strong> must be from the specified range in Step 5.</p><p>There is also a startup script added to the VM which we will discuss in the next step.</p><pre>resource &quot;google_compute_instance&quot; &quot;proxy_vm&quot; {<br> name         = &quot;proxy-vm&quot;<br> project      = var.project_id<br> zone         = var.zone<br> machine_type = &quot;n1-standard-1&quot;<br><br><br> boot_disk {<br>   initialize_params {<br>     image = &quot;debian-cloud/debian-11&quot;<br>   }<br> }<br> tags                    = [&quot;proxy-srv&quot;]<br> metadata_startup_script = file(&quot;setup_proxy.sh&quot;)<br><br> network_interface {<br>   subnetwork = google_compute_subnetwork.proxy_subnet.name<br>   network_ip = var.vm_ip_address<br>   access_config {<br>     nat_ip       = google_compute_address.static_ip.address<br>     network_tier = &quot;STANDARD&quot;<br>   }<br> }<br>}</pre><p><strong>9. Setting up an HTTP Proxy Server on the VM</strong></p><p>You might have noticed that there is a startup script added to the VM. This script will run right after the VM gets created. It sets up a Forward Proxy on the VM so no manual work is required.</p><p>Feel free to use any Proxy Server that suits your needs. Here we are using <strong>“github.com/elazarl/goproxy”</strong> to build our own proxy server.</p><p>The script creates a Go project, builds it, and then runs the binary using a Systemd Service so it will start automatically on VM reboots.</p><p>You can change the Listen Port number for the proxy by editing the script. However, if you change it, you also need to change the firewall rule to match the new port.</p><p><strong>10. Adding Firewall Rules allowing Ingress Traffic to the Proxy Port</strong></p><p>For security reasons, we only accept ingress traffic to the Proxy Server from its Internal IP address. This means that no one from the outside world can use our Proxy Server.</p><p>This policy is enforced using a firewall rule:</p><pre>resource &quot;google_compute_firewall&quot; &quot;proxy_ingress&quot; {<br> name    = &quot;allow-proxy-ingress&quot;<br> network = google_compute_network.vpc_network.name<br><br><br> source_ranges = [&quot;${var.named_private_ip}/${var.named_private_ip_prefix_length<br>}&quot;]<br> allow {<br>   protocol = &quot;tcp&quot;<br>   ports    = [&quot;9231&quot;] # If you change this, make sure you&#39;re also changing it inside setup_proxy.sh<br> }<br> target_tags = [&quot;proxy-srv&quot;]<br>}</pre><p><strong>11. Instructing Cloud Build instances to use VMs private IP address as Proxy</strong></p><p>Now that we have everything in place, it’s time to trigger a sample build to see the results.</p><p>Here is a simple Build instruction that sets the <strong>http_proxy</strong> and <strong>https_proxy</strong> environment variables, installs curl, and then queries ipify API. After a successful run, you should be able to see that the VM’s static IP address gets printed, indicating that the outside world thinks our Build Instances have that IP address.</p><pre>steps:<br> - name: ubuntu<br>   script: |<br>     export http_proxy=&quot;http://10.0.3.10:9231&quot;<br>     export https_proxy=&quot;http://10.0.3.10:9231&quot;<br>     apt update<br>     apt install curl -y<br>     curl https://api.ipify.org/<br>options:<br> pool:<br>  name: &quot;projects/{project_id}/locations/europe-west2/workerPools/{private_worker_pool_name}&quot;</pre><h4><strong>Conclusion</strong></h4><p>That is all! We have managed to assign a static external IP address to a Cloud Build instance through a proxy server hosted on Google Compute Engine. We have also verified this by running a sample Cloud Build job, where we saw that an external request&#39;s IP address matched our proxy VM&#39;s external IP. With a static external IP for your Cloud Build instance you can whitelist the IP in external providers you may need to access for builds, adding that extra layer of security to your application!</p><p><em>Datatonic, Google Cloud’s 4 X Partner of the Year, is the leading cloud data + AI consultancy for the world’s most ambitious businesses, challenging traditions to deliver tangible innovation at the leading edge of Google Cloud. Our team has a wealth of experience with Cloud Build, and other Google Cloud products. Need help with your data and AI? Get in touch at </em><a href="https://datatonic.com/contact/"><em>datatonic.com/contact/</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb3f80b9ce15" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/configuring-cloud-build-to-use-static-external-ip-addresses-bb3f80b9ce15">Configuring Cloud Build to use Static External IP Addresses</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning: How to Train an RL Agent from Scratch]]></title>
            <link>https://blog.montrealanalytics.com/reinforcement-learning-how-to-train-an-rl-agent-from-scratch-96af39a3287?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/96af39a3287</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 16:00:02 GMT</pubDate>
            <atom:updated>2022-10-04T16:00:02.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBLGvr74VotyoObPL35mgw.jpeg" /></figure><p>In the <a href="https://datatonic.com/insights/reinforcement-learning-identifying-opportunities-use-cases/">first blog post</a> of our Reinforcement Learning (RL) series, we gave an introduction to the core concepts of RL, and guidance for identifying suitable use cases to show you where RL can provide business value across a range of industries.</p><p>This second blog will introduce you to a specific type of RL, called <strong>Q-learning</strong>, and show you how to <strong>code your own RL agent</strong> using the example of the game, Catch.</p><h3>The Game of Catch</h3><p>The game of Catch is an ideal example to illustrate the inner workings of RL as only a few hundred lines of code are required. In this game, the RL agent tries to catch falling fruit (a single pixel) in a basket (three pixels-wide). The basket can only move horizontally. The agent is successful if it can catch the fruit; if it misses the fruit, the game is lost. This game can be translated into an RL framework:</p><ol><li>The<strong> agent</strong> moves a basket trying to catch the falling fruit.</li><li>The <strong>environment</strong> is a 10×10 grid consisting of fruit dropped from the top of the grid in a random column, falling over 10 consecutive time steps. The agent’s basket consists of 3 cells that move laterally at the bottom row of the grid.</li><li>The <strong>state</strong> of the environment is defined as a 3-dimensional tuple: [fruit row position, fruit column position, basket column position].</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mAabzSyeyNK1ZAyp" /><figcaption>Fig 1: The environment state depicted with fruit and a basket (left) and representation in grid cells (right).</figcaption></figure><ol><li>The three<em> </em><strong>actions </strong>are<em>:</em> moving the basket left, right, or staying stationary.</li><li>The<strong> reward</strong> is +1 if the basket catches the fruit, -1 if the basket misses the fruit and 0 any other time (when the fruit is still falling).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rBUyqb08WxW2r363" /><figcaption>Fig 2: Reinforcement Learning framework applied to Catch</figcaption></figure><p>This problem lends itself well to being solved by RL as we can create an algorithm where the agent finds a way to maximise its score without us giving it any indication of how the game should be played.</p><p>In this example, we will use a specific type of RL called <strong>Q-learning</strong>.</p><h3>What is Q-Learning?</h3><p>In Q-learning, a Q-value for each action and state is learned. These Q-values represent how useful an action is in a given state for gaining future rewards.</p><p>We can subdivide RL algorithms according to <strong>how the agent learns</strong>, the <strong>agent’s representation of the environment</strong>, the <strong>agent’s behaviour function</strong>, and whether the agent <strong>waits to learn until the end of the game or not</strong>. In the figure below you can see how Q-learning resides within the RL Landscape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5dVCW_hHi4XatvRw" /><figcaption>Fig 3: Situating Q-learning in the world of Reinforcement Learning</figcaption></figure><p><strong>Learning Methods of the Agent</strong></p><p>We’ll start with how the agent learns. There are two main approaches to solving RL problems:</p><ol><li><strong>Policy-based</strong> methods: explicitly building a representation of the policy. This is a probabilistic mapping from the states to a set of valid actions that the agent keeps in memory whilst learning.</li><li><strong>Value-based </strong>methods: not storing any explicit policy, only a value function.</li></ol><p>There is also a hybrid,<strong> </strong>3. <strong>actor-critic </strong>approach, which employs both value and policy functions. In our code example, we use a <strong>value-based</strong> approach, using the Q-value.</p><p><strong>The Environment’s Representation</strong></p><p>The agent’s representation of the <strong>environment</strong> can be modelled using a <strong>model-based </strong>approach or, when not using any predictions of the environment, can be <strong>model-free</strong>. Our catch example is a model-free approach as no model represents the agent’s environment; only the game interface is used.</p><p><strong>The Agent’s Behaviour</strong></p><p>The agent can behave either <strong>off-policy</strong> or <strong>on-policy</strong>. In our example, the current policy is updated from experiences generated by a previous policy. This means we are dealing with an <strong>off-policy</strong> learner, as it does not learn the optimal Q-value directly from the agent’s actions.</p><p><strong>When to Update the Estimates</strong></p><p>In this code example, the estimates refer to the estimates of the Q-values (see Fig 11). One option would be to update the estimates once the final outcome is known (i.e. at the end of the game); these are called Monte Carlo methods. A second option is to adjust predictions to match later, more accurate, predictions about the future before the final outcome is known. This latter option is known as <strong>temporal difference learning</strong>.</p><p>In our implementation of RL to solve the game of Catch, the Q-value estimates are learned by sampling transitions stored in an experience replay buffer. The value functions are updated during the game using <strong>temporal differencing.</strong></p><p>To summarise all of this, <strong>Q-Learning is a value-based, model-free, off-policy, temporal difference algorithm.</strong></p><h3>The Experience Replay Buffer</h3><p>When using Q-learning, we can also use an experience replay buffer. Generating new experiences can be difficult, time-consuming, and expensive.</p><p>The experience replay buffer allows us to minimise the number of experiences we need to generate to train a robust and high-performing agent by reusing previous ones. Without an experience replay buffer, the agent would only update its Q-values based on the most recent transition. This would require much more experience to converge.</p><p>The system stores a history of the agent’s experiences. An <strong>experience</strong> (or transition) consists of the environment <strong>state</strong> and the <strong>action</strong> at a given time step. It also contains the received <strong>reward</strong>, the next <strong>state</strong> and an optional done <strong>signal</strong>.</p><p>The learning phase is based on taking random samples from the experience replay. This improves the sample efficiency and stability of the training, making the experience replay a crucial component in the learning process of off-policy deep RL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g_LlfgEUspvH0tpO" /><figcaption>Fig 4: A typical Reinforcement Learning framework for a Q-learning agent (with S, A, R, S, D representing the current state, current action, reward, next state and done signal)</figcaption></figure><h3>Reinforcement Learning Catch Code Walkthrough</h3><p>The implementation of this game can be found in <a href="https://github.com/teamdatatonic/rl-agent-playing-catch">this GitHub repo</a>.</p><p>The codebase comprises four python files defining the <strong>environment</strong>, the <strong>experience replay</strong>, the <strong>training</strong> of the agent and <strong>running</strong> a trained agent. Let’s dive into the python code of our RL model!</p><p><strong>Environment Definition (env.py)</strong></p><p>The Catch environment is defined as a 10×10 pixel grid and includes the methods of interacting with it. At each time step, we iterate through the agent’s action, the state transition, and the reward cycle. We redraw the environment upon each state change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7gIt9NtmX3QUznZ" /><figcaption>Fig 5: <strong>‘</strong>act’ function in env.py</figcaption></figure><p>When the agent wants to interact with the environment, it will call the ‘act’ function (see Fig. 5). The action must be specified as a parameter when calling the ‘act’ function. The action is used to update the state of the environment, presenting us with a new reward. Every time an action is taken, we need to check whether the fruit reached the bottom of the grid at the end of the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CMTE524tRYwgOi06" /><figcaption>Fig 6: <strong>‘</strong>observe’<strong> </strong>function in env.py</figcaption></figure><p>When the ‘act’ function returns the updated values, the ‘observe’ function is called to redraw the 10×10 pixel grid to show the new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5p75KRKczdEyylSz" /><figcaption>Fig 7: ‘reset<strong>’</strong> function in env.py</figcaption></figure><p>Additionally, the environment file defines a ‘reset’ function which resets the environment state. The fruit row is reset to the top of the grid (position 0) and the fruit column and basket position are randomly initialised. Since the fruit basket is three pixels wide and defined by its central position, it cannot be initialised in either position 0 or 9.</p><p><strong>Experience Replay Definition (experience_replay.py)</strong></p><p>The experience replay file contains a helper class that defines the experience replay buffer and its associated methods. The experience replay buffer stores previous state-action interactions. A sample of these interactions will be used to train a Deep Learning model to make better decisions on actions to take going forward.</p><p>We define an experience as a tuple of the previous state, the action taken, the next state transitioned to, the reward received from transitioning to the next state, and the signal that it is done.</p><p>We use a simple python list as our experience replay buffer. The experience replay buffer has a maximum size. Any experiences added to a full experience replay buffer will replace the oldest experience. This functionality is defined in the ‘add_experience’ method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JOmnZaxcoTVaPeuO" /><figcaption>Fig 8: ‘add_experience<strong>’</strong> function in experience_replay.py</figcaption></figure><p>There is also a ‘get_qlearning_batch’ function that will randomly sample the experience replay buffer and build a training set for the Keras model. The input features are a flattened representation of the grid pixels, representing the current state, with the target being the Q-value of each state-action pair.</p><p>Note that the ‘get_qlearning_batch’ method of the experience buffer is specific to Q-learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oez4roesWNT9_kre" /><figcaption>Fig 9: ‘get_qlearning_batch<strong>’</strong> function in experience_replay.py</figcaption></figure><p><strong>Train File (train.py)</strong></p><p>The Q-learning training file defines the Keras model and the agent training loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lZFHzlZAtDm2Iap2" /><figcaption>Fig 10: Input and outputs of the Keras Model</figcaption></figure><p>We define a simple Neural Net, with two hidden layers, that takes the grid pixels of the current state as its input, and then outputs the predicted Q-values for each action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1imp3P42ArqbAeOn" /><figcaption>Fig 11: ‘define_model<strong>’</strong> function in train.py</figcaption></figure><p>We also define instances of the environment and the experience replay buffer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_56V7WxkllUfABNq" /><figcaption>Fig 12: section of the <strong>‘</strong>main’ program in train.py</figcaption></figure><p>An epoch of the training loop is defined by running through an iteration of the catch game and storing the state experiences and rewards received in the experience replay buffer as the game is played. After each action selection, we create a batch of training data by sampling the experience replay buffer and training the model on these experiences.</p><p>We follow an epsilon-greedy strategy when deciding which action to take. This means that at least 90% of the time the agent chooses what it believes to be the best action, but 10% of the time a random action is taken to see what happens. We can change the ratio of exploration by changing the ‘epsilon’ variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vljX-F9UBaI36qXF" /><figcaption>Fig 13: epsilon greedy section of ‘train_model<strong>’</strong> function in train.py</figcaption></figure><p>In the next game (epoch), the model is then used to run another game of catch, producing more experiences with slightly different, and hopefully improved, action decisions. The loop is repeated until all epochs are run. The resulting model artefact is saved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*62WZTFPAmgx-eaRY" /><figcaption>Fig 14: training loop part of <strong>‘</strong>train_model’ function in train.py</figcaption></figure><p><strong>Inference File (run.py)</strong></p><p>The inference file defines how a trained model can be used to show a reasonable game of catch. The trained model should predict more optimal Q-values, allowing the agent to make better decisions when moving the basket and therefore should be more successful at catching the fruit.</p><p>At each time step:</p><ol><li>We pass the grid state to the model</li><li>The model returns the estimated Q-values for each action</li><li>The action with the highest Q-value is chosen and sent to the environment</li><li>The environment returns the new state and the reward received</li><li>The new state is drawn on the canvas</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*YBhHLCFREDDMlP_b" /><figcaption>Fig 15: Gif of running the game with the optimal policy in run.py</figcaption></figure><h3>Summary</h3><p>Following the code above, you should be able to create a Reinforcement Learning model successfully. While we’ve used RL to develop a model to play a relatively simple game, RL has several impactful real-world applications.</p><p><strong><em>As 4x Google Cloud Partner of the Year, Datatonic has a wealth of experience in both Machine Learning and a range of Google products and services. </em></strong><a href="http://datatonic.com/contact"><strong><em>Get in touch</em></strong></a><strong><em> to learn how your business can benefit from Reinforcement Learning or other Machine Learning models.</em></strong></p><p><strong>Further Reading</strong></p><p>If you want to learn more about Reinforcement learning, take a look at these resources:</p><ul><li><a href="https://www.coursera.org/learn/unsupervised-learning-recommenders-reinforcement-learning">Coursera Course</a> on Unsupervised Learning, Recommenders, Reinforcement Learning</li><li><a href="https://youtube.com/playlist?list=PLoROMvodv4rMiGQp3WXShtMGgzqpfVfbU">Stanford Machine Learning Course</a> taught by Andrew Ng (from the middle of Lecture 16 onwards)</li><li><a href="https://www.davidsilver.uk/teaching/">UCL Course on Reinforcement Learning</a> taught by David Silver</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96af39a3287" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/reinforcement-learning-how-to-train-an-rl-agent-from-scratch-96af39a3287">Reinforcement Learning: How to Train an RL Agent from Scratch</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning: Bringing Use Cases to Life]]></title>
            <link>https://blog.montrealanalytics.com/reinforcement-learning-bringing-use-cases-to-life-44969663c1e0?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/44969663c1e0</guid>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 15:42:59 GMT</pubDate>
            <atom:updated>2022-10-04T15:42:59.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OA_Rj5fMYwBgH4vT-wTKKg.jpeg" /></figure><p><strong>Reinforcement Learning (RL)</strong> has been one of the most talked about Machine Learning <a href="https://www.udacity.com/blog/2022/06/2022s-most-relevant-machine-learning-trends.html">trends</a> over the last few years. Often used in the world of gaming, RL leverages <strong>fast-paced trial and error</strong> to develop powerful solutions. By <strong>optimising decisions based on reward maximisation</strong>, RL has the potential to transform other industries too. However, identifying specific use cases and creating the conditions for RL applications to be successful can be challenging.</p><p>In this two-part blog series, Datatonic’s Data Scientists and Machine Learning Engineers cover the core concepts of RL, <strong>real-world applications,</strong> and provide guidance on <strong>identifying suitable use cases</strong> and deploying them successfully.</p><h3>What is Reinforcement Learning?</h3><p>Reinforcement Learning (RL) is a type of Machine Learning, where the algorithm learns to interact with an environment to maximise a reward through trial and error. RL is a general framework for learning sequential decision-making tasks; it is about discovering the smart actions that lead to the desired outcome of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FHbCPUN0-O3kicdz" /><figcaption>Fig 1: A typical RL framework.</figcaption></figure><p>The RL algorithm, or RL <strong>agent</strong>, learns smart behaviour by taking <strong>actions</strong> in an <strong>environment</strong> and receiving feedback (<strong>rewards</strong> and <strong>states</strong>). Rewards can be positive or negative (e.g. penalties) and are the only signal used to determine if the agent is doing well or not.</p><p>The <strong>state </strong>is the current situation of the world or environment that the agent is able to see and experience and is the information that the agent receives to decide the next action. We assume that the state has all the relevant information for the agent to choose its next action.</p><p>Games such as <a href="https://arxiv.org/pdf/1312.5602v1.pdf">Atari</a> and <a href="https://www.deepmind.com/research/highlighted-research/alphago">Go</a> have become testbeds for RL algorithms. They lend themselves well to being solved by RL as lots of sequential actions need to be taken over time, without a supervised signal, in a simulated environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6iaA5qIpRsw-bO19" /><figcaption>Fig 2: RL framework applied to Mario Kart.</figcaption></figure><p>To understand the fundamental concepts of RL, let’s look at an example: Mario Kart. An AI Mario would be the RL <strong>agent</strong> in this case. The possible <strong>actions</strong> Mario can take are 1.) turning the steering wheel and 2.) pressing the accelerator or the brake. The optimal actions would be based on the position and speed of his vehicle, the location on the track, and the other surrounding vehicles. All these elements will define the <strong>state</strong> Mario finds himself in.</p><p>If Mario can reach the destination quickly while respecting the game rules, he will be <strong>rewarded</strong> with higher scores. Mario will play the game multiple times, with the game interface depicting the virtual <strong>environment</strong>. By gaining more experience, he will make smarter decisions on when to accelerate, turn or brake, allowing him to be faster and maximise his score. These concepts of agent, action, environment, state, and reward form the fundamental building blocks for RL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4FfZIqw8fTm2Xg-7" /><figcaption>Fig 3: Branches of Machine Learning.</figcaption></figure><p>RL differs from Supervised Learning (SL) and Unsupervised Learning (UL) in three main ways:</p><p><strong>1. Learning</strong></p><p>In RL, there is no answer, no supervisor, but only a reward signal. This reward signal indicates what is “good” and what is “bad” behaviour. The decision maker, i.e. the agent, has the freedom to decide what actions to take to maximise the reward. Conversely, in SL, the correct answer is given via a labelled training data set.</p><p><strong>2. Sequentiality &amp; Timelines</strong></p><p>Another distinction is that in RL, the feedback can be delayed over time. A decision made now might only be rewarded later. For example, AI Mario may only learn that accelerating at a specific point was “good” upon achieving a faster time at the end of the lap. This is because the algorithm seeks to maximise the long-term reward. In RL, the timing and the order of the agent’s decisions matter as we are dealing with sequential decision-making processes.</p><p><strong>3. Data Generation</strong></p><p>Perhaps the most important distinction in RL is how the data is generated. In RL, the agent’s actions influence the subsequent data it receives, unlike SL/UL. The RL agent gets to take actions, influence its environment, and move around in it. Depending on where the RL agent decides to go, it will “see” different things, and it will get different rewards. So, the agent is influencing the data that it receives as it “finds” it.</p><h3>Reinforcement Learning Solves Real-World Sequential Decision-Making Problems</h3><p>RL has been <a href="https://www.technologyreview.com/2019/01/25/1436/we-analyzed-16625-papers-to-figure-out-where-ai-is-headed-next/">gaining momentum</a>, especially since March 2016, when DeepMind’s <a href="https://www.deepmind.com/research/highlighted-research/alphago">AlphaGo</a> Reinforcement Learning algorithm defeated a former world champion of Go. Go is an ancient Chinese board game known for being one of the most complex and strategic games in the world. At the time, Go was seen as the next big challenge for Machine Learning; there was a gap of almost two decades since IBM’s Deep Blue beat the world chess champion in 1997. When AlphaGo won, it was a massive turning point.</p><p>RL has been at the heart of some of the most significant breakthroughs in recent years. Companies like <a href="https://www.deepmind.com/blog/deepmind-ai-reduces-google-data-centre-cooling-bill-by-40">Google</a>, <a href="https://www.amazon.science/publications/automate-page-layout-optimization-an-offline-deep-q-learning-approach">Amazon</a>, and <a href="https://research.atspotify.com/shifting-consumption-towards-diverse-content-via-reinforcement-learning/">Spotify</a>, are just a few examples of those actively investing in RL. This has included personalisation of push alerts, product suggestions, and operational purposes such as cooling of data centres and faster video loading by pre-fetching content.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWXuK6gekU1Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWXuK6gekU1Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWXuK6gekU1Y%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4943c0676d375aa4c3148a84039cee0/href">https://medium.com/media/f4943c0676d375aa4c3148a84039cee0/href</a></iframe><p>The real value of RL lies in solving real-world sequential decision-making <a href="https://www.linkedin.com/pulse/data-science-20-how-applied-reinforcement-learning-take-horn/">problems</a>. Shifting the focus from optimising predictions to optimising decisions based on reward maximisation, could even lead to the development of <a href="https://venturebeat.com/2021/06/09/deepmind-says-reinforcement-learning-is-enough-to-reach-general-ai/">artificial general intelligence</a>. We are at the point where the tools and computational resources available allow us to build a growing range of RL solutions.</p><h3>Current Uses of Reinforcement Learning</h3><p>Environments in which at least one of the following conditions apply are typically good candidates for an RL solution:</p><ul><li>There is a known model of the environment, but no analytical solution is available.</li><li>Only a simulation model of the environment is given (the subject of a simulation-based optimisation)</li><li>The only way to collect information about the environment is to interact with it.</li></ul><p>Reinforcement Learning can be used in different <a href="https://rl-book.com/applications/">industries</a> such as gaming, media, telecommunications, logistics, the energy sector, finance, advertisement, healthcare, e-commerce, and many more. Let’s take a look at some examples.</p><p>A prime RL application example is a recommendation system. RL has significant advantages when developing a recommendation system for <a href="https://arxiv.org/pdf/1003.0146.pdf">new feeds</a>, <a href="https://research.atspotify.com/shifting-consumption-towards-diverse-content-via-reinforcement-learning/">products</a>, or <a href="https://arxiv.org/abs/1905.12767v2">videos</a>. This is a good fit for personalising product recommendations on a dynamic website. Unlike SL, which would require constant model updates, RL can continually update recommendations based on user feedback. RL can learn to make good decisions in the short term while also doing well on a longer-term goal, such as customer retention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*blVBycvCMYN2JzH4" /><figcaption>Fig 5: Reinforcement Learning has been used in the energy sector.</figcaption></figure><p>RL can also be used to optimise processes such as <a href="https://arxiv.org/pdf/2206.03721v1.pdf">smart energy grids</a> and <a href="https://www.deepmind.com/blog/safety-first-ai-for-autonomous-data-centre-cooling-and-industrial-control">data centre cooling.</a> These are difficult to optimise using traditional formula-based engineering, or human intuition. It is impractical to come up with rules and heuristics for every operating scenario. In this case, the RL agent continues to learn the best action to take over a timespan from microseconds to months.</p><p>Other applications of RL include abstractive text summarisation engines, dialogue agents for text and speech, learning optimal treatment policies in healthcare, and RL-based agents for online stock trading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*sCAbGcT5tbVl-2ia" /><figcaption>Fig 6: Google’s DeepMind is using Reinforcement Learning to train an AI to <a href="https://www.deepmind.com/blog/accelerating-fusion-science-through-learned-plasma-control">Control Nuclear Fusion</a>.</figcaption></figure><p>Unfortunately, the development of real-world solutions using RL has been lagging, as the ability to identify potential use cases can be challenging.</p><h3>Reinforcement Learning in Practice</h3><p>Reinforcement Learning has <a href="https://vitalflux.com/reinforcement-learning-real-world-examples/">applications</a> in multiple industries, including self-driving cars, ad recommendations, personalised chatbot responses, and many others. To identify use cases, it’s important to know which conditions need to be present for RL to work effectively. Below, we detail some of the <a href="https://medium.com/swlh/when-to-use-reinforcement-learning-and-when-not-to-919557dd34a">hard constraints</a> to consider when looking to use RL.</p><p><strong>1. Formulating a Control Problem Instead of a Prediction Problem</strong></p><p><a href="https://www.deepmind.com/blog/real-world-challenges-for-agi">Prediction and control</a> problems are two of the most common problem classes. Prediction models try to learn about a domain and understand how it might evolve. Control models prompt agents to take actions in an environment. RL is applicable to control problems, where the solution is difficult to describe as a prediction problem. This can be due to a large complex problem space, or the need for a highly dynamic system that can easily adapt to unseen situations. If solving a certain problem can be learned by receiving feedback from the environment through trial and error, with well-defined rewards, RL could be the answer.</p><p><strong>2. Choosing the Right Variables to Describe the State</strong></p><p>It is also important to consider which variables describe the state and how these will be quantified. To make a smart decision at each step, the RL agent needs to have access to the right information to define the state of the environment. More information might give a more accurate description to the agent, but it could result in an increased training time for the agent as more variables need to be taken into account.</p><p>Furthermore, having information available that is not relevant might confuse the agent, and not having enough information may result in a poorly-performing agent or even learning the wrong behaviour.</p><p><strong>3. Shifting from Predictions to Actions</strong></p><p>The RL agent requires a well-defined set of available decisions. These actions determine what the agent can do given the situation it finds itself in. An agent needs to know which actions it can take, though it doesn’t necessarily know what effects it will have on the environment.</p><p><strong>4. Defining the Reward Function</strong></p><p>Well-defined rewards are an essential part of RL as they indirectly determine the desired behaviour of the RL agent. The reward can either be computed after each action or at the end of a series of actions. But, if the reward function is poorly designed, the RL agent might exhibit unwanted behaviour.</p><p>A classic example of this is shown below in the game, CoastRunners. Instead of racing to the finish line while gathering as many points as possible, the agent finds a way to achieve a higher score by crashing into boats, catching fire and going the wrong way on the track. The agent will do what it is rewarded to do under the defined constraints.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtlOIHko8ySg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtlOIHko8ySg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtlOIHko8ySg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6937bf682f783271f6c33f8a0150409d/href">https://medium.com/media/6937bf682f783271f6c33f8a0150409d/href</a></iframe><p><strong>5. Using RL Safely</strong></p><p>The agent learns through trial and error by interacting directly with the environment. This means that the agent will make mistakes. However, the freedom to explore without consequence is not always present. It is necessary to be able to define a safe exploration space; safety constraints are needed to avoid catastrophic results in many real-world settings.</p><p>For example, in the case of autonomous vehicles, it is impractical to start the training from scratch in the real world. Therefore, numerous trials will be run in a simulated environment before testing models in real life. But, a well-performing agent in a simulation doesn’t necessarily mean that it will transfer its skills to real-world applications. This introduces another important concept: balancing the cost of making the simulation realistic versus minimising the domain transfer gap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*do_3DlMxmC_LkBx4" /><figcaption>Fig 8: <a href="https://wayve.ai/blog/learning-to-drive-in-a-day-with-reinforcement-learning/">Teaching a car to follow a lane</a> from scratch using Reinforcement Learning.</figcaption></figure><h3>Summary</h3><p><strong>Reinforcement Learning</strong> is an area with lots of interest, but identifying the right use cases can be difficult. While a wide range of industries can use Reinforcement Learning, it is important to consider a number of factors, both before starting and while developing your model. For example, properly defining the reward function and choosing the right variables to describe the state.</p><p>This blog has covered several of these, and with these considerations, it becomes easier to identify where RL can be used effectively to <strong>help your business</strong>.</p><p>Environments in which at least one of the following conditions apply are typically good candidates for an RL solution:</p><ul><li>There is a known model of the environment, but no analytical solution is available.</li><li>Only a simulation model of the environment is given (the subject of a simulation-based optimisation)</li><li>The only way to collect information about the environment is to interact with it.</li></ul><p>When used correctly, RL can be used to train models that generate <strong>huge business value</strong> at a <strong>lower cost</strong> than other types of Machine Learning model training.</p><p>In the <a href="https://datatonic.com/insights/reinforcement-learning-training-rl-agent-tutorial/">next blog</a>, we’ll provide a code walkthrough, where you can train your first RL agent. We hope these blog posts might give you some tips and insights to getting you started with RL!</p><p><strong><em>Datatonic is </em></strong><a href="https://datatonic.com/insights/datatonic-google-cloud-specialization-partner-award-machine-learning/"><strong><em>Google Cloud’s Machine Learning Partner of the Year</em></strong></a><strong><em> with a wealth of experience developing and deploying impactful Machine Learning models and MLOps Platform builds. Need help with developing an ML model, or deploying your Machine Learning models fast? Have a look at our </em></strong><a href="https://datatonic.com/insights/vertex-ai-mlops-platform/"><strong><em>MLOps 101 webinar</em></strong></a><strong><em>, where our experts talk you through how to get started with Machine Learning at scale or </em></strong><a href="https://datatonic.com/contact"><strong><em>get in touch</em></strong></a><strong><em> to discuss your ML or MLOps requirements!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44969663c1e0" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/reinforcement-learning-bringing-use-cases-to-life-44969663c1e0">Reinforcement Learning: Bringing Use Cases to Life</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision: Generative Models and Conditional Image Synthesis]]></title>
            <link>https://blog.montrealanalytics.com/computer-vision-generative-models-and-conditional-image-synthesis-29b4a013b857?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b4a013b857</guid>
            <category><![CDATA[dalle-2]]></category>
            <category><![CDATA[image-synthesis]]></category>
            <category><![CDATA[inpainting]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 14:53:34 GMT</pubDate>
            <atom:updated>2022-09-20T14:53:34.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfwNpOZKmUE1nfwyLeL3Tg.jpeg" /></figure><p>Our Computer Vision blog series has already covered an <a href="https://datatonic.com/insights/computer-vision-insights-datatonic-experts/">introduction to Computer Vision</a> and some current use cases, the <a href="https://datatonic.com/insights/computer-vision-future-google-cloud/">future of Computer Vision</a>, how to create an <a href="https://datatonic.com/insights/computer-vision-object-detection-vertex-ai-automl/">Object Detection model</a> without any code, and how to train and deploy your own <a href="https://datatonic.com/insights/deploying-image-segmentation-models-vertex-ai/">Image Segmentation model</a>. <strong>This blog post will explore one of the hottest topics in the Computer Vision field, Generative Models, focusing on one of its most popular branches, Conditional Image Synthesis.</strong></p><p>In this blog, we will start by presenting our brand new Fashion Generator demo, and then we will go deeper into the underlying technologies behind it: <strong>Conditional Generative Models.</strong></p><p>As part of <strong>Datatonic Labs</strong>, our dedicated R&amp;D hub where we push the boundaries for cloud technologies, data engineering, and AI, we have been able to explore cutting-edge Conditional Image Synthesis models. To showcase the potential of these models, we have developed a demo oriented to the Fashion sector.</p><h3>Datatonic’s Fashion Generator Demo</h3><p>Our <strong>Fashion Generator</strong> model can generate new clothing styles by using an input image of people wearing clothes, removing the original clothes, and replacing them with new stylish ones generated by the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mQFpoIELrgpjjCaB" /><figcaption>Fig 1: The original image (left) and the Fashion Generator output (right).</figcaption></figure><p>The generative part of the demo is based on a Variational Autoencoder model. Having previously explored different alternatives such as Conditional GAN (Generative Adversarial Networks) or Diffusion models, we finally decided to use Variational Autoencoders to enable higher diversity of outputs.</p><p>We used data from <a href="https://www.kaggle.com/competitions/imaterialist-fashion-2020-fgvc7/data">Kaggle</a> to train our model, as there is a large set of images and clothes masks available that fit our use case. We used <a href="https://cloud.google.com/vertex-ai">Vertex AI</a> Workbench notebooks, taking advantage of its flexibility in terms of available resources, reduced setup time, and scalability functions that allowed us to easily access the GPU resources for the training stage.</p><p>You can access this demo through our <a href="https://demohub.datatonic.com/">Demo Hub</a> by clicking on the <strong>Fashion Generator</strong> demo. Keep reading to find out more about how it works!</p><h3>What is a Generative Model?</h3><p>You may have heard about Deep Learning models like Deep Fakes or those able to estimate how your face would look in 25 years. Indeed, deep generative models are behind these impressive use cases, but these models go far beyond purely trivial purposes and offer great possibilities for industries such as game design, cinematography, and content generation, among others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*39KmY5Cmjvz5oOzY" /><figcaption>Fig 2: Human faces artificially <a href="https://github.com/NVlabs/stylegan">generated by AI</a>.</figcaption></figure><p>These models are based on unsupervised learning algorithms capable of approximating complex, high-dimensional probability distributions from data and generating new samples from these underlying distributions. These algorithms may be applied to many types of data, including audio, image, and video data.</p><p>In the last five years, there has been huge progress in the field of generative models from both academia and industry. There are two specific projects worth noting: <a href="https://arxiv.org/abs/1812.04948">StyleGAN</a> from NVIDIA, presenting a model capable of generating human faces, and the <a href="https://openai.com/blog/better-language-models/">GPT-2</a> language model from OpenAI, which can generate original text based on an introductory piece of text. However, evaluating the performance of these models has been difficult given the subjective aspect of measuring the quality of the output.</p><h3>Types of Generative Model</h3><p>It is quite common to classify generative models into two main groups:</p><p><strong>1. Likelihood-based models</strong></p><p>Models in this group try to explicitly learn the likelihood distribution P(X|Y) through loss functions. They are trained to infer a probabilistic distribution that is as similar as possible to the original input data distribution. We could classify VAE models into this group.</p><p><strong>2. Implicit models</strong></p><p>Unlike likelihood-based models, implicit models are not explicitly trained to learn the likelihood distribution, but to generate output similar to the input data. In the case of GAN, the generator learns how to generate images that could fool the discriminator by generating images that look real enough to avoid the discriminator detecting them as fake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W6tp4eWfCVYEGm2I" /><figcaption>Fig 3: GAN can be applied to video games to create new levels.</figcaption></figure><h3>Evaluating Generative Models</h3><p>As we mentioned previously, evaluating generative models’ performance is challenging. In the case of likelihood-based models, we may use the likelihood values to measure how good a model is, but this does not take into account the output of the models. While outputs can be observed visually, at least for image outputs, we need an empirical metric to objectively measure the model quality and compare it against other models.</p><p>Here are some of the most commonly used metrics to evaluate generative models:</p><p><strong>1. Kullback-Leibler Divergence (KL Divergence)</strong></p><p>The KL Divergence measures how different a probability distribution is from another probability distribution. This is similar to standard maximum likelihood optimisation problems, but we are minimising this metric instead of maximising the likelihood.</p><p><strong>2. Inception Score (IS)</strong></p><p>This metric evaluates the quality of the generative model output based on the InceptionV3 Network pre-trained on ImageNet. The IS value is composed by measuring two different aspects: (1) if the InceptionV3 network is capable of clearly identifying a certain type of object; and (2) the variety of outputs: checking if the generative model can generate a large set of different objects.</p><p><strong>3. Fréchet Inception Distance (FID)</strong></p><p>This metric uses the InceptionV3 Network slightly differently than the IS metric. It tries to measure the differences between real and generated images by evaluating the responses of the penultimate layer of the Inception Network when using real and generated images as the input. A lower FID means that generated images are similar to the real ones, so the model is performing well.</p><p>It is important to highlight that these metrics have some limitations to keep in mind when using them to evaluate the models:</p><ul><li>Their values can only be compared in the same context (dataset, image size, etc.).</li><li>There may be different implementations for the same metric.</li></ul><h3>Conditional Image Synthesis</h3><p>While generative models have been a milestone in the Computer Vision field, these technical advances need to be adapted to real business problems. In many cases, we may want to be able to control the output in some way, whether for exploring output variations or generating content in a specific direction. This is where Conditional Image Synthesis models appear to resolve the matter.</p><p>This kind of model is given an additional input that influences the output that allows us to control the content generation. This input may be very diverse, from text to segmentation masks. A popular example of these models is <a href="https://openai.com/blog/dall-e/">DALL-E</a>, an impressive model capable of generating realistic images from text descriptions. In this case, the way of conditioning the model output is through text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1O93JYXa01CfyGpN" /><figcaption>Fig 4: Image generated by <a href="https://openai.com/dall-e-2/">DALL-E</a> based on the description: “a painting of a fox sitting in a field at sunrise in the style of Claude Monet”.</figcaption></figure><p>Recent advances in the Conditional Image Synthesis field have been based on the original generative model architectures, such as GAN and VAE, and applying some modifications to allow the model to be given additional input to control the output. Nevertheless, there are new architectures, like Diffusion Models, with a different approach to generating synthetic images.</p><p><strong>Conditional GAN</strong></p><p>Before we start explaining the Conditional GAN model, it is worth giving a brief introduction to the GAN architecture. This model architecture was first introduced in <a href="https://arxiv.org/abs/1406.2661">2014</a>, and is composed of two sub-models: a generator and a discriminator. The former tries to generate realistic images similar to the ones present in the training data and the latter tries to discriminate between real images and the images generated by the generator. The generator learns from the output of the discriminator and is trained to create images that look ‘real’ to the discriminator.</p><p>This is great, but we cannot control the generator output, as it is randomly generated based on the ‘knowledge’ gathered from the training phase. This characteristic differentiates GAN from Conditional GAN, as the latter allows control of the generator output. The Conditional GAN architecture includes an additional control vector that feeds both the generator and discriminator, controlling the model’s behaviour in the provided direction.</p><p>This control vector can be in multiple formats such as text labels, images, and segmentation masks, among others. An example of this type of model is <a href="https://blogs.nvidia.com/blog/2019/03/18/gaugan-photorealistic-landscapes-nvidia-research/">GauGAN</a>, by NVIDIA, which takes a segmentation mask as a conditional input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cwGAvsGmlPoP_j7p" /><figcaption>Fig 5: A realistic image of a waterfall created using GauGAN.</figcaption></figure><p>The GAN architecture models have a lot of potential applications, but it is important to consider which use cases they may perform well on. GAN can generate high-resolution images but is unable to catch the entire data distribution, suffering from a lack of diversity. Generally speaking, GAN models are suitable for tasks where the required images have sparse spatial details (like human faces) or good textural details are required, such as landscapes.</p><p><strong>Variational Autoencoders (VAE)</strong></p><p>To understand Variational Autoencoders, it helps to first understand what autoencoders are, as they are the foundation upon which VAE rests. The autoencoder architecture is composed of an encoder that compresses the input image into a numerical vector, where each dimension represents a feature using discrete values, and a decoder that takes that vector and tries to reconstruct the original image from the information encoded in that numerical vector.</p><p>The encoder is trained to gather the more representative features of every image and compress that information into a numerical vector. Meanwhile, the decoder is trained to reproduce the original image from that vector. For solving real problems, this is fairly limited, as the decoder is always going to generate the same output given an encoded vector; there is no margin for diversity.</p><p><a href="https://arxiv.org/pdf/1312.6114">Variational Autoencoders</a> solve this issue in a very simple way. Instead of compressing the input image into a numerical vector with discrete values, the encoder describes the image attributes using probabilistic terms, using probability functions instead of discrete numbers. This vector is commonly named latent space, and the decoder can randomly sample the probability distributions of each attribute to infer a new image, providing more diverse outputs.</p><p>In terms of limitations, VAE models are good at estimating the latent distribution and providing more diverse outputs than GAN, but often the results are blurry compared to the high-quality images GAN may provide. So, VAE is usually recommended when image resolution requirements are not so high, and diversity is a plus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHRjSKJApnioNbWZ" /><figcaption>Fig 6: Faces generated by a Variational Autoencoder model.</figcaption></figure><p><strong>Diffusion Models</strong></p><p>The <a href="https://arxiv.org/abs/2111.05826">Palette Model</a> is an Image-to-Image model that can perform various tasks, like Inpainting, Image Refinement, Colorization, and more. The Inpainting task is exciting as the examples in the paper show excellent results when given an image with a blanked-out area. The results are images with no blank areas, and the filled area looks natural.</p><p>The Diffusion model is inspired by nonequilibrium thermodynamics, and the process is explained in this <a href="https://arxiv.org/abs/1503.03585">paper</a> that explores the area. The Model is based on a Markov Chain of data, where the chain consists of a set of images derived from an original image. Noise is added to the image, or a specific area of the image, in steps and constitutes the chain when the last image, or the selected area of the image, is just random noise. The Model then learns how to reconstruct the image by denoising it recursively. The result is an image without noise and a natural fill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*FqpCZvgbqfrHymsn" /><figcaption>Fig 7: An example from the <a href="https://arxiv.org/abs/2111.05826">Palette Paper</a>. The first image from the right is the original image; the four images in the middle are generated images.</figcaption></figure><p>The Palette Diffusion Model does have a limitation when it comes to inpainting. We cannot condition the model to generate predefined information. If the blanked-out area on the input image were a dog, the dog would most likely not appear in the resulting image. The diffusion process creates natural-looking photos but with no control of the outcome.</p><p>Diffusion models are fascinating when it comes to potential use cases. The Palette model explored four tasks; colourization, inpainting, uncropping, and JPEG restoration. The various functions make it an exceptional media editing tool. Taking pictures, such as at tourist attractions, can be a pain when people are in the way of the beautiful photos you want to take. With the inpainting task, the model can remove the people if blanked out in the input. The information about people is removed and will likely not be generated in the output image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RC8PLRFXkKwh86vB" /><figcaption>Fig 8: The inpainting task removes people from the <a href="https://arxiv.org/abs/2111.05826">image</a>.</figcaption></figure><p>Another use case is restoring the resolution of images by the restoration task. Storing or sending high-resolution media can be data-heavy. Lowering the image’s resolution could solve this problem if we could restore it to the local machine, which is possible with the diffusion model.</p><h3>Summary</h3><p>In this blog post, we have looked at Conditional Image Synthesis models and highlighted their importance and potential future impact. The main takeaways we’d like to highlight for anyone interested in using Conditional Image Synthesis are the following:</p><ul><li>Understand the challenges, limitations, and possibilities associated with each of the models discussed.</li><li>Identify which one may fit a particular use case better.</li><li>Understand the fundamentals underlying the latest generative models use cases.</li></ul><p>There are a lot of expectations in the Computer Vision field regarding upcoming advances in this area, as there is an increasing interest, investment, and research around generative models. We can see fast progress, meaning there is still a lot to expect from these models.</p><p><strong>Further Reading</strong></p><p>For more information about some of the topics discussed in this blog, take a look at these resources:</p><ul><li>Multimodal Conditional Image Synthesis: <a href="https://arxiv.org/abs/2112.05130">https://arxiv.org/abs/2112.05130</a></li><li>Multiple latent spaces VAE: <a href="https://arxiv.org/pdf/2106.13416.pdf">https://arxiv.org/pdf/2106.13416</a></li><li>Vector Quantized Variational Autoencoder (VQ-VAE): <a href="https://arxiv.org/pdf/1906.00446v1">https://arxiv.org/pdf/1906.00446v1</a></li><li>Diffusion Models: <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">https://lilianweng.github.io/posts/diffusion-models/</a></li><li>Deep Unsupervised Learning using Nonequilibrium Thermodynamics: <a href="https://arxiv.org/abs/1503.03585">https://arxiv.org/abs/1503.03585</a></li></ul><p>Check out our other Computer Vision blogs in this series:</p><p><strong>Part 1: </strong><a href="https://datatonic.com/insights/computer-vision-insights-datatonic-experts/"><strong>Computer Vision: Insights from Datatonic’s Experts</strong></a></p><p><strong>Part 2: </strong><a href="https://datatonic.com/insights/computer-vision-future-google-cloud/"><strong>Computer Vision: Emerging Trends and Google Cloud Technology</strong></a></p><p><strong>Part 3: </strong><a href="https://datatonic.com/insights/computer-vision-object-detection-vertex-ai-automl/"><strong>Computer Vision: Object Detection and No-Code AI with AutoML</strong></a></p><p><strong>Part 4: </strong><a href="https://datatonic.com/insights/deploying-image-segmentation-models-vertex-ai/"><strong>Computer Vision: Deploying Image Segmentation Models on Vertex AI</strong></a></p><p><strong>Part 5: </strong><a href="https://datatonic.com/insights/computer-vision-generative-models-conditional-image-synthesis/"><strong>Computer Vision: Generative Models and Conditional Image Synthesis</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b4a013b857" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/computer-vision-generative-models-and-conditional-image-synthesis-29b4a013b857">Computer Vision: Generative Models and Conditional Image Synthesis</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision: Deploying Image Segmentation Models on Vertex AI]]></title>
            <link>https://blog.montrealanalytics.com/computer-vision-deploying-image-segmentation-models-on-vertex-ai-e51ca67a7ed4?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e51ca67a7ed4</guid>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 14:46:24 GMT</pubDate>
            <atom:updated>2022-09-20T14:46:24.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE1aFT3M0BeJDKYFTjn9Ug.jpeg" /></figure><p>In the <a href="https://datatonic.com/insights/computer-vision-object-detection-vertex-ai-automl/">most recent blog</a> of our Computer Vision series, we showed you how to use Vertex AI’s AutoML to train and deploy an Object Detection model. As powerful and efficient as AutoML is, you may want the flexibility to train and deploy more bespoke models, or tackle a Computer Vision task that isn’t currently covered by AutoML. Fortunately, Vertex AI has you covered here as well, with custom options for training and deploying your models on Google Cloud.</p><p>In this blog, we’ll show you how to train and deploy your own <strong>custom Image Segmentation model</strong> using Vertex AI. We’ll provide a background on Image Segmentation, and Vertex AI’s training options. Then, we will walk you through the step-by-step process of getting your own model up and running.</p><h3>Background</h3><p><strong>Image Segmentation</strong></p><p>Image Segmentation is a technique used in digital image processing, where an image is partitioned into multiple different segments, each representing a different part of the image. Image Segmentation can be used for tasks like distinguishing the background from the foreground in an image, or clustering pixels in an image together based on colour similarities.</p><p>In particular, we are going to focus on building a model that can perform a particular type of Image Segmentation, called <strong>Semantic Segmentation</strong>.</p><p><strong>Semantic Segmentation</strong></p><p>Semantic Segmentation is a type of Image Segmentation where the aim is to partition the image into semantically meaningful classes and to classify each pixel into one of these predetermined classes.</p><p>Semantic Segmentation is one step more sophisticated than Object Detection, in that rather than trying to draw a bounding box around the object, the goal is to draw a careful outline around the object that is detected so that you know exactly which pixels belong to the object and which pixels don’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*UMxw6wZARFumgPvr" /><figcaption>Fig 1: An example of Semantic Segmentation</figcaption></figure><p>One important thing to note is that in Semantic Segmentation we don’t differentiate between instances of the same object. For example, if there are two bikes in an image, Semantic Segmentation would label all of the pixels corresponding to either bike with the same “bike” label. This is in contrast to Instance Segmentation, which gives a unique label to every instance of a particular object in the image.</p><p>Semantic Segmentation is particularly useful in applications such as self-driving cars, where the car needs to understand exactly which pixels represent a drivable surface and hence where it is safe to drive. Additionally, it can be used in medical imaging to segment sections of the patient’s anatomy, which can make it easier to spot irregularities and diagnose serious diseases.</p><p><strong>U-Net</strong></p><p>In this blog, the model architecture that we will be using is a special type of Convolutional Neural Network, called a <a href="https://arxiv.org/abs/1505.04597">U-Net</a>. U-Net was initially developed for biomedical Image Segmentation, but the architecture is useful in many other applications, making it one of the most important and foundational neural network architectures of Computer Vision today.</p><p>To train and deploy such a model on Google Cloud, we’ll need to use Vertex AI’s custom training options.</p><p><strong>Custom Model Training with Vertex AI</strong></p><p>Vertex AI’s training options allow you to have more control over the model’s architecture, meaning you can train and deploy model architectures that you write yourself. It does this through the use of containers, where you can choose from either pre-built containers (available for supported frameworks such as Tensorflow), or custom container options which allow you to put your code in a Docker container and push it to the Container registry to run on Vertex AI.</p><p>This means that you can deploy pretty much any model framework or architecture you want with relative ease, and can even accelerate the training process using GPUs. <strong>Let’s get started!</strong></p><h3>Tutorial</h3><p>In this tutorial, we train and deploy a model which provides a Semantic Segmentation of <strong>urban street scene </strong>images. We will use the <a href="https://www.cityscapes-dataset.com/">Cityscapes dataset</a> for this tutorial, where the objective is to label each pixel in the image as one of the following <strong>eight</strong> categories listed under ‘Group’ in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s6gUn1S7IxO3Ayw_" /><figcaption>Fig 2: Categories in the Cityscapes dataset</figcaption></figure><h3>Creating a Project on GCP</h3><p>To get started in training a custom Image Segmentation model on Google Cloud, create a <a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects">Google Cloud project</a> and set up a Google account with <a href="https://cloud.google.com/iam/docs/understanding-roles">sufficient permissions</a>. For this tutorial, you will need permission to use Vertex AI and to create and manage Storage Buckets. You may also need to enable certain APIs such as the Vertex AI API, the Compute Engine API, and the Cloud Storage API.</p><p>Next, choose a <a href="https://cloud.google.com/compute/docs/regions-zones">region</a> to run your project in. If you would like to use a GPU to train your model, make sure to <a href="https://cloud.google.com/vertex-ai/docs/general/locations#region_considerations">choose a region where they are available</a> as they cannot be used in all regions.</p><p>Finally, create a <a href="https://cloud.google.com/storage/docs/creating-buckets">cloud storage bucket</a>. This is the location on Google Cloud where all input and output data will be stored.</p><h3>Preparing the Training Dataset</h3><p>To download and use the <a href="https://www.cityscapes-dataset.com/">Cityscapes data</a>, you will need to sign up for an account and request access. Download the <em>leftImg8bit_trainvaltest.zip</em> and <em>gtFine_trainvaltest.zip</em> files once you have access. Decompress these two files and upload the resulting folders to the base of your Cloud Storage Bucket.</p><h3>Training a Model</h3><p>The first step in training a model using Vertex AI custom training is to write a Python training script. For this tutorial, we have adapted <a href="https://keras.io/examples/vision/oxford_pets_image_segmentation/">this script</a> for use with the Cityscapes dataset. Our updated version of this script, named <strong>model.py</strong>, can be found <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/model.py">here</a>.</p><p>The first part of this script (see <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/model.py#L11-L83">here</a>) is a helper class which makes it easier to read in batches of the training images and their labels, known as segmentation masks, from the Cloud Storage Bucket. Each of these segmentation masks is a 1-D array, which has the same size as its corresponding image, where each entry relates to a pixel in the original image.</p><p>The values for each pixel contain a numeric ID which maps to one of the classes in the dataset. For example, if a pixel in the segmentation mask has a value of <strong>11, </strong>that means that the pixel is assigned to that of a <strong>building</strong>.</p><p>Note that instead of training using these classes directly we instead group them into the 8 broad categories mentioned above (flat, human, vehicle, construction, object, nature, sky, void). The <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/model.py#L23-L59">id_to_cat variable</a> is used to do this.</p><p>Finally, we define the part of the script (see <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/model.py#L147-L213">here</a>) which uses our helper classes to load in our training data from our storage bucket, create a model using the <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/model.py#L86-L142">get_model method</a> above, train a model, and save it to the storage bucket.</p><h3>Packaging the Model Code to Run Vertex AI Training</h3><p>The next step is to package up the training code as a <strong>Docker container</strong> that can be run by the Vertex AI training service. There are two main ways this can be done. One is to create our own <a href="https://cloud.google.com/vertex-ai/docs/training/create-custom-container">custom docker container</a> which packages all of the dependencies and training code together.</p><p>The other, which we use in this tutorial, is to make use of Google’s <a href="https://cloud.google.com/vertex-ai/docs/training/pre-built-containers">pre-built training containers</a>. These pre-built containers are a great option if you are training a model which uses one of the common Python libraries for Machine Learning, such as scikit-learn, TensorFlow, PyTorch, or XGBoost. Given the model in this tutorial uses the TensorFlow framework, we use a TensorFlow image here. Select the image you wish to use and make a note of its URI.</p><p>At the same time, we also select a <a href="https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers">pre-built prediction container image</a> that will be used later when <strong>deploying</strong> our trained model to a Vertex AI Endpoint. Here, again, we use a TensorFlow image. Select the image you wish to use and make a note of its URI.</p><p>We can also use <a href="https://cloud.google.com/vertex-ai/docs/training/configure-compute#specifying_gpus">GPUs</a> to train the model. Make sure you check your chosen <a href="https://cloud.google.com/vertex-ai/docs/general/locations#accelerators">GCP region</a> has GPUs available before deciding to use them.</p><p>If your region doesn’t have them available, or you do not want to use them, set the accelerator_type variable in the scripts below to “ACCELERATOR_TYPE_UNSPECIFIED” and make sure the training and prediction container images you select are for the CPU version of the particular framework you are using. Otherwise, select the GPU you wish to use and make a note of its name. For this tutorial, we use a single NVIDIA Tesla K80 GPU.</p><p>To make use of the pre-built training containers, we use the <a href="https://github.com/googleapis/python-aiplatform">Vertex AI SDK for Python</a> (aiplatform) to write a script that automatically packages up the training code with a pre-built training container and runs it on Vertex AI. You can find this script, named <strong>train.py</strong>, <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/train.py">here</a>. We need to update the following variables in the script before running it:</p><ul><li>the name of our GCP project (project_id),</li><li>the GCP region we’re using (region),</li><li>our GCS Bucket in the same region (bucket_name),</li><li>the URI of our pre-built training container image (train_image),</li><li>the URI of our pre-built prediction container image (deploy_image),</li><li>the type of GPU we want to use (accelerator_type), and</li><li>the path to our training script (script_path)</li></ul><p>When the script has run successfully, this should start a training job on Vertex AI.</p><p>Once your training job is running, you should see a new entry appear in the Training section of the Vertex AI UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j8W0cTuwNpt8nRpX" /><figcaption>Fig 3: The Training section of the Vertex AI UI.</figcaption></figure><p>You can click into your training job, select its associated <strong>CustomJob</strong>, and then select <strong>View Logs</strong> to view the logs produced as your model trains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MgDNJ9WQrN5ZWqVi" /><figcaption>Fig 4: Logs Explorer in Vertex AI</figcaption></figure><h3>Deploying Your Model on Vertex AI</h3><p>Wait until your model has finished training, then click again on its training job entry in the Vertex AI. This will take you to the entry for your model artifact in the Model Registry. Click on <strong>Version Details</strong> here and make a note of your model’s ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QNj9KNiJhSvvBv25" /><figcaption>Fig 5: The Model Registry</figcaption></figure><p>Once again we make use of the Vertex AI Python SDK to deploy the trained model to a Vertex AI Endpoint. To do this we need to supply the <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/deploy.py"><strong>deploy.py</strong> script</a> with the project_id, region, bucket_name and accelerator_type variables, and also provide the model’s ID (model_id).</p><p>Once your model has been deployed, you should see an entry appear in the <strong>Endpoints</strong> section of the Vertex AI UI for your model. Make a note of the ID of this endpoint, as we will need it when using the model to make predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TKrn28-egD0_ZncN" /><figcaption>Fig 6: Vertex AI Endpoints</figcaption></figure><h3>Using Your Deployed Model to Segment an Image</h3><p>We will now use our model to segment a test image. The <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/predict.py"><strong>predict.py</strong> script</a> takes the image, converts it to a numpy array and sends it to the endpoint. The deployed model returns a segmentation mask which is colourised and saved as a PNG (mask.png) using the Pillow Python library. After this, the script overlays the segmentation mask onto the test image and also saves this overlay as a separate PNG (overlay.png).</p><p>Remember to update the project_id, region, and bucket_name variables, and provide the path to the test image (image_path)and also the ID of the deployed endpoint (endpoint_id) in the script below. Then, run it to test your deployed model.</p><h3>Results</h3><p>Finally, we can examine the two output images to see how well the model performed at segmenting the test image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pULDhyDmOg6AW_sx" /><figcaption>Fig 7: The original image used in our Semantic Segmentation example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SXzPTclIIUc8Rz7C" /><figcaption>Fig 8: The segmentation mask</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9yrMztUXoYq6G58" /><figcaption>Fig 9: The segmentation mask overlaid on the original image</figcaption></figure><p>As you can see, in this case, the model has successfully segmented the image into its component parts. The cars parked on the street (pink) are separated from the trees (green) and buildings (red) surrounding them. The bonnet of the driving car (white) is separated from the road (grey), and the sky (blue) is separated from the trees (green).</p><p>The full list of colour mappings is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*Q5-KVZdURKq-vAre" /><figcaption>Fig 10: The list of colour mappings</figcaption></figure><p>It is worth acknowledging that the boundaries of the masks here are a bit fuzzy; this is because we are shrinking all of our images to 160×160 pixels during training and prediction to simplify the training process. If you want to improve on these results, feel free to try reducing the amount of shrinkage as this may help to make the boundaries between objects sharper. Additionally, we advise experimenting with training the model for a greater number of epochs (defined in train.py), as this should give better results.</p><h3>Summary</h3><p>In this article, we’ve shown you how you use Vertex AI to train and deploy a custom Image Segmentation model. Hopefully, by now you’ve realised how easy it is to train and deploy your model using Vertex AI once you have developed it. Although the focus of this blog was on Image Segmentation, you can use the same training and deployment methods via the Vertex AI Python SDK for a much larger range of Machine Learning tasks.</p><p>The scripts we’ve provided in this blog are easily adaptable, with very few modifications needed to be made to the <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/train.py"><strong>train.py</strong></a> and <a href="https://github.com/teamdatatonic/image-segmentation-blog-scripts/blob/main/deploy.py"><strong>deploy.py</strong></a> scripts in particular, so we hope you enjoy tweaking them for your own use case!</p><p><strong><em>As 4x Google Cloud Partner of the Year, Datatonic has a wealth of experience in Computer Vision, Machine Learning, and a range of Google products and services. </em></strong><a href="http://datatonic.com/contact"><strong><em>Get in touch</em></strong></a><strong><em> to learn how your business can benefit from Computer Vision or other Machine Learning models.</em></strong></p><p>Check out our other Computer Vision blogs in this series:</p><p><strong>Part 1: </strong><a href="https://datatonic.com/insights/computer-vision-insights-datatonic-experts/"><strong>Computer Vision: Insights from Datatonic’s Experts</strong></a></p><p><strong>Part 2: </strong><a href="https://datatonic.com/insights/computer-vision-future-google-cloud/"><strong>Computer Vision: Emerging Trends and Google Cloud Technology</strong></a></p><p><strong>Part 3: </strong><a href="https://datatonic.com/insights/computer-vision-object-detection-vertex-ai-automl/"><strong>Computer Vision: Object Detection and No-Code AI with AutoML</strong></a></p><p><strong>Part 4: </strong><a href="https://datatonic.com/insights/deploying-image-segmentation-models-vertex-ai/"><strong>Computer Vision: Deploying Image Segmentation Models on Vertex AI</strong></a></p><p><strong>Part 5: </strong><a href="https://datatonic.com/insights/computer-vision-generative-models-conditional-image-synthesis/"><strong>Computer Vision: Generative Models and Conditional Image Synthesis</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e51ca67a7ed4" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/computer-vision-deploying-image-segmentation-models-on-vertex-ai-e51ca67a7ed4">Computer Vision: Deploying Image Segmentation Models on Vertex AI</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision: Object Detection and No-Code AI with AutoML]]></title>
            <link>https://blog.montrealanalytics.com/computer-vision-object-detection-and-no-code-ai-with-automl-cad8e5c35d1d?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cad8e5c35d1d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 11:50:51 GMT</pubDate>
            <atom:updated>2022-09-20T11:50:51.751Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6c2vLzzZPPR0D3C_luvRQ.jpeg" /></figure><p>In the <a href="https://datatonic.com/insights/computer-vision-insights-datatonic-experts/">first</a> and <a href="https://datatonic.com/insights/computer-vision-future-google-cloud/">second</a> parts of this Computer Vision blog series, we spoke with some of Datatonic’s experts to hear their experiences of Computer Vision, and where it is heading in the next few years. This blog will provide a step-by-step walkthrough of how to develop your own Computer Vision model, train it on Google Cloud, and deploy it <strong>without writing a single line of code</strong> courtesy of <strong>Vertex AI’s AutoML </strong>service.</p><h3>Introducing AutoML on Vertex AI</h3><p>One of the key trends in Machine Learning in 2022 is <strong>no-code AI</strong>: an efficient method to get started on AI projects with minimal effort or domain knowledge. The <a href="https://cloud.google.com/vertex-ai/docs/start/automl-users">Vertex AI AutoML</a> service is an example of this trend and allows developers, software engineers, or just curious minds to train efficient, high-quality Machine Learning models effortlessly.</p><p><strong>AutoML</strong> caters to a wide range of applications, which includes extracting insights from tabular, language, and image data. The service is well suited to rapid experimentation during the early stages of a project, developing proof of concepts, and even building high-performance models to serve both online and offline (Edge).</p><h3>Object Detection</h3><p>In <strong>Object Detection</strong>, our goal is to locate instances of desired objects within images. For those of you with more of a Machine Learning background, the task can be thought of as both classification and regression; the network uses a classification head for predicting the class type and the regression head of the network is used for optimising the bounding box location. To put it simply, we are training a model to draw boxes around desired objects in an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0V4PCyW3KKRbem00" /><figcaption><em>Fig 1: Object Detection being used to monitor traffic</em></figcaption></figure><p>Object Detection has many applications that can help automate processes in various industries. Examples include locating faults within parts on a production line or monitoring the types of traffic on certain roads. In this walkthrough, we build a <strong>Datatonic Logo Detector</strong>, where the objective is to locate and draw boxes around every instance of the Datatonic logo within an image.</p><h3>Creating a Vertex AI Managed Dataset</h3><p>Within Google Cloud head over to <strong>Vertex AI </strong>(found within the navigation menu on the left-hand side of the User Interface), and navigate to the <strong>“Datasets”</strong> section to begin your project. Select <strong>“CREATE” </strong>and follow the steps to set up your dataset of choice; in this case,<strong> “Image object detection”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5ZIcvDIQ9hcr-GJJ" /><figcaption><em>Fig 2: Creating a managed dataset on Vertex AI</em></figcaption></figure><p>Next, we will need to import our image data. From within your dataset, navigate to the <strong>“IMPORT”</strong> tab and choose the<strong> “Upload images from your computer” </strong>option, and select your data for upload. In this example, we are going to define our Training, Validation, and Test sets via the User Interface (UI), so leave <strong>“Data split”</strong> as <strong>“Default”</strong> when importing. The images will be uploaded to Google Cloud Storage so you must also specify a Cloud Storage bucket for them to be stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*V7o45zWWZHhv-to9" /><figcaption><em>Fig 3: Adding images to your Vertex AI dataset</em></figcaption></figure><h3>Data Labelling</h3><p>Once your dataset has been uploaded, it is time to start the data labelling process. This is where we tell the Object Detection algorithm what to learn by drawing boxes around the desired objects and classifying them. Each group of objects we would like to detect, such as cats or dogs, are called classes. In this case, bounding boxes are drawn around only a single class: the Datatonic logo. However, it is possible to label and classify multiple classes.</p><p>Navigate to the “<strong>BROWSE” </strong>tab and under <strong>“Images”</strong> select <strong>“ADD NEW LABEL”</strong> and add a label for each class you would like to train on. Ideally, we should have an equal number of examples of each class within the dataset to give AutoML the best chance to perform well across your data; this is called balancing the classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tGgr25rn0bhawjYN" /><figcaption><em>Fig 4: Labelling data for the Object Detection model</em></figcaption></figure><p>To label your data, select an image in your Vertex AI Dataset and then click on <strong>“Add bounding box” </strong>in the toolbar above your image. Simply click to draw your bounding boxes around the desired objects — all occurrences if there is more than one in an image. Draw these bounding boxes as tightly as possible around the perimeter of the objects; this <strong>reduces unnecessary noise</strong> and helps the algorithm to learn your objects better.</p><p>After drawing each bounding box, you will be prompted to confirm which class the objects belong to. Follow this procedure until all of your data is fully labelled. The labelling service provided by Vertex AI’s managed datasets is another key advantage to using Google Cloud as this avoids the difficulties associated with using external labelling software.</p><p>If you have a lot of images to label, you can also take advantage of another Vertex AI service and let others label the images for you. Simply navigate to <strong>“CREATE LABELING TASK” </strong>to specify your labelling instructions, but bear in mind this will incur <a href="https://cloud.google.com/vertex-ai/pricing#labeling">additional charges</a>.</p><h3>Object Detection Model Training</h3><p>Typically, one of the most time-consuming aspects of a Machine Learning project is model development, where it can take many weeks to experiment with different modelling approaches and custom algorithms to find the optimal solution.</p><p>With Vertex AI’s AutoML, users do not need to spend time on model selection, experimentation, or hyperparameter tuning; this is all taken care of, allowing for more time to be spent on other areas, such as data collection or building the infrastructure around productionising your solution.</p><p>Users are also not limited by the constraints of their local machines, which often affect the algorithms chosen and training time; Vertex AI will handle the compute resources used for training your complex models.</p><p>To commence training, select <strong>“Train new model” </strong>from the panel on the right-hand side of the UI, and within <strong>“Training method” </strong>select “AutoML”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*5w9Pwx4CLGRxBpwR" /><figcaption><em>Fig 5: Defining training, validation, and test data splits</em></figcaption></figure><p>For AutoML to train on your data, it needs three dataset splits: training data (used during training), validation data (used to monitor training), and test data (used for testing after the model has trained).</p><p><strong>In terms of splitting your data into these sets, there are several options:</strong></p><ol><li>Allow Vertex AI to do this randomly for you, where you only need to determine the split percentages (the default is 80% Train, 10% Validation, and 10% Test).</li><li>Manually select images for each set via the UI (use the <strong>“ASSIGN ML USE” </strong>option).</li><li>Specify within the image import JSONL file.</li></ol><p>Using the default splits that AutoML generates for you is the easiest and quickest method and reduces the complexity of your project. If you choose to manually select which images are present in your training, validation, and test sets, then it is advised to keep the splits similar to the defaults, and ensure that each set has equal proportions of each class.</p><p>By selecting the <strong>“Randomly assigned” </strong>option within <strong>“Model details”</strong>,<strong> </strong>the splits are taken care of for you so you can jump straight into training (Fig 5).</p><p>Despite taking care of model training and selection for you, Vertex AI’s AutoML allows for the specification of certain model characteristics to suit your use case. In addition to allowing for online and offline model serving, you can specify whether to optimise for accuracy or low latency under <strong>“Training options”</strong>.<strong> </strong>This gives control to the user to mould the AutoML model to the project requirements or business needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*5k6XYX6jkpN3i5Cg" /><figcaption><em>Fig 6: Selecting your training options</em></figcaption></figure><p>For <strong>“Compute and pricing”</strong>,<strong> </strong>it is important to be aware of the costs associated with using <a href="https://cloud.google.com/vertex-ai/pricing#americas">Vertex AI’s AutoML service</a>. A useful tip for when you submit your training job is to ensure “<strong>Enable early stopping”</strong> is selected (Fig 7). This means that when the model has converged (essentially meaning it will not learn anymore from the data provided) training will stop, and you will only be charged for node hours used instead of the full budget allocated.</p><p>When ready, select <strong>“START TRAINING” </strong>and you can now relax without the need to monitor live model metrics, as this is also taken care of for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*JLHMQCI0uI_oqObR" /><figcaption><em>Fig 7: Selecting the training length and pricing options</em></figcaption></figure><h3>Model Evaluation</h3><p>Once training is complete (the status of this can be found under Vertex AI <strong>“Training”</strong>), you can then navigate to the <strong>“Models” </strong>page to analyse its performance by simply selecting your model and version. The <strong>“EVALUATE”</strong> tab allows you to see key metrics relating to your model’s performance such as <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#evaluation_metrics_returned_by">precision</a>, <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#evaluation_metrics_returned_by">recall</a>, and <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#evaluation_metrics_returned_by">average precision</a> as well as providing you with various graphs which allow you to gain a deeper understanding of your model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*we0NGzx0bKRMUy4K" /><figcaption><em>Fig 8: Evaluating the model performance</em></figcaption></figure><p>To observe a more detailed, object-by-object analysis, select a class beneath the <strong>“All labels” </strong>section. The UI shows how your model is performing on your test images by displaying your <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#how_you_use_model_evaluation_metrics">True Positives</a>, <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#how_you_use_model_evaluation_metrics">False Positives</a>, and <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#how_you_use_model_evaluation_metrics">False Negatives</a>. This means you can see which images your model performs well on, and where it could improve, allowing for data-driven decisions to be made for improving performance.</p><p>For example, is there a particular type of class or image angle that is not performing so well? If so, you can tailor your dataset to include more images of these occurrences. Even without Machine Learning expertise, it is straightforward to understand how your model is behaving via this evaluation service.</p><p>There are also some slightly more technical aspects of the service; you can alter the <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#evaluation_metrics_returned_by">confidence</a> and <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#evaluation_metrics_returned_by">IOU thresholds</a> that are used when calculating whether an instance is a True Positive, False Positive, or False Negative, and thus visualise how these thresholds are affecting your results. You can also alter the desired confidence threshold when serving your model based on whether you wish to prioritise precision or recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EBKcwMAISvydv6y0" /><figcaption><em>Fig 9: True Positives, False Positives, and False Negatives of the Datatonic Logo class</em></figcaption></figure><h3>Model Deployment</h3><p>Once you are happy with your model, it is time to deploy and see it in action! Navigate to the <strong>“DEPLOY &amp; TEST”</strong> tab and follow the instructions to create your endpoint. This will deploy your model to Google Cloud.</p><p>With AutoML Edge, you are also able to export your model as a TensorFlow Lite model, a TensorFlow SavedModel to run in a docker container, or as a TensorFlow.js package for running in a browser. This flexibility in deployment methods is another reason why this service is so beneficial to so many users.</p><p>Once you have deployed your model to an endpoint, you can test it by uploading images to the UI to see it in action! As we can see in Fig 10, the model has predicted many bounding boxes for the image. On the right-hand side, we can see the confidence of the predictions, and ignore the low ones. If you hover your cursor over the predictions, then the bounding box they relate to is highlighted. In this case, it successfully classified the three logos! Remember to undeploy your model from the endpoint when you are finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2RvjfwSwTofK8dWI" /><figcaption><em>Fig 10: Deployed model predictions</em></figcaption></figure><h3>Diving Deeper into Object Detection and AutoML</h3><p>So far, we have discussed the no-code, no-ML-expertise-needed approach to AutoML. However, for those of you who are curious to dive deeper into the service to integrate your model into your application then I encourage you to take advantage of <a href="https://cloud.google.com/vertex-ai/docs/reference/rest">Vertex AI’s API</a>. You can use this to <a href="https://cloud.google.com/vertex-ai/docs/training/automl-api">train</a> your model, <a href="https://cloud.google.com/vertex-ai/docs/predictions/deploy-model-api#deploy_the_model">deploy</a> it to an endpoint, call <a href="https://cloud.google.com/vertex-ai/docs/samples/aiplatform-predict-image-object-detection-sample#aiplatform_predict_image_object_detection_sample-python">online predictions</a>, make <a href="https://cloud.google.com/vertex-ai/docs/predictions/batch-predictions#image">batch predictions</a> on a set of data, and to further <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#api">evaluate</a> your model’s performance with metrics such as the <a href="https://cloud.google.com/vertex-ai/docs/training/evaluating-automl-models#evaluation_metrics_returned_by">F1 score</a>.</p><h3>Summary</h3><p>With Vertex AI’s AutoML service, Machine Learning has become much more accessible and democratised for users with little prior expertise in the area. The quality of no-code Machine Learning solutions is only going to get better over <a href="https://datatonic.com/insights/computer-vision-future-google-cloud/">the next few years</a> and the high performant and easy-to-productionise nature of Vertex AI’s AutoML means that the service can allow for the fast integration of AI into businesses to rapidly generate real value.</p><p><strong><em>As 4x Google Cloud Partner of the Year, Datatonic has a wealth of experience in Computer Vision, Machine Learning, and a range of Google products and services.</em></strong><em> </em><strong><em>Check out our </em></strong><a href="https://demohub.datatonic.com/"><strong><em>Object Detection Model</em></strong></a><strong><em> on the Datatonic Demo Hub, and </em></strong><a href="http://datatonic.com/contact"><strong><em>contact us here</em></strong></a><strong><em> to discuss how using Object Detection or other Machine Learning models could help your business!</em></strong></p><p>Check out our other Computer Vision blogs in this series:</p><p><strong>Part 1: </strong><a href="https://datatonic.com/insights/computer-vision-insights-datatonic-experts/"><strong>Computer Vision: Insights from Datatonic’s Experts</strong></a></p><p><strong>Part 2: </strong><a href="https://datatonic.com/insights/computer-vision-future-google-cloud/"><strong>Computer Vision: Emerging Trends and Google Cloud Technology</strong></a></p><p><strong>Part 3: </strong><a href="https://datatonic.com/insights/computer-vision-object-detection-vertex-ai-automl/"><strong>Computer Vision: Object Detection and No-Code AI with AutoML</strong></a></p><p><strong>Part 4: </strong><a href="https://datatonic.com/insights/deploying-image-segmentation-models-vertex-ai/"><strong>Computer Vision: Deploying Image Segmentation Models on Vertex AI</strong></a></p><p><strong>Part 5: </strong><a href="https://datatonic.com/insights/computer-vision-generative-models-conditional-image-synthesis/"><strong>Computer Vision: Generative Models and Conditional Image Synthesis</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad8e5c35d1d" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/computer-vision-object-detection-and-no-code-ai-with-automl-cad8e5c35d1d">Computer Vision: Object Detection and No-Code AI with AutoML</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision: Emerging Trends and Google Cloud Technology]]></title>
            <link>https://blog.montrealanalytics.com/computer-vision-emerging-trends-and-google-cloud-technology-39cf100c8bff?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/39cf100c8bff</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 16:01:59 GMT</pubDate>
            <atom:updated>2022-09-16T16:01:59.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nrQtmdylMDaAnLVpFkdWA.jpeg" /></figure><p>In the <a href="https://datatonic.com/insights/computer-vision-insights-datatonic-experts/">first blog of this series</a>, we explored some of the most exciting current use cases of Computer Vision, and how they are already starting to benefit our daily lives, as well as businesses. In this blog, we spoke with some of the team again to hear more about where Computer Vision is heading, and how Google Cloud can be used to make it all happen!</p><h3>The Future of Computer Vision</h3><p>Much of the future use of Computer Vision is dependent on its increased availability as it becomes more widely used; new models can build upon accumulated research and training and create innovative use cases more easily. We are only just scratching the surface of what Computer Vision is capable of, so <strong>we asked some of the team about what they expect in the near future:</strong></p><p><strong><em>Where do you see Computer Vision heading in the next few years?</em></strong></p><ol><li>Democratisation</li></ol><p><a href="https://www.linkedin.com/in/christellexu/"><em>Christelle Xu, Business Analyst</em></a><em>: I think we’ll see the </em><strong><em>democratisation of tooling </em></strong><em>that Data Scientists can use to develop sophisticated use cases. So for example, something that used to take hundreds of lines of code and deep expertise can now be deployed more easily by a Data Scientist using </em><strong><em>AutoML</em></strong><em> or </em><strong><em>XGBoost</em></strong><em>. I think with respect to Computer Vision, a lot of the tooling will become more democratised and </em><strong><em>more accessible to Data Scientists</em></strong><em>, so what used to be novel will be much more common. In the next few years, we’re going to begin to see more tooling to support easier modelling of use cases. We’re already starting to see it now with </em><a href="https://cloud.google.com/vision"><em>Vision AI</em></a><em> and </em><a href="https://cloud.google.com/document-ai"><em>Document AI</em></a><em>. Those use cases will largely be in areas that drive business value.</em></p><ol><li>Deploying Computer Vision Use Cases to Remain Competitive</li></ol><p><a href="https://www.linkedin.com/in/tobi-lipede/"><em>Tobi Lipede, Senior Data Scientist</em></a><em>: In certain industries, it’s going to be necessary </em><strong><em>to keep a competitive edge</em></strong><em> by leveraging Computer Vision. In industries like manufacturing, agriculture, and others with complex supply chains, companies that don’t begin to leverage Computer Vision will lose their ability to compete quite quickly and won’t be able to scale as fast as others. </em><strong><em>In the next couple of years, I definitely see it becoming a lot more standard.</em></strong></p><ol><li>Enhancing Hardware</li></ol><p>Currently, many companies do not realise the power of the hardware they are using in more traditional manners, or how the application of simple Computer Vision installations can power modelling that creates hugely beneficial value for their business.</p><p>The agricultural sector has already started to incorporate several use cases of artificial intelligence and Computer Vision in areas such as plant health detection and monitoring, planting, weeding, harvesting, and advanced analysis of weather conditions. We developed a <a href="https://datatonic.com/case-studies/image-recognition-google-cloud-crocus/">similar model for Crocus</a> which is able to classify over 5000+ different plant varieties in under 30 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N0qhzhf4VeZeUAYo" /><figcaption><em>Fig 1: Some of the features available in Crocus’ mobile application, Iris.</em></figcaption></figure><p>Applying Computer Vision to such industries would enable multiple possible use cases for already-existing hardware to have a more powerful impact on businesses. For example, Computer Vision would enable the augmentation of data powered by CCTV and satellite imagery.</p><p><em>Christelle Xu: I think one of the biggest challenges we have with Computer Vision is that companies want to get involved but don’t always have cameras or the right data. This is part of the reason why big factories and the manufacturing industry, for example, can accelerate Computer Vision use cases, because often they </em><strong><em>already have cameras and mature image, video and IoT data</em></strong><em>. Many companies need help not only identifying use cases but also advice about the best approaches to collect data quickly and cost-efficiently, ultimately creating meaningful use cases with strategic business impact. This is something we’ve been working on with our clients at Datatonic.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*pKk0rI6u1yWoOhYb" /><figcaption><em>Fig 2: Computer Vision being used to monitor the safety of workers in a warehouse</em></figcaption></figure><p><strong>On Edge Deployment</strong></p><p><a href="https://www.linkedin.com/in/mgela/"><em>Matt Gela, Senior Data Scientist</em></a><em>: One of the interesting trends is that Computer Vision models will be deployed more and more </em><strong><em>on edge devices</em></strong><em>, meaning we can capture and process images in near real-time, without a connection to the cloud when making predictions. This allows Computer Vision to perform tasks where action may need to be taken immediately, which will greatly advance its use in areas such as manufacturing safety.</em></p><p>Edge computing brings computation and data storage closer to the devices where it’s being collected, rather than relying on a central location. One significant advantage of this is the increased speed of Machine Learning models.</p><p><em>Christelle Xu: On edge means being able to use Machine Learning at the point of the user. For example, I can use Computer Vision on my phone or my laptop, which can run much faster while also </em><strong><em>maintaining the user’s privacy</em></strong><em>. I think part of my excitement is seeing how we reach a point where it is much more widespread.</em></p><p>One example of this is Google Lens, which allows you to use <strong>Optical Character Recognition</strong> on your mobile phone. This can be used for instant search features, as well as translation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*VkkClJAbikAglcPS" /><figcaption><em>Fig 3: Google Lens being used on edge to translate text</em></figcaption></figure><p><strong>Building Upon Existing Models</strong></p><p>The future of Computer Vision is also likely to see us improving upon existing types of models, for similar use cases that we are starting to experiment with:</p><p><em>Alex Thomas: I think text-to-image generation is going to be increasingly used over the next few years. These are the early days for this technique and I could see it getting better and expanding as time goes on. Potentially in the future, we could even generate 3D assets just by typing out some text.</em></p><p>Computer Vision is expected to develop in many ways by building upon existing work. Some of the most significant and universal developments over the next few years will be:</p><ul><li>Models that require <strong>fewer data points to train on</strong> before they are ready for deployment, significantly reducing training time and cost.</li><li>Ability to apply <strong>pre-trained models</strong> to other use cases; this will grow exponentially as more models are developed and more work involving Computer Vision is carried out.</li><li>Models that incorporate <strong>emerging types of imagery</strong>, enabling us to work within three dimensions. This includes Computer Vision that can incorporate other features such as depth and density.</li></ul><p>Furthermore, developing better models faster and more easily will help to enable the <strong>aggregation of models</strong>. By having several models in one place, we can combine them, and create a propensity model supported by scalable architecture (MLOps) with pipelines that can support multiple complex models. This would also allow for data unification through a data warehouse. To learn more about MLOps, look at <a href="https://datatonic.com/case-studies/">some of our case studies</a>, or check out our recent <a href="https://datatonic.com/insights/vertex-ai-mlops-platform/">MLOps 101 webinar</a> about how to get started with Machine Learning at scale.</p><p><strong>Multimodal Models</strong></p><p>We’re heading toward greater adoption of<strong> multimodal models</strong> — Computer Vision models with various data sets added. This can be done by aggregating the data from various models or developing a single model with customised architecture, enabling us to create <strong>models that use a combination of inputs such as image, text, and sound.</strong> These models are especially powerful in situations where we need to make a decision based on multiple different types of input, such as reviewing and analysing evidence in legal cases.</p><p>This is already being developed through Visual Question Answering (VQA), a Computer Vision task where a system is given text-based questions about an image and can infer the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tslBYgV4SfI1N071" /><figcaption><em>Fig 4: Formula 1 cars on a race track</em></figcaption></figure><p>For example, you could type “What sport is this?”, and a trained Computer Vision model could tell you it is Formula 1. Alternatively, you could ask for the main colour of the car at the front (orange). While these examples seem relatively simple, they require our model to have a complex understanding of both image and language and there are several potential real-life use cases.</p><p><strong>Integrating Computer Vision Models</strong></p><p>Computer Vision models should not be seen as isolated from the more traditional data found within businesses. They can be used to exploit previously siloed data points and integrate them into Modern Data Stacks or multi-model architectures to create significant overarching business value.</p><p>Images are often accompanied by text or metadata, which can all be combined through related modelling to produce a more <strong>informed and powerful output. </strong>Computer Vision models detecting anomalies on a factory floor could be combined with other testing data to determine the impact of a product flaw or inconsistency (e.g., identifying cracks using Computer Vision combined with the vibration of moving parts, the tension of screws, or the frequency of sound emitted during testing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*9wWh1cY9zO6ebZDK" /><figcaption><em>Fig 5: Crack detection using Computer Vision</em></figcaption></figure><p><strong>Internet of Things (IoT)</strong></p><p>The <a href="https://www.wired.co.uk/article/internet-of-things-what-is-explained-iot">Internet of Things</a> describes physical objects with sensors, processing ability, software, or other technologies that connect and exchange data with other devices and systems over the Internet or other communications networks. As the technology becomes more advanced, Computer Vision will likely be used in more devices which make up the IoT.</p><p><em>Christelle Xu: I find the Internet of Things (IoT) interesting. With regard to Computer Vision, I’m looking forward to the </em><strong><em>increased availability, resiliency, and speed</em></strong><em> that will be enabled as a result of improved technology, particularly as edge technology matures. We may already have a lot of IoT devices in our homes, but I’m interested in the use cases that begin to exist, as this technology matures. Furthermore, from a business perspective, manufacturers will be able to create new products with differentiators, enabling them to grow their business. The company can form a partnership with Google, and ultimately, customers are excited because they can take advantage of innovative products.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_2kC4whVgTCu8Pir" /><figcaption><em>Fig 6: Google Home, an IoT smart home device</em></figcaption></figure><p>The IoT already includes devices such as Google Home, as well as wearable smartwatches. Computer Vision is likely to play a bigger role in the IoT over the next few years with devices such as next-generation home security systems, which make use of Computer Vision models including facial recognition and action recognition.</p><p><strong>Facial Recognition</strong> — matching faces to identities. Commonly used for:Security applications, allowing people into restricted areasUnlocking smartphones</p><p><strong>Computer Vision and Image Captioning</strong></p><p><a href="https://www.linkedin.com/in/sofieverrewaere/"><em>Sofie Verrewaere, Senior Data Scientist</em></a><em>: I’d like to see more </em><strong><em>Computer Vision being used for people who are visually impaired </em></strong><em>to interpret</em><strong><em> </em></strong><em>the objects in their surroundings</em><strong><em>.</em></strong><em> The next frontier for Computer Vision technologies could be acquiring and utilising </em><strong><em>visual common sense reasoning</em></strong><em> so that machines can move beyond just identifying the types of objects in image data. Computer Vision could then be used to answer more complex questions, such as who is doing what and for what reason?</em></p><p><strong>Image Captioning</strong> — automatically writing descriptive captions for images and videos. Commonly used for:<br>+ Describing visual media for visually impaired people<br>+ Summarising and identifying key points in a video</p><p>Projects such as Google’s <a href="https://blog.google/outreach-initiatives/accessibility/get-image-descriptions/"><em>Get Image Descriptions from Google</em></a> have come a long way in the field of automatic image description features. This software uses Computer Vision to generate image descriptions for images that do not have any alt text.</p><p>Computer Vision is being used in a multitude of ways to aid visually impaired people. A study of one use case found that people using a long cane or a guide dog were able to reduce the <a href="https://eandt.theiet.org/content/articles/2021/07/wearable-computer-vision-aid-helps-blind-people-avoid-collisions/">number of collisions by 37 per cent</a> with a wearable Computer Vision aid. The user wears a camera and two wristbands that vibrate when the camera detects a potential upcoming collision, prompting the user to stop and change direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/0*-WkJM45D03DBnuWz" /><figcaption><em>Fig 7: Image processing unit of the wearable collision avoidance device</em></figcaption></figure><p>Over the next few years, trends suggest that developments in Computer Vision and wearable technology will become even more valuable in use cases that aim to assist visually impaired people.</p><p><strong>Scaling Computer Vision</strong></p><p>As previously mentioned, we are still in the ‘exploitation’ phase of Computer Vision applications in the industry. Models are being developed, but in a lot of cases, they are not being applied at scale yet. There are a few reasons for this:</p><ul><li>Image and video data can initially be difficult to work with; they can take up more space than some other types of data and have different formats.</li><li>Companies are not aware of the value that this data holds; they know that their spreadsheets and tables have value but not necessarily the image and video data that they collect.</li><li>Computer Vision can sometimes be more costly than ‘standard’ Machine Learning models and sometimes requires a higher upfront investment.</li></ul><p>However, deploying effective Computer Vision models can provide a <strong>huge Return On Investment (ROI)</strong>. Computer Vision can be used to automate many tasks, leading to <strong>lower running costs and less manual effort for less complex tasks</strong>. It can also be used to find less expensive solutions to problems, often by simply integrating Computer Vision into existing hardware to remove the need for manual monitoring. The sooner businesses invest in Computer Vision, the sooner they will be able to benefit from these long-term advantages!</p><h3>Using Google Cloud</h3><p>Obstacles to developing and productionising effective Computer Vision models can be overcome by using Google Cloud, and its various applications and services.</p><p><strong><em>Why use Google Cloud? What are some of the useful tools available?</em></strong></p><p><em>Alex Thomas: The big tool that you’ll hear a lot of people talking about, for Computer Vision, in particular, is Google Cloud’s </em><strong><em>AutoML</em></strong><em>. At the moment you can use it for </em><strong><em>Object Detection </em></strong><em>and </em><strong><em>Image Classification</em></strong><em>. It’s relatively straightforward to develop a solution as you don’t have to use any coding or know Machine Learning in-depth to get started. On the most recent project I worked on, we used AutoML, and it was </em><strong><em>easy for us to iterate on and improve our model</em></strong><em> throughout the project. We could train a model, quickly see how it performed, tweak the images, and then </em><strong><em>generate an improved model.</em></strong><em> I think that’s the silver bullet that Google Cloud has over many of its competitors…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sBoh1jy7Cllr8kuM" /></figure><p><em>…Google also created a framework called </em><strong><em>TensorFlow</em></strong><em> which is a key piece of software used to build neural networks for Computer Vision work. A lot of Google Cloud services tie in well with TensorFlow. If you’ve built something that’s really cutting-edge, it’s easier to deploy it with Google Cloud and get it out there than with other platforms. You can deploy a high-tech model with only a few lines of code.</em></p><p>Being able to get started on Machine Learning models without needing massive amounts of coding experience makes it a lot more accessible for businesses, greatly <strong>reducing the time and cost to develop and deploy a model.</strong></p><p><em>Tobi Lipede: I’ve previously worked with other cloud providers. I think what distinguishes Google Cloud is </em><strong><em>how easy it is to get started</em></strong><em>. Something as simple as setting up a notebook environment in Google Cloud can be done without major DevOps/SRE overheads. Their hierarchical permissions model is simple to reason about while maintaining security. Going from the notebook to production is easy too — integrations between the (Vertex AI) workbench, BigQuery, the feature store and endpoints work really well</em><strong><em>.</em></strong></p><p><em>“Google Cloud has many great APIs that trickle down from Google’s cutting-edge research, which will enable customers to implement Computer Vision features </em><strong><em>with ease and great benefit.” — </em></strong><a href="https://www.linkedin.com/in/danielmiskell/"><em>Daniel Miskell, Machine Learning Engineer</em></a></p><p><em>Christelle Xu: I think for Google Cloud, the way that it tries to differentiate itself is in the Machine Learning space with tools such as </em><a href="https://cloud.google.com/vertex-ai"><em>Vertex AI</em></a><em>. With Computer Vision in Google Cloud, there are loads of features available through AutoML, letting you use tools like </em><a href="https://cloud.google.com/vision"><em>Vision AI</em></a><em> and </em><a href="https://cloud.google.com/document-ai"><em>Document AI</em></a><em>. These are fast-forwarded tools that use transfer learning; a lot of the deep learning has already been done and all you need to do is train it on your data, and all of a sudden, you have the power of Google Cloud behind you which you can apply to your business use case.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rImUQodMwSR-JVDs" /><figcaption><em>Fig 8: Google’s Document AI turns unstructured documents into clear structured insights</em></figcaption></figure><p>The features and services provided by Google will continue to enable rapid progress toward the exciting Computer Vision developments and use cases discussed in this blog. The next blog in this series will talk you through setting up your own <strong>Object Detection model </strong>using Vertex AI’s AutoML <strong>without a single line of code!</strong></p><p><strong><em>As 4x Google Cloud Partner of the Year, Datatonic has a wealth of experience in Computer Vision, Machine Learning, and a range of Google products and services. </em></strong><a href="http://datatonic.com/contact"><strong><em>Get in touch</em></strong></a><strong><em> to learn how your business can benefit from Computer Vision or other Machine Learning models.</em></strong></p><p><strong>Contributors: </strong><a href="https://www.linkedin.com/in/christellexu/"><strong>Christelle Xu, Business Analyst</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/tobi-lipede/"><strong>Tobi Lipede, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/mgela/"><strong>Matt Gela, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/alex-thomas-4286549b/"><strong>Alex Thomas, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/sofieverrewaere/"><strong>Sofie Verrewaere, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/danielmiskell/"><strong>Daniel Miskell, Machine Learning Engineer</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39cf100c8bff" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/computer-vision-emerging-trends-and-google-cloud-technology-39cf100c8bff">Computer Vision: Emerging Trends and Google Cloud Technology</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision: Insights from Datatonic’s Experts]]></title>
            <link>https://blog.montrealanalytics.com/computer-vision-insights-from-datatonics-experts-48e69fdebf88?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e69fdebf88</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 12:39:19 GMT</pubDate>
            <atom:updated>2022-09-16T12:39:19.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*on41nocvOfmF54jT4ABYMw.jpeg" /></figure><p><strong>Computer Vision</strong> is a field of Artificial Intelligence that enables computers to derive meaningful information and data from digital images, videos and other visual inputs. This blog, the first in a series about Computer Vision, will cover a brief history of Computer Vision, and then look at some of the most exciting use cases right now. Our future blogs will explore the future of Computer Vision, how Google Cloud Platform can help deploy your Computer Vision models, and how to create your own Object Detection model!</p><p>Computer Vision has been used for decades, becoming more popular in 2012 with the release of AlexNet, a Convolutional Neural Network (CNN) architecture, that won the <strong>ImageNet Large Scale Visual Recognition Challenge</strong>. AlexNet’s success established numerous best practices for CNNs moving forward, and in the last ten years, Computer Vision has evolved rapidly due to improved computational power, better graphics processing, and modern GPUs. This has been accelerated by the creation of large labelled datasets, such as <a href="https://www.image-net.org/">ImageNet</a>, which is comprised of 14 million images.</p><p>Due to these advances, Machine Learning models are now much better feature extractors than humans and are more efficient in identifying them, to the extent that they can detect anomalies or differences beyond the perception of traditional human programming. As we will see, this has several practical applications.</p><p><strong>To get a deeper understanding of Computer Vision, we spoke with Datatonic’s leading Machine Learning and Data Science experts to get their insights:</strong></p><p><strong><em>When did you first experience or hear about Computer Vision? What was the first project you worked on?</em></strong></p><p><a href="https://www.linkedin.com/in/christellexu/"><em>Christelle Xu, Business Analyst, former Data Scientist</em></a><em>: I heard about Computer Vision very early on in my data science career. The first Computer Vision project I worked on was in graduate school where we used pixels to try to analyse what number was shown onscreen. It’s quite a common Computer Vision project. My first professional experience was an insurance Hackathon project with Datatonic. We were trying to develop a model that </em><strong><em>extracts relevant information</em></strong><em> in order to create a document for an insurance policy case.</em></p><p><a href="https://www.linkedin.com/in/tobi-lipede/"><em>Tobi Lipede, Senior Data Scientist</em></a><em>: I think I first came across it a good few years ago now. My Master’s dissertation was about </em><strong><em>Image Segmentation</em></strong><em> for medical images, so I gained some experience there. The models were slightly different to what people are using now, but Computer Vision really caught my attention. Then, I taught myself a little bit more about it through an online Stanford University Computer Vision course.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IDvHnGc4MoPbMKGh" /></figure><p><strong>Image Segmentation</strong>: Partitioning a digital image into multiple image segments, and labelling the individual pixels that belong to each segment or object. This is used extensively in self-driving cars.</p><p><a href="https://www.linkedin.com/in/mgela/"><em>Matt Gela, Senior Data Scientist</em></a><em>: Hearing about self-driving cars is the one that comes to mind before I started my career in Data Science! The first project I worked on was with an aviation security client. We created an </em><strong><em>object detection model</em></strong><em> using </em><strong><em>AutoML</em></strong><em> to help improve the detection rate of prohibited objects.</em></p><p>The third blog in this series will walk you through how to create your own <strong>object detection model </strong>using <strong>AutoML</strong>, without writing a single line of code!</p><p><strong>Object Detection</strong>: Detection of objects in an image and their bounding box. Commonly used for:<br>+ Detecting faults such as cracks on a production line, automating quality inspection<br>+ Vehicle detection in warehouses<br>+ Inventory management</p><p><strong><em>What gets you excited about Computer Vision?</em></strong></p><p><a href="https://www.linkedin.com/in/alex-thomas-4286549b/"><em>Alex Thomas, Senior Data Scientist</em></a><em>: Probably its wide variety of use cases. Traditionally, Data Science has </em><a href="https://www.netguru.com/blog/data-science-in-marketing#:~:text=Data%20science%20in%20marketing%20can,essential%20to%20running%20a%20business."><em>huge business value</em></a><em>. It can help businesses in terms of marketing such as targeting the right customers, but I think Computer Vision has a wider scope. There are so many different areas where we can use Computer Vision, and I think that’s the most exciting thing about it.</em></p><p><a href="https://www.linkedin.com/in/sofieverrewaere/"><em>Sofie Verrewaere, Senior Data Scientist</em></a><em>: I think probably its potential in the Healthcare industry. When you look at medical diagnosis, Computer Vision is reaching a point where it is </em><a href="https://www.sciencedaily.com/releases/2018/08/180822114436.htm"><em>better at detecting some diseases than doctors</em></a><em> because they have better visibility. It definitely has a lot of medical applications. I’ve seen Computer Vision being used to detect certain types of cancers on medical scans. Also, Computer Vision being used to combat climate change. Anything that’s “AI for good” I would say. It can also be used for faster recovery after natural disasters, meaning the disasters can be overcome more quickly.</em></p><p>More than <a href="https://www.thezebra.com/resources/research/natural-disaster-statistics/">200 million</a> people are threatened by floods, hurricanes, wildfires and other natural disasters <strong>each year</strong>; this will likely increase due to climate change. However, Computer Vision is already being integrated with satellite imagery and drone cameras to monitor the amount of <a href="https://www.weforum.org/agenda/2020/01/natural-disasters-resilience-relief-artificial-intelligence-ai-mckinsey/">damage caused to different buildings</a> and areas following natural disasters. This information can be combined with other data and used to identify the best places to set up temporary schools and medical tents, and where relief workers should prioritise reconstruction efforts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*4XuFhps5mTz0ZEwY" /></figure><p>Furthermore, Computer Vision systems allow homeowners to <a href="https://docs.google.com/presentation/d/1bwJDRC777rAf00Drthi9yT2c9b0MabWO5ZlksfvFzx8/edit#slide=id.gf171287819_0_2353">take photos of the damage</a> to their homes after natural disasters, enabling them to better predict repair costs and receive insurance claim payouts months faster than before these systems were used.</p><p><a href="https://www.linkedin.com/in/danielmiskell/"><em>Daniel Miskell, Machine Learning Engineer</em></a><em>: With recent breakthroughs, we’re now seeing very exciting applications in Computer Vision. We can create </em><a href="https://this-person-does-not-exist.com/"><em>photos of humans that have never existed</em></a><em> and we can imagine a section of fictional writing through text-to-image models. I’m very excited about the many ways these techniques are going to benefit our lives!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*U2EDoOXLRJI1iFlR" /></figure><p>Some of the most exciting applications of Computer Vision are around the potential applications to the healthcare industry. Already, there are several use cases where Computer Vision is <a href="https://viso.ai/applications/computer-vision-in-healthcare/#:~:text=Computer%20vision%20has%20been%20used,enable%20a%20more%20accurate%20diagnosis.">improving healthcare</a>, such as medical imaging, cancer detection, and medical training via simulation-based surgical platforms.</p><p><em>“Using Computer Vision, we can now identify tumours from images of patients’ lungs more accurately and faster than ever before” — Daniel Miskell, Machine Learning Engineer</em></p><p>In the near future, Computer Vision could lead to increased accuracy in disease detection, as well as increased automation of time-consuming tasks, leading to better access to healthcare for patients.</p><p><em>Tobi Lipede: We’re just scratching the surface of all the things we can do. A lot of companies haven’t necessarily explored all of the applications that there are for Computer Vision. When I think of use cases like the </em><a href="https://datatonic.com/case-studies/image-recognition-lush/"><em>project we worked on with LUSH</em></a><em> for customers to identify different products so that LUSH could eliminate packaging, I realise there are so many different applications. So many different companies that could benefit from Computer Vision, including any company with a physical store.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*73lfp9zmIjz8Ijah" /></figure><p>You can learn more about our work with LUSH <a href="https://www.linkedin.com/posts/datatonic_register-for-computer-vision-in-retail-activity-6782983915280855040-PGEx?utm_source=linkedin_share&amp;utm_medium=member_desktop_web">here</a>. This use case is an example of image classification. By training a Computer Vision model to recognise multiple classes of objects, the model can learn to detect each one and assign new unseen images to each class.</p><p><strong>Image Classification </strong>— classification of different groups of subjects in an image by assigning them to specific labels.</p><p>Having heard a bit more about some of our team and their experiences with Computer Vision, let’s explore some of the use cases they have worked on, as well as some of the exciting upcoming developments in the field!</p><h3>Uses of Computer Vision</h3><p>Powerful pre-trained Machine Learning (ML) models can be applied directly to Computer Vision tasks or altered slightly for classifications similar to what the pre-trained network was trained on. In the next section, we’ll look at several types of Computer Vision techniques and how they are being applied today across different use cases that businesses can capitalise on.</p><p><strong>Techniques and Use Cases</strong></p><p>Computer Vision can be broken down into several different model types, with unlimited innovative use cases. As we’ll see, we can also combine different types of models to satisfy a specific use case. One example is combining <strong>Object Detection</strong> with <strong>Optical Character Recognition</strong> (OCR) to create a model that first detects an object within an image or video, and then detects the text within the image file. Self-driving cars use this process to read road signs.</p><p><strong>Optical Character Recognition (OCR) </strong>— extraction of text from images. Commonly used for:<br>+ Translating signs, menus, and handwritten text into a typed document<br>+ Document extraction</p><p><strong><em>What use cases have you seen or worked on with Computer Vision? Do you have a favourite?</em></strong></p><p><em>Alex Thomas: There’s a use case that’s taken off in the last year called </em><strong><em>text-to-image generation.</em></strong><em> You might’ve seen stuff on social networks about a model called </em><strong><em>DALL-E.</em></strong><em> You can type in a description like “man sitting in a chair in the style of Picasso” and it’ll generate an image in a photo-realistic style. It’s a cool technology and I think it’s going to make things like generating art, assets for video games, animated movies, and websites easy and quick.</em></p><p>You can try out <a href="https://huggingface.co/spaces/dalle-mini/dalle-mini">DALL-E Mini,</a> an open-sourced text-to-image program, to automatically generate any image you like. Here is the example of “man sitting in a chair in the style of Picasso”. We can see how well it understood the input by looking at the images it generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dtagKMzHvUms5QW1" /></figure><p>Similar technology has already been used in some of the more recent Pixar movies to automatically generate high-resolution frames, drastically reducing the time required by graphic designers and animators. Another example is Hello Games’ survival game, <em>No Man’s Sky, </em>which uses AI for world generation, allowing players to explore 1.8×1019 unique planets.</p><p><em>Tobi Lipede: My favourite practical applications would probably be anything related to robotics. For example, the </em><a href="https://www.bostondynamics.com/products/spot"><em>Boston Dynamics robot, Spot</em></a><em>. Just thinking about the AI and Computer Vision that goes into making that work is so cool. I’m also quite interested in </em><strong><em>action recognition</em></strong><em> applications. I think there’s a lot of different stuff that can be done with that. I’d like to work on my own hand gesture recognition project — like controlling my TV without a remote. Instead of classifying one image, it’s looking at a sequence of frames to work out what is happening. Other than that, I’d like to see fully autonomous self-driving cars; I don’t have my license yet so I’m hoping they get on it soon.</em></p><p><strong>Action Recognition </strong>— detection of actions being performed in an image or video. Commonly used for:<br>+ Detecting actions in manufacturing procedures to verify they have been done correctly<br>+ Monitoring the safety of workers<br>+ Machine interaction (by detecting hand signals)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uGVMTCrV8u_jXRlw" /></figure><p>Combining physical robotics with Computer Vision now means that robots have an even wider range of potential use cases. The Boston Dynamics robot, Spot, that Tobi mentioned, is now being used by the New York Fire Department to <a href="https://outsider.com/news/boston-dynamics-robot-dog-joins-new-york-fire-department-search-and-rescue-missions/">help with search and rescue missions</a>.</p><p><em>Christelle Xu: I think from a business perspective, the biggest use cases are going to come down to working with massive enterprises to leverage the data that they have and support their processes. For me, the coolest use case that exists right now is probably the supermarkets where you can walk in, grab what you want, and just walk out…</em></p><p>These supermarkets use a combination of Computer Vision, deep learning algorithms, and sensors. Once you have scanned a QR code on your phone using a mobile app upon entering, you can pick up any items you want and simply leave the shop. You are then emailed your receipt and charged online for the items you “bought”. This completely eliminates the need to queue or scan your items, saving huge amounts of time for consumers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8SH2JNmXW7_v74lM" /></figure><p><em>…I have one near me and it’s incredible. It’s these services where you can have eyes and ears everywhere and human work is simplified and automated out that Computer Vision can be used. That is the future. Right now, it seems like a weird thing but they are going to be everywhere soon. 100%.</em></p><p>As we continue to build upon our experience of Computer Vision, even more innovative use cases, such as the ones discussed in this blog, will become more widespread. The next blog in this series, coming out next week, will discuss some of the likely future developments of Computer Vision, as well as what Google Cloud Platform is doing to make them happen!</p><p><strong><em>As 4x Google Cloud Partner of the Year, Datatonic has a wealth of experience in both Computer Vision and a range of Google products and services. </em></strong><a href="http://datatonic.com/contact"><strong><em>Get in touch</em></strong></a><strong><em> to learn how your business can benefit from Computer Vision or other Machine Learning models.</em></strong></p><p><strong>Contributors: </strong><a href="https://www.linkedin.com/in/christellexu/"><strong>Christelle Xu, Business Analyst</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/tobi-lipede/"><strong>Tobi Lipede, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/mgela/"><strong>Matt Gela, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/alex-thomas-4286549b/"><strong>Alex Thomas, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/sofieverrewaere/"><strong>Sofie Verrewaere, Senior Data Scientist</strong></a><strong>, </strong><a href="https://www.linkedin.com/in/danielmiskell/"><strong>Daniel Miskell, Machine Learning Engineer</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e69fdebf88" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/computer-vision-insights-from-datatonics-experts-48e69fdebf88">Computer Vision: Insights from Datatonic’s Experts</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Powerful Machine Learning Models on Google Cloud Platform]]></title>
            <link>https://blog.montrealanalytics.com/deploying-powerful-machine-learning-models-on-google-cloud-platform-29a2913641ab?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a2913641ab</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 14:23:24 GMT</pubDate>
            <atom:updated>2022-06-24T14:23:24.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rax3Fs6DE_O_DIS9uFDFZw.jpeg" /></figure><p><strong>In our </strong><a href="https://datatonic.com/insights/natural-language-processing-text-summarisation-domain-specific-texts/"><strong>last blog</strong></a><strong>, Machine Learning Engineer, Hiru Ranasinghe covered how we developed a Natural Language Processing (NLP) model with Hugging Face to generate abstracts for COVID-19 research papers. Now the model has been developed, it is time to deploy it.</strong></p><p>In this blog, we will show you how to deploy Machine Learning (ML) models on Google Cloud Platform (GCP), and use it to serve predictions via an API, using our NLP model as an example. Once deployed, the model can be integrated with a front end (e.g., a website), such as our COVID-19 Text Summariser demo which can be found <a href="https://demohub.datatonic.com/">here</a>.</p><p>We will walk through all the steps to take saved model files, like ours from <a href="https://datatonic.com/insights/natural-language-processing-text-summarisation-domain-specific-texts/">the first blog in this series</a>, to deployment. After reading, you should be able to take an ML model from development and host it on the internet using Google Cloud Platform for members of the public or your business to use.</p><h4>Background</h4><p>Before we get into how to deploy your model, it is worth looking at the bigger picture of the steps and services that a prediction request will go through before reaching the deployed model. Google Cloud has many services that have similar functions, so it is useful to understand when to choose each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KzyEe5MprNutVXrT" /><figcaption><em>Fig 1: Cloud Architecture demonstrating the process of model deployment</em></figcaption></figure><p>Before the model is deployed, model serving source code is used by Cloud Build to build the serving image. This is then uploaded to the Artifact Registry, and, finally, deployed on Cloud Run. Google Cloud Run is a solution to execute container images on Google Cloud.</p><p>When a user wants to get predictions from the model, a prediction request is made via the frontend (e.g., a website) by the user. This request is then sent from the frontend to API Gateway; we’ll discuss this in more detail below. API Gateway then sends this request to the Cloud Run instance running the model serving image. This generates a prediction from the request and sends it back to API Gateway, which in turn displays it on the frontend.</p><h4>Google Cloud Services</h4><p>Below, we outline the stages in developing and deploying an ML model along with the rationale for the chosen services. Note that the creation and management of these Google Cloud services can be automated with Terraform.</p><p><strong>Model Development: Vertex AI + Google Cloud Storage</strong></p><p><a href="https://cloud.google.com/vertex-ai">Vertex AI</a> is Google’s unified AI platform, which has several features for performing tasks across the ML lifecycle. In particular, Vertex AI offers managed Jupyter notebooks. These can be used for model development in a cloud environment, and training jobs using more powerful hardware can be run to quickly train models. In addition, trained model artifacts can be stored in Google Cloud Storage as the API for fetching these artifacts is easy to use; a single command can be used to fetch the artifacts when the container image is built.</p><p>Model development within a cloud environment has several advantages:</p><ul><li><strong>Faster download and upload</strong> speeds by using Google’s network</li><li><strong>Lower computational load</strong> for local machines</li><li><strong>Swift integration</strong> with Google’s other services</li><li><strong>Range of hardware</strong> for different ML tasks</li></ul><p><strong>Model Deployment: Cloud Run + API Gateway</strong></p><p>Deploying models with Google Cloud Run is very simple. Container images can have files written in any language, and all they need to do is run an HTTP server. Using Vertex AI endpoints was another consideration, but container images must follow strict requirements. On the other hand, Cloud Run is completely flexible and poses no restrictions on container images.</p><p>Another benefit of using Cloud Run instead of Vertex endpoints is that Cloud Run can scale down to zero instances. Contrarily, Vertex endpoints must always run on a virtual machine. This means that a charge is incurred even when the endpoint receives no requests.</p><p>One downside of using Cloud Run is that every time the deployed container changes, its URL changes too. Therefore, in order to preserve the URL to which the model requests are sent, we use API Gateway in front of the Cloud Run instance.</p><h4>Technical Implementation</h4><p>The end goal is to build an application that runs an HTTP server which has routes to handle prediction requests. To achieve this, Uvicorn is used to run the HTTP server and FastAPI is used to define the routes of the application.</p><p>Our model deployment folder has the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*KRK8QA2PL97eYqdP" /><figcaption>Fig 2: The structure of the model deployment folder</figcaption></figure><p>For now, we will focus on the following:</p><ul><li><em>Dockerfile</em> — defines the serving container image</li><li><em>cloudbuild — </em>directory with the Cloud Build configuration to build and push the container image</li><li><em>helpers.py — </em>defines model inference logic</li><li><em>main.py — </em>defines the HTTP server and its routes for handling predictions and health checks; this is run by Uvicorn when the server starts</li><li><em>pyproject.toml — </em>used by Poetry; this manages python dependencies</li></ul><p><strong>Below are the steps we’ll take to deploy our model:</strong></p><ol><li>Setting up dependency management with Poetry (Optional)</li><li>Using FastAPI to run an HTTP server with developer-defined routes</li><li>Writing the Dockerfile to define the model serving image</li><li>Building and pushing the model serving image to a registry using Cloud Build</li><li>Deploying the model serving image on Cloud Run</li><li>Setting up the API Gateway</li><li>Testing the model</li></ol><h4><strong>1. Setting up Dependency Management with Poetry (Optional)</strong></h4><p>This is an optional step for setting up Poetry, a dependency management tool. A <em>requirements.txt</em> can be used instead, but using Poetry is more scalable and promotes best practices. Poetry automates the creation of a virtual environment to install dependencies into. It also resolves dependency versions that work together and locks these down into a separate file. This way, dependencies don’t need to be resolved by pip each time packages are installed.</p><p>First, install Poetry onto your machine:</p><p><strong>‘pip install poetry’</strong></p><p>In the root directory, initialise Poetry to create a <em>pyproject.toml:</em></p><p><strong>‘poetry init’</strong></p><p>In the <em>pyproject.toml</em>, add in package dependencies under <em>[tool.poetry.dependencies]</em>. Read more about how to do this <a href="https://python-poetry.org/docs/basic-usage">here</a>.</p><p>Install the packages into Poetry’s virtual environment:</p><p><strong>‘poetry install’</strong></p><p>This step can take a while depending on the number of package dependencies. Once dependency management is set up, it is time to start defining the HTTP server using FastAPI.</p><h4><strong>2. Using FastAPI to Run an HTTP Server with Developer-Defined Routes</strong></h4><p>In this step, we will explain how to write the <em>main.py </em>to handle prediction requests. We will assume that you have already created the basic Python function that generates predictions from user input (in our case, <em>helpers.py) </em>and can simply import and call it as part of a route.</p><p>Install FastAPI and Uvicorn if you haven’t already:</p><p>If using pip: <strong>‘pip install fastapi uvicorn’</strong></p><p>If you’ve set up dependency management with Poetry:<strong> ‘poetry add fastapi’ ‘poetry add uvicorn’</strong></p><p><strong>Imports</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*aQobZK45wWvbqluG" /><figcaption>Fig 3: Code showing imports from FastAPI library</figcaption></figure><p>The imports from the FastAPI library are used to generate the API schema, which API Gateway uses to handle Cross-Origin Resource Sharing (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS)</a> issues. ‘<strong>BaseModel’</strong> is a class used to form the base of request and response objects. It removes all of the complexities used in HTTP requests and responses and allows you to simply define what data you expect to receive and what data you want to send as a response. The ‘<strong>List’</strong> class is then used when defining the request and response data.</p><p><strong>Requests and Responses</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*3XkhiBZ8hujO59y6" /><figcaption><em>Fig 4: Defining the structure of the HTTP requests and responses</em></figcaption></figure><p>Using the <strong>‘BaseModel’</strong> Class, we can define the structure of the HTTP requests the model expects, and the structure of the HTTP responses which are sent back.</p><p><strong>Routes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TwtFszaItOv9FEIn" /><figcaption><em>Fig 5: Defining functions that run when requests are sent to specific routes</em></figcaption></figure><p>Here, we define the functions that run when requests are sent to specific routes. The <strong>‘@app.get’</strong> and <strong>‘@app.post’</strong> are decorators that tell our application to run these functions when a GET or POST request is sent to the specified route.</p><p>The <strong>‘/predictions’</strong> route takes the input from the user’s request, uses it to call the <strong>‘gen_summary’ </strong>function, and returns the prediction. The <strong>‘/api/healthz’ </strong>route is used to check if the deployed container works.</p><p><strong>API Schema</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mOEviHoM6f7D4GKi" /><figcaption><em>Fig 6: Defining a custom OpenAPI schema</em></figcaption></figure><p>The API Gateway requires a schema written in the <a href="https://swagger.io/specification/">openAPI specification</a>. This spec is a YAML file and can be created using the function we imported earlier. The <strong>‘x-google-backend’</strong> key added to the YAML sets the configuration that the API Gateway will use, such as the Cloud Run URL and the timeout for requests. These two variables are set via our Terraform code which automatically builds this infrastructure.</p><p>The final block of code is used so that the API Gateway can handle CORS issues.</p><p><strong>Local Testing</strong></p><p>To test the server locally, run <strong>‘uvicorn –host 0.0.0.0 main:app –port 7080’. </strong>This runs the server from your local machine at port 7080. For full documentation on Uvicorn, see <a href="https://www.uvicorn.org/settings/">here</a>. A test request can then be sent using the <strong>‘curl’ </strong>Unix command or a tool like <a href="https://www.postman.com/downloads/">Postman</a>.</p><p>Once the server works, it is time to build the container image that runs this server!</p><h4><strong>3. Writing the Dockerfile to Define the Model Serving Image</strong></h4><p>Since we are using Google Cloud Build, any local files in the root of the directory are uploaded to Google Cloud Storage temporarily so they can be used with any COPY statements. However, it would be very time-consuming if the model files were uploaded each time a build is completed as they make up several gigabytes. Therefore, we use a multi-stage build, splitting the build into two steps:</p><ol><li>Copy the model files from Google Cloud Storage into an intermediate builder container image</li><li>Create the serving container image, installing dependencies and copying model files from the intermediate builder container image.</li></ol><p>This is done in two steps to make the serving container image as small as possible. For example, the serving container image doesn’t need the Google Cloud SDK. Also, the intermediate builder container image is discarded after the Cloud Build job is complete. The first stage of the build is defined like so in the Dockerfile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GeS5CeTV1w_mshRT" /><figcaption><em>Fig 7: Reducing the size of the serving container</em></figcaption></figure><p>The Dockerfile’s first step<strong> </strong>uses a lightweight (alpine) tag of the Google Cloud SDK base image, makes a directory, and copies the model files from Google Cloud Storage into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SlI9dG9irZJE_2xj" /><figcaption><em>Fig 8: Creating the serving container image</em></figcaption></figure><p>The Dockerfile’s second step creates the actual serving container image. It uses the Python slim base image and installs Poetry (optional) into it. We then copy the Poetry files, or requirements.txt, from the local folder into the container image and install the dependencies.</p><p>With all the dependencies installed, the other project files are copied into the serving container image. A .dockerignore file can be created to ignore specific files in the copy. We then copy the model files from the first stage into the serving container image.</p><p>Lastly, we set environment variables used by the model and run the Uvicorn server that listens for requests.</p><h4><strong>4. Building and Pushing the Model Serving Image to a Registry Using Cloud Build</strong></h4><p>Now the model serving image is defined, we need to actually build it and push it to a registry. This is done using Cloud Build. The instructions for Cloud Build are saved in <em>cloudbuild/container_build.yaml</em>. The instructions will depend on what process you use to manage container images, but the <a href="https://cloud.google.com/build/docs/configuring-builds/create-basic-configuration">Cloud Build documentation</a> explains how to write basic configuration files.</p><p>Run <strong>‘gcloud builds submit –project=${GCP_PROJECT_NAME} –config=cloudbuild/container_build.yml –timeout=3600’</strong> to start the build process.</p><p>The timeout flag has been added to change how long to wait in seconds before cancelling the job. The default is 600 seconds (10 minutes), which is too short given the large model file sizes. When using large model files (&gt;100Mb), it is recommended to extend the timeout to 3600 seconds (1 hour) to ensure the build job has time to complete.</p><h4><strong>5. Deploying the Model Serving Container Image on Cloud Run</strong></h4><p>Once the container image is on the Google Container Registry, it can be easily deployed onto Cloud Run.</p><p>First, navigate to Cloud Run in your project and click <strong>“CREATE SERVICE”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*8p7SZX4-_0gCRLiM" /><figcaption><em>Fig 9: The Cloud Run menu</em></figcaption></figure><p>Ensure the <strong>“Deploy one revision from an existing container image”</strong> option is chosen and select your container image, a name for the deployed model service, and a region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*WnbXzv-nZatWGBTg" /><figcaption><em>Fig 10: Selecting deployment options for your model</em></figcaption></figure><p>For CPU allocation, we chose to only allocate during request processing. This means that billing is done on a per-request basis. In terms of autoscaling, we recommend setting the minimum instance number to at least one, to reduce cold starts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*YE3sJaCov5lMHBkk" /><figcaption><em>Fig 11: Selecting CPU allocation and pricing</em></figcaption></figure><p>In terms of security, there are two settings. The Ingress option can be configured to only allow requests from within a Virtual Private Cloud (VPC) network (regardless of the user’s IAM permissions). The Authentication option is to determine whether you want to allow requests from anyone, or only authorised users with IAM permission. We set Ingress to <strong>“Allow all traffic” </strong>because we are not using a VPC network. Authentication is set to <strong>“Require authentication” </strong>so that only our middleware and authorised internal users can directly send requests to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*5U_o5vIWsZjyst9Q" /><figcaption><em>Fig 12: Selecting options for Ingress and Authentication</em></figcaption></figure><p>Lastly, we set the container to listen for requests on port 7080 as configured in our Dockerfile and set the capacity of the machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*UCoAp63eN3GlQl4C" /><figcaption><em>Fig 13: Selecting the capacity for your model</em></figcaption></figure><p>Once set, feel free to click <strong>“Create”</strong> and wait a few minutes for the instance to spin up!</p><h4><strong>6. Setting up the API Gateway</strong></h4><p>Lastly, we set up the API Gateway which sits in front of our Cloud Run instance.</p><p><strong>Generating the Spec</strong></p><p>First, we need to actually generate the spec mentioned in the previous section. This is done using a nodeJS package. The FastAPI function generates the spec as a JSON, and we use the converter to turn it into YAML.</p><p>If you don’t have Node.js installed, see <a href="https://nodejs.org/en/download/">here</a>. Once it is installed, navigate to the root directory of your project and install the api-spec-converter package:</p><p><strong>‘npm install -g api-spec-converter’</strong></p><p>We then define a shell script which generates the spec using this package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ht71arc4zwjyh6mJ" /><figcaption><em>Fig 14: Script that generates the spec.yaml used in the API Gateway configuration</em></figcaption></figure><p>Line 18 declares where to output the YAML file. Run the script to generate the spec.</p><p>When not using Terraform, the Cloud Run URL will need to be manually input into the spec and will need to be changed each time the Cloud Run instance is changed.</p><p><strong>Creating the API Gateway in Google Cloud</strong></p><p>An API Gateway in Google Cloud sits within an API object. This API object has a configuration object (which uses our previously generated spec) and a gateway object. To set up an API Gateway, navigate to API Gateway within the Google Cloud Console, then click <strong>“Create Gateway”.</strong></p><p><strong>API</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*XdgY4ia3hCdMaNzE" /><figcaption><em>Fig 15: Creating an API</em></figcaption></figure><p>Choose a display name and ID for the API object.</p><p><strong>API Config</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*Xy4mx13LQWo9n-I9" /><figcaption><em>Fig 16: API Config</em></figcaption></figure><p>Upload the generated API Spec and choose a display name for the config.</p><p><strong>Gateway Details</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*B8y86tW7z38_Gqn7" /><figcaption><em>Fig 17: Selecting your Display Name and Location</em></figcaption></figure><p>Set a display name for the gateway as well as its location; it is best to put in your own location.</p><h4><strong>7. Testing the Model</strong></h4><p>Send a request to the model using cURL or Postman, similar to what we did when testing it locally. The main difference this time is that the URL will be the API Gateway’s URL with <strong>‘/predictions’</strong> at the end. If everything is successful, a prediction will be returned!</p><p>Congratulations! By following these steps, you should have successfully deployed your model and will now be able to send requests and receive responses from it!</p><p><strong><em>Datatonic are </em></strong><a href="https://datatonic.com/insights/datatonic-google-cloud-specialization-partner-award-machine-learning/"><strong><em>Google Cloud’s Machine Learning Partner of the Year</em></strong></a><strong><em> with a wealth of experience developing and deploying impactful Machine Learning models and MLOps Platform builds. Need help with developing an ML model, or deploying your Machine Learning models fast? Have a look at our </em></strong><a href="https://datatonic.com/insights/vertex-ai-mlops-platform/"><strong><em>MLOps 101 webinar,</em></strong></a><strong><em> where our experts talk you through how to get started with Machine Learning at scale, or </em></strong><a href="https://datatonic.com/contact"><strong><em>get in touch</em></strong></a><strong><em> to discuss your ML or MLOps requirements!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a2913641ab" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/deploying-powerful-machine-learning-models-on-google-cloud-platform-29a2913641ab">Deploying Powerful Machine Learning Models on Google Cloud Platform</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing: Text Summarisation for Domain-Specific Texts]]></title>
            <link>https://blog.montrealanalytics.com/natural-language-processing-text-summarisation-for-domain-specific-texts-2b4c2a7cb806?source=rss-31d0e4dc6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b4c2a7cb806</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Team Datatonic]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 11:01:31 GMT</pubDate>
            <atom:updated>2022-06-24T11:01:31.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqOkDxded-6bFPgyraDbGg.jpeg" /></figure><p>Natural Language Processing (NLP) is one of the most popular innovation use cases dominating the AI landscape, with the Global NLP Market <a href="https://www.mordorintelligence.com/industry-reports/natural-language-processing-market">projected to be worth $48.46 billion by 2026</a>. The pandemic has expedited market growth even further, especially in the healthcare sector, and this rapid expansion is leading to new advancements in the field.</p><p>One of these is the increase in the prevalence of transformer language models, such as <strong>Bidirectional Encoder Representations from Transformers (BERT) </strong>and<strong> Generative Pre-trained Transformer 3 (GPT-3)</strong>. These models have been trained on massive quantities of data and enhance the performance of a wide range of NLP issues dramatically, paving the way for novel and complex applications. Combined with the flexibility and scalability of cloud computing, transformer models have brought cutting-edge NLP solutions ever closer to businesses.</p><p>There are important <a href="https://cloud.google.com/blog/topics/healthcare-life-sciences/himss-2022-data-interoperability-natural-language-processing-better-health-outcomes">applications of NLP in the healthcare industry</a>, such as extracting insights from unstructured formats like clinical notes and lab results. Text summarisation is one such example, where large pieces of text are distilled into a concise summary by a language model and can aid time-sensitive decisions. For instance, independent reviews of the medical necessity of prescribed treatments might be requested by a patient or their insurer. In this scenario, the reviewers are required to examine hundreds of documents before coming to a conclusion, which can be extremely time-consuming and can also lead to human error. The application of text summarisation allows the reviewer to transform the vast volume of text into a decision quickly and accurately.</p><p><strong>This blog will cover some common challenges with using text summarisation on longer and domain-specific texts, and how to overcome them.</strong></p><h4><strong>What makes language models so powerful?</strong></h4><p>Language models are usually pre-trained models that have been trained using very large corpora of text (e.g., BERT was trained on 3.3 billion words) on tasks such as missing word prediction. This results in the hidden layers of the model learning a general understanding of language, which can then be utilised for the downstream task (in our case, text summarisation) through transfer learning.</p><p><strong>Extractive and Abstractive Summarisation</strong></p><p>In NLP, there are two forms of text summarisation: extractive and abstractive.</p><p><strong>Extractive summarisation</strong> is the process of selecting a predefined number of sentences that are most important in understanding the text.</p><p><strong>Abstractive summarisation</strong>, on the other hand, generates a summary consisting of novel sentences by either rephrasing or using words not found within the original text. The task of abstractive summarisation is much more complex than extractive summarisation, as it requires the language model to not only comprehend the message conveyed by the text but also generate a summary that encapsulates the general understanding of the original text.</p><p><strong>Example</strong></p><p><strong>Source Text:</strong> The Australian Grand Prix will be the first to feature four separate DRS zones around the lap this weekend as F1 returns to Albert Park. The Albert Park track map on the official Formula 1 website has been updated to show that the circuit now features four DRS zones to aid overtaking. The Melbourne circuit has undergone major re-profiling since the last Australian Grand Prix held at the venue in 2019, with a number of corners being made wider and faster in a bid to improve racing. This will be the first time a grand prix has been held with four separate DRS activation points around the circuit.</p><p><strong>Extractive Summarisation: </strong>The Australian Grand Prix will be the first to feature four separate DRS zones around the lap this weekend as F1 returns to Albert Park. The Melbourne circuit has undergone major re-profiling since the last Australian Grand Prix held at the venue in 2019, with a number of corners being made wider and faster in a bid to improve racing.</p><p><strong>Abstractive Summarisation:</strong> The Australian Grand Prix will feature four DRS zones, which is the first track to do this. Since the last Grand Prix in 2019, corners of the Albert Park track have been made wider and faster to improve racing.</p><p>However, a problem arises when we try to summarise very long pieces of text. This is because large pre-trained models usually have a limit to the length of text they can ingest. For example, the base-BERT (the most popular version of BERT) can only take up to 512 words as input, which poses a problem when one would want to summarise a body of text longer than this.</p><h4><strong>How to Summarise Long, Domain-Specific Text</strong></h4><p>Given the massive focus on COVID-19 over the past couple of years, we wanted to put text summarisation to the test in the context of coronavirus, and use NLP to summarise COVID-19 research papers. This provided us with an exciting challenge, as research papers not only contain large, complex bodies of text, but also use domain-specific language. With most popular models limited to 512 words, we set out to build a model that uses a mix of approaches to overcome the limitations of existing models.</p><p><strong>Our Approach</strong></p><p><strong>Combining extractive and abstractive summarisation </strong>allows us to summarise longer bodies of text, by using extractive summarisation to reduce the word count of the original text to a length short enough to be input into the abstractive summariser. The extractive step ensures that only the most important sentences are retained, effectively acting as a filter for the abstractive step. Then, the shortened text is used to produce an abstractive summary of the original text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5M-bIgXet7SIYOzo" /><figcaption>Fig 1: A diagram to illustrate the steps</figcaption></figure><p>General-purpose language models, such as BERT, would struggle to comprehend domain-specific language such as medical terminology. This would mean that the abstractive summariser would find it difficult to produce text in a similar style to medical research papers. Consequently, we needed a solution to train our model on domain-specific language.</p><p>Our next steps walk you through how we solved this, and how you can implement a similar solution to finetune models for your purpose.</p><p><strong>Getting Started</strong></p><p><strong>1. Pick an Appropriate Dataset</strong></p><p>To provide more accurate forms of summarisation for COVID-19 papers, our solution required finetuning the type of language of the domain. To do this, we need a training set with the inputs as example texts to summarise and a summary as the ‘label’, which the model will use as the ground truth to summarise the input. In our case, we acquired the <a href="https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge">COVID-19 Open Research Dataset from Kaggle</a>, with 500,000+ scholarly articles related to COVID-19, SARS-CoV-2 and other coronaviruses. The article abstract was split from the main body of text so we could use the abstract as our “label” and the main body of text as the input to summarise.</p><p><strong>2. Extractive Summary</strong></p><p>The extractive summariser model did not need to be trained as we use an unsupervised algorithm to generate the summary. To generate an extractive summary we:</p><ol><li>Used the Hugging Face implementation of BERT to encode each sentence into vectors</li><li>Applied the K-nearest neighbours (KNN) algorithm (an unsupervised algorithm) to identify a predefined number of clusters. Each cluster then contains a group of sentences around a particular topic and the sentence vector closest to the centroid of the cluster is assumed to encapsulate the meaning of all the sentences within the cluster.</li><li>Our model picks the aforementioned sentence from each cluster to produce an extractive summary. It is important to note that the number of sentences in the extractive summary is determined by the number of clusters we seek to find in the KNN algorithm.</li></ol><p><strong>3. Abstractive Summary</strong></p><p>On the other hand, the abstractive step could be finetuned, and we used an autoregressive model that takes the extractive summary as input to the model and paraphrases it into a more cohesive summary. For our solution, we trained the Bidirectional Auto-Regressive Transformers (BART) model by using the abstract of the research papers as the target output. The abstract was omitted from the input into the extractive summariser to avoid data leakage.</p><p><strong>Training Language Models on Vertex AI</strong></p><p>To train the abstractive BART model, we curated a training dataset consisting of the extractive summary of the original research paper as inputs and the respective abstract as the target label. After experimenting, we found 6 epochs with a learning rate of 2e-4 to be the optimal hyperparameters for the BART model. It took 12,000 training steps for us to reach a training loss that we were happy with.</p><p>Many other researchers in this problem domain found resources to be a limiting factor in model performance, but we benefited from the scalability of the Vertex AI Workbench on GCP to utilise the A100 GPU, which significantly sped up training time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Akl06aFAnb4Ivgrx" /><figcaption><em>Fig 2: Flowchart of Model Fine Tuning</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*i5DGmEfIcMWWgmHE" /><figcaption>Fig 3: Flowchart of Inference</figcaption></figure><p>Using this model, we are able to summarise complex research papers into simple abstracts, which only require some minor grammatical edits and sense checking. This has a wide range of applications, not only in the healthcare sector, but many other industries, including academia, law, and business.</p><p>Try the model out for yourself with our “Covid Research Paper Summariser“ demo <a href="https://demohub.datatonic.com/demos/covid-text-summarisation">here</a>.</p><p>We hope you enjoyed this blog! Part two of this blog series will cover how we deployed a REST API using Vertex AI endpoints to serve our model on the demo site. We will also cover how we developed a React frontend and Express.js server to communicate with the API using Google Cloud App Engine.</p><p><strong>As 4x Google Cloud Partner of the Year, Datatonic has a wealth of experience in both text summarisation and developing and deploying Machine Learning models. </strong><a href="http://datatonic.com/contact"><strong>Get in touch</strong></a><strong> to learn how your business can benefit from working with us.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b4c2a7cb806" width="1" height="1" alt=""><hr><p><a href="https://blog.montrealanalytics.com/natural-language-processing-text-summarisation-for-domain-specific-texts-2b4c2a7cb806">Natural Language Processing: Text Summarisation for Domain-Specific Texts</a> was originally published in <a href="https://blog.montrealanalytics.com/">${around_the_block}</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>