<?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 Yasser Mushtaq on Medium]]></title>
        <description><![CDATA[Stories by Yasser Mushtaq on Medium]]></description>
        <link>https://medium.com/@yasser.mushtaq?source=rss-4d8667382cb9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*W3F7iW8_LO_-zYzu</url>
            <title>Stories by Yasser Mushtaq on Medium</title>
            <link>https://medium.com/@yasser.mushtaq?source=rss-4d8667382cb9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:36:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasser.mushtaq/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[Databricks Asset Bundles (DABs): Deploying with GitHub Actions for CI/CD]]></title>
            <link>https://medium.com/towards-data-engineering/databricks-asset-bundles-dabs-deploying-with-github-actions-for-ci-cd-d3fa7d443327?source=rss-4d8667382cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3fa7d443327</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Yasser Mushtaq]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 09:42:16 GMT</pubDate>
            <atom:updated>2024-06-11T15:32:19.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>Automated Deployment of DABs using GitHub Actions and CI/CD</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ESOTDS7akbV1SEod" /><figcaption>Photo by <a href="https://unsplash.com/@kadh?utm_source=medium&amp;utm_medium=referral">Kira auf der Heide</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What are Databricks Asset Bundles?</h4><p>In short, <a href="https://docs.databricks.com/en/dev-tools/bundles/index.html">Databricks Asset Bundles</a> (DABs) are an Infrastructure-as-Code (IaC) approach to deploying Databricks resources. This could be Databricks Jobs, Delta Live Tables (DLT) pipelines, and so on. They are a recent development by Databricks, aimed at simplifying and consolidating resource development and deployment.</p><p>Although not the aim of this discussion, an IaC approach has numerous benefits, such as reproducibility and incorporation into Continuous Integration and Delivery (CI/CD) workflows. Ultimately, using DABs will allow you to develop templated projects, and utilise software engineering best practices.</p><h4>Aim</h4><p>Having recently worked through setting up a DAB based project on Azure Databricks — here I go through the process of getting setup, particularly whilst incorporating with GitHub Actions for CI/CD workflows.</p><p>Although there is a great deal of documentation available, certain elements were trickier to determine, particularly in regards to GitHub Actions setup. In addition, there was a lot of back of forth across different documents to gather the required information. Therefore I thought it useful to provide a step-by-step guide!</p><h4>Initial Steps</h4><p>The aim of my project itself was to deploy a DLT pipeline for an ELT process. This was going to produce some end-user tables/views in Databricks. I wanted to set this up in a manner that was reproducible and utilised development best practices.</p><p>To get started with a basic setup of a DAB, and develop an understanding of how they work, I found it useful to do a local deployment first. The first step required locally is install Databricks CLI. This will allow you to test/deploy bundles from the command line. If you haven’t got this installed, you can find instructions for your OS <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/cli/install">here</a>.</p><p><strong>Authentication — Local User</strong></p><p>Following local installation of Databricks CLI, you need to authenticate to your Databricks workspace. When using your local machine, in the docs this is referred to as <em>OAuth user-to-machine</em> (U2M) authentication. This approach wouldn’t be suited to an automated CI/CD system like GitHub Actions. We will cover this later, in <em>OAuth machine-to-machine</em> (M2M) authentication.</p><p>The steps for local authentication are straight forward, the first step is to run the following on the command line:</p><pre>databricks auth login - host &lt;workspace-url&gt;</pre><p>Replace &lt;workspace-url&gt; with your Azure Databricks URL. There are some small subsequent steps here to assign an authentication profile, which you can find <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/bundles/">here</a>.</p><p><strong>Creating a Bundle</strong></p><p>Next, you complete the steps outlined in “Step 2” <a href="https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/tutorial-bundles">here</a>. The result of following these steps is to create a template bundle for a DLT pipeline resource. As previously stated, my project involved deploying a DLT pipeline. You may have other use cases, in which case check the documentation for existing templates. There are some ‘common tasks’ at the bottom of this <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/bundles/">page</a>. Examples include templates for an MLOps Stack.</p><p><strong>Explore the Bundle</strong></p><p>In the directory you created the bundle in, you can now explore the files the above process created. Some key ones are the databricks.yml, which includes configurations relating to the target workspace and deployment environments. Also pertinent to DLT include a job configuration YAML, which specifies a schedule, a task to run and configuration for a cluster. For my project, I kept the default setting.</p><pre>resources:<br>  jobs:<br>    ae_sim_job:<br>      name: ae_sim_job<br><br>      schedule:<br>        # Run every day at 8:37 AM<br>        quartz_cron_expression: &#39;44 37 8 * * ?&#39;<br>        timezone_id: Europe/Amsterdam<br><br>      # can send an email on pipeline failure, although GitHub will also do this<br>      # email_notifications:<br>      #   on_failure:<br>      #     - user@email.com<br><br>      tasks:<br>        - task_key: refresh_pipeline<br>          pipeline_task:<br>            pipeline_id: ${resources.pipelines.ae_sim_pipeline.id}<br>        <br>      job_clusters:<br>        - job_cluster_key: job_cluster<br>          new_cluster:<br>            spark_version: 13.3.x-scala2.12<br>            node_type_id: Standard_D3_v2<br>            autoscale:<br>                min_workers: 1<br>                max_workers: 4</pre><p>The name of the job is prefixed with my project name <em>ae_sim</em>.</p><p>Referenced in the job is the pipeline task to run. This is detailed in the ae_sim_pipeline YAML file, as follows.</p><pre>resources:<br>  pipelines:<br>    ae_sim_pipeline:<br>      name: ae_sim_pipeline<br>      target: ae_sim_${bundle.environment}<br>      allow_duplicate_names: true<br>      libraries:<br>        - notebook:<br>            path: ../src/ae-sim-elt-build.ipynb<br><br>      configuration:<br>        bundle.sourcePath: /Workspace/${workspace.file_path}/src</pre><p>Here we define a target, which is the target schema (which you will see the result of below, basically ae_sim_dev/prod), as well as a reference to the notebook we want to run for the DLT pipeline.</p><p>These two code chunks above are kept in separate YAML files, and as such provide a modular approach to building our DAB.</p><blockquote>We don’t go into details about the intricacies of DLT, but you can read more <a href="https://docs.databricks.com/en/delta-live-tables/index.html">here</a>. In short, they are a declarative framework for data pipelines, where you can include features like quality control checks.</blockquote><p><strong>Manual Validate, Deploy and Run</strong></p><p>Follow steps 4, 5 and 6 from the same <a href="https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/tutorial-bundles">link</a> as above to <em>validate</em>, <em>deploy</em> and <em>run</em> the bundle we have created. This deploys to a dev environment, and the result is a materialised view you can explore! Any changes you now make to the DLT notebook will be reflected in the workspace after you deploy and run the bundle again!</p><p><strong>Things to Note</strong></p><p>When you look through the bundle files, there are some key things to note and be aware of:</p><ul><li>In the ‘targets’ for dev and prod, the workspace is defined as a host name in the format (if you use Azure Databricks): host: <a href="https://xxxxxx.x.azuredatabricks.net/">https://xxxxxx.x.azuredatabricks.net</a></li><li>When deploying in the real world, using GitHub, you wouldn’t explicitly declare this in the YAML here. It can be declared as a GitHub secret in the deployment environment.</li><li>Also under workspace for prod environment, is root_path, which is where all the files are deployed to. By default this will include your login username. However, we can also change this to a <em>service principal</em> ID.</li><li>Under run_as, which indicates the user the deployment runs under, by default you will see your login username. For a production environment, it is much more robust to use a <em>service principal. </em>This prevents run failures if the original developer leaves your organisation. In addition, you probably don’t want your username/host name visible in a repo, particularly if it is public!</li></ul><p><strong>Service Principal</strong></p><p>The use of service principals relates to the aforementioned <em>OAuth machine-to-machine (M2M) </em>authentication method<em>. </em>This basically<em> </em>uses the credentials of an automated entity to authenticate with the desired target environment, and this is how we setup our GitHub Actions for CI/CD.</p><p>There are two ways by which you can setup a service principal, which will access your workspace and perform the required actions. One would be via your cloud provider, for instance using Microsoft Entra ID, or alternatively, you can create a service principal within your Databricks workspace itself. I opted for the latter.</p><p>The steps required to setup via Microsoft Entra ID start at step 1 <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/oauth-m2m">here</a>. Whereas I started from step 2. The steps outlined here basically require you to go to the <em>manage account</em> settings (top right of the DB workspace). Then user management &gt; service principals &gt; add service principal. Select the type of service principal (Azure or Databricks managed), type the display name and then add.</p><p><em>Note — you need to be an Azure Databricks account admin, or global admin to do this!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhi-CqQr6qxqYBupLxcf_g.png" /><figcaption>User management under manage account.</figcaption></figure><p>Finish steps 4 and 5 from the <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/oauth-m2m">docs</a> to set permissions and <strong>create a secret</strong> for the service principal. The principal will now have a unique ID and secret. Together with your workspace hostname, we now have the details we need to setup our deployment environment in GitHub Actions.</p><p><strong>Prepare Bundle for Upload to GitHub Actions</strong></p><p>We now have the elements we need to deploy an automated solution. However, there are some changes we can make to the databricks.yml file to reflect that we won’t be running the bundle from a local environment and will be using a service principal, not our own user ID.</p><p>These adjustments are under the targets section of the YAML file. Read the comments in the code below for detail.</p><pre>targets:<br>  # The &#39;dev&#39; target, for development purposes. This target is the default.<br>  dev:<br>    # We use &#39;mode: development&#39; to indicate this is a personal development copy:<br>    # - Deployed resources get prefixed with &#39;[dev my_user_name]&#39;<br>    mode: development<br>    default: true<br>    # below we normally define a workspace host, but here we declare in GitHub Actions env<br>    # so the below workspace can be commented out/removed<br>    # workspace:<br>    #   host: https://xxxxxx.x.azuredatabricks.net<br><br>  ## Optionally, there could be a &#39;staging&#39; target here.<br>  ## (See Databricks docs on CI/CD at https://docs.databricks.com/dev-tools/bundles/ci-cd.html.)<br>  #<br>  # staging:<br>  #   workspace:<br>  #     host: https://xxxxxx.x.azuredatabricks.net<br><br>  # The &#39;prod&#39; target, used for production deployment.<br>  prod:<br>    # We use &#39;mode: production&#39; to indicate this is a production deployment.<br>    # Doing so enables strict verification of the settings below.<br>    mode: production<br>    workspace:<br>      # again we don&#39;t need to specify the host here, we can do that in GitHub<br>      # host: https://xxxxxx.x.azuredatabricks.net<br>      # default always use /Users/user@email.com for all resources to make sure we only have a single copy.<br>      # If this path results in an error, please make sure you have a recent version of the CLI installed.<br>      # I amended below to use SP id in path not user email (fine for my purpose but you can leave this as user@email.com<br>      # note this uses a variable sp_name, declared in the actual file<br>      root_path: /Users/${var.sp_name}/.bundle/${bundle.name}/${bundle.target}<br>    run_as:<br>      # By default this runs with user email in production. We could also use a SP here,<br>      # see https://docs.databricks.com/dev-tools/bundles/permissions.html.<br>      # so here we use a SP, not a user_name<br>      # user_name: user@email.com<br>      service_principal_name: &quot;dad6aa45-6871-xxxx-xxxx-xxxxxxxxxxxx&quot;</pre><p>In addition, we need to create our GitHub/workflows directory, for our CI/CD setup. These are the files GitHub Actions use for CI/CD workflows.</p><blockquote>GitHub Actions allow for automation of software deployment workflows, and include CI/CD.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TARun0BoepgbK-zIDrKG8A.png" /><figcaption>Workflow for CI/CD with GitHub Actions</figcaption></figure><p>The base GitHub workflow files were taken from this <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/bundles/ci-cd">link</a>, which gives you a basic setup for CI/CD with GitHub Actions. However, we make some changes to the default configuration to utilise our service principal ID and secret. We also use GitHub secrets to store the details we need.</p><p>Here is another <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/#unified-auth-vars-fields">reference</a> I found useful to determine which environment variables to use in GitHub Actions for authentication. Particularly under the heading, <em>Environment variables and fields for client unified authentication.</em></p><p>These variables are used when the client machine is attempting to authenticate with the workspace, and so are important get right!</p><p>To begin with, here is our GitHub Actions YAML file for our dev environment. This validates, deploys, and runs the specified job in our bundle within our <em>dev </em>workspace environment.</p><pre># This workflow validates, deploys, and runs the specified bundle<br># within a pre-production target named &quot;Dev&quot;.<br>name: &quot;Dev deployment&quot;<br><br># Ensure that only a single job or workflow using the same concurrency group<br># runs at a time.<br>concurrency: 1<br><br># Trigger this workflow whenever a pull request is opened against the repo&#39;s<br># main branch or an existing pull request&#39;s head branch is updated.<br>on:<br>  pull_request:<br>    types:<br>      - opened<br>      - synchronize<br>    branches:<br>      - main<br><br>jobs:<br>  # Used by the &quot;pipeline_update&quot; job to deploy the bundle.<br>  # Bundle validation is automatically performed as part of this deployment.<br>  # If validation fails, this workflow fails.<br>  deploy:<br>    name: &quot;Deploy bundle&quot;<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      # Check out this repo, so that this workflow can access it.<br>      - uses: actions/checkout@v3<br><br>      # Download the Databricks CLI.<br>      # See https://github.com/databricks/setup-cli<br>      - uses: databricks/setup-cli@main<br><br>      # Deploy the bundle to the &quot;qa&quot; target as defined<br>      # in the bundle&#39;s settings file.<br>      - run: databricks bundle deploy<br>        working-directory: .<br>        env:          <br>          # below as described here: https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/oauth-m2m<br>          # below we use params for machine to machine auth based on account ID and token <br>          # you can also use service principal - better than user auth for prod<br>          DATABRICKS_BUNDLE_ENV: dev<br>          DATABRICKS_TOKEN: ${{ secrets.SP_TOKEN }}<br>          DATABRICKS_ACCOUNT_ID: ${{ secrets.DB_USER }}<br>          DATABRICKS_HOST: ${{ secrets.DB_HOST }}<br>          # DATABRICKS_CLIENT_ID: ${{ secrets.SP_ID }}<br>          # DATABRICKS_CLIENT_SECRET: ${{ secrets.SP_SECRET }}<br><br>  # Validate, deploy, and then run the bundle.<br>  pipeline_update:<br>    name: &quot;Run pipeline update&quot;<br>    runs-on: ubuntu-latest<br><br>    # Run the &quot;deploy&quot; job first.<br>    needs:<br>      - deploy<br><br>    steps:<br>      # Check out this repo, so that this workflow can access it.<br>      - uses: actions/checkout@v3<br><br>      # Use the downloaded Databricks CLI.<br>      - uses: databricks/setup-cli@main<br><br>      # Run the Databricks workflow named &quot;ae_sim_pipeline &quot; as defined in the<br>      # bundle that was just deployed.<br>      - run: databricks bundle run ae_sim_pipeline  --refresh-all<br>        working-directory: .<br>        env:<br>          DATABRICKS_BUNDLE_ENV: dev<br>          DATABRICKS_TOKEN: ${{ secrets.SP_TOKEN }}<br>          DATABRICKS_ACCOUNT_ID: ${{ secrets.DB_USER }}<br>          DATABRICKS_HOST: ${{ secrets.DB_HOST }}<br>          # DATABRICKS_CLIENT_ID: ${{ secrets.SP_ID }}<br>          # DATABRICKS_CLIENT_SECRET: ${{ secrets.SP_SECRET }}</pre><p>Note that here we define the workflow behaviour to trigger whenever we open a pull request against the main branch or when an existing pull request head branch is updated. Also, we utilise some environment variables, which are defined in GitHub secrets. For the dev environment, you use the host name, account id (your login user email) and token. You could also use a service principal here if you wanted, which are the commented out variables (we will use these in the production environment).</p><p>The token can be generated locally after you have logged-in using Databricks CLI. You run the following command from your command line to generate the token:</p><pre>databricks tokens create --comment &lt;comment&gt; --lifetime-seconds &lt;lifetime-seconds&gt; -p &lt;profile-name&gt;</pre><p>Where your profile name is the authentication profile created when you authenticated to your workspace with the Databricks CLI. Find out more <a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/pat">here</a>.</p><p>Now whenever I open a pull request against the main branch, my development pipeline will begin. Remember that the <em>run ae_sim_pipeline</em> in the code above is a reference to my projects resource that is being executed.</p><p>Below is our GitHub Actions configuration for our production environment.</p><pre># This workflow validates, deploys, and runs the specified bundle<br># within a production target named &quot;prod&quot;.<br>name: &quot;Production deployment&quot;<br><br># Ensure that only a single job or workflow using the same concurrency group<br># runs at a time.<br>concurrency: 1<br><br># Trigger this workflow whenever a pull request is pushed to the repo&#39;s<br># main branch.<br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  deploy:<br>    name: &quot;Deploy bundle&quot;<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      # Check out this repo, so that this workflow can access it.<br>      - uses: actions/checkout@v3<br><br>      # Download the Databricks CLI.<br>      # See https://github.com/databricks/setup-cli<br>      - uses: databricks/setup-cli@main<br><br>      # Deploy the bundle to the &quot;prod&quot; target as defined<br>      # in the bundle&#39;s settings file.<br>      - run: databricks bundle deploy --force-lock<br>        working-directory: .<br>        env:<br>          #DATABRICKS_TOKEN: ${{ secrets.SP_TOKEN }}<br>          # below as described here: https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/oauth-m2m<br>          # below we use params for machine to machine auth based on service principal - better than user auth<br>          DATABRICKS_BUNDLE_ENV: prod<br>          DATABRICKS_HOST: ${{ secrets.DB_HOST }}<br>          DATABRICKS_CLIENT_ID: ${{ secrets.SP_ID }}<br>          DATABRICKS_CLIENT_SECRET: ${{ secrets.SP_SECRET }}<br><br>  # Validate, deploy, and then run the bundle.<br>  pipeline_update:<br>    name: &quot;Run pipeline update&quot;<br>    runs-on: ubuntu-latest<br><br>    # Run the &quot;deploy&quot; job first.<br>    needs:<br>      - deploy<br><br>    steps:<br>      # Check out this repo, so that this workflow can access it.<br>      - uses: actions/checkout@v3<br><br>      # Use the downloaded Databricks CLI.<br>      - uses: databricks/setup-cli@main<br><br>      # Run the Databricks workflow named &quot;my-job&quot; as defined in the<br>      # bundle that was just deployed.<br>      - run: databricks bundle run ae_sim_pipeline --refresh-all<br>        working-directory: .<br>        env:<br>          #DATABRICKS_TOKEN: ${{ secrets.SP_TOKEN }}<br>          DATABRICKS_BUNDLE_ENV: prod<br>          DATABRICKS_HOST: ${{ secrets.DB_HOST }}<br>          DATABRICKS_CLIENT_ID: ${{ secrets.SP_ID }}<br>          DATABRICKS_CLIENT_SECRET: ${{ secrets.SP_SECRET }}</pre><p>The workflow behaviour here is to trigger whenever a pull request is pushed into the main branch.</p><p>Note the main difference here is the use of the service principal ID and secret (DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET). This means when the production job is run, it is run under these credentials. This protects against dependencies on specific individuals.</p><p>With these files in your .github/workflows directory, you are good to go!</p><p>You now need to create a GitHub repository with the bundle files and the above GitHub workflow files included. You can view my own <a href="https://github.com/Ya5s3r/ae-sim-deployment-databricks">repository</a> for an example if needed. Don’t forget to define your GitHub <a href="https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions">secrets</a> correctly! Otherwise your run will fail very quickly!</p><h4>Outcome</h4><p>Once you hopefully have some nice green ticks in your GitHub Actions runs…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*uND1O_F6s8jMLKGBGCA6Jw.png" /><figcaption>Successful deploy and run pipeline of DAB!</figcaption></figure><p>…You will see the outcomes in your Databricks workspace. Firstly, you’ll notice a folder in the users directory for the service principal, as well as your own personal user email. In addition, you will see a .bundle folder in each of these directories. This is where all the relevant deployment files and folders are kept. For instance, you will see your Python notebooks in the files/src/ subfolder. You will also find both dev and prod deployment folders.</p><p>In my use case, where I deployed a DLT pipeline, I also had both development and production pipelines visible in the DLT tab under <em>data engineering</em>.</p><p>Here is a basic DLT pipeline that my DAB deployment produced and ran. You will see the prefix dev in the heading, indicating this was a dev deployment by a certain user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0Dhi3nFx75xdK5shh0LsA.png" /></figure><p>In comparison you will notice the production version of this pipeline <em>run as</em> the service principal ID, which will also be visible in the DLT tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*FOjgZLYR8v0gbLK6eSBySg.png" /></figure><p>In a real world scenario, you would deploy your development and production environments in separate Databricks workspaces. However, in my personal project, given I only had access to one workspace, I deployed both in the same workspace, but the target schema/tables were defined in the bundle files in a manner that identifies the environment type, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*SB87f-AGZ3Ii2JU9Zxeh-w.png" /><figcaption>Both dev and prod schemas within the same DB workspace.</figcaption></figure><h4>Summary</h4><p>In summary, here we demonstrated how to develop and deploy a DAB, Databricks Asset Bundle, an IaC feature to easily deploy resources to your Databricks workspace. In addition, we demonstrated the steps required to deploy using GitHub Actions for CI/CD, while utilising best practices such as service principal IDs for production environments.</p><p>This was developed while working on a personal project to deploy a DLT pipeline for an ELT pattern, in a automated fashion. You can view my project repository <a href="https://github.com/Ya5s3r/ae-sim-deployment-databricks">here</a>.</p><p>Any feedback, comments, or to connect, you can reach me on <a href="http://www.linkedin.com/in/yassermushtaq">LinkedIn</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3fa7d443327" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/databricks-asset-bundles-dabs-deploying-with-github-actions-for-ci-cd-d3fa7d443327">Databricks Asset Bundles (DABs): Deploying with GitHub Actions for CI/CD</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Discrete Event Simulation — with SimPy]]></title>
            <link>https://medium.com/data-science/object-oriented-discrete-event-simulation-with-simpy-53ad82f5f6e2?source=rss-4d8667382cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ad82f5f6e2</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[simpy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[discrete-event-simulation]]></category>
            <dc:creator><![CDATA[Yasser Mushtaq]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 14:02:32 GMT</pubDate>
            <atom:updated>2023-03-30T10:43:35.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object-Oriented Discrete Event Simulation — with SimPy</h3><h4>Improving a busy emergency department with stochastic discrete event simulation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e7YfIqLhDHmMyADU" /><figcaption>Photo by <a href="https://unsplash.com/@shakusky?utm_source=medium&amp;utm_medium=referral">Zichao Zhang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In everyday life we often encounter and engage with queue based systems. This is the case where a system or process necessitates that entities, such as customers or patients, flow through the system while queuing for limited resources. We also often find ourselves wondering if the system we are engaged with is optimal, or speculate about the amount of time it will take to be served.</p><blockquote>Within the domain of queuing theory, Discrete Event Simulation (DES) is a method by which we can address these issue in a programatic and mathematical way.</blockquote><p>I previously wrote an introduction to DES, which outlines some of the key ideas behind the methodology, see <a href="https://medium.com/@yasser.mushtaq/discrete-event-simulation-simply-put-4ae9f098a809">here</a>.</p><p><em>Here</em>, we will go through an implementation of DES using the Python package SimPy. Further, we will demonstrate on <strong>object-orientated</strong> approach, highly useful as our models grow in complexity.</p><h4>Let’s Propose a Problem</h4><p>Put simply, DES can help us optimise any system characterised by entities queuing to request a particular service. This is applicable in numerous fields, such as manufacturing, telecommunications and healthcare. A typically highly pressurised environment, emergency departments offer a good use-case to test this method. Below, we have a process flow diagram depicting a simplified emergency department system. The entities, in this case patients, flow into the system, are triaged, and subsequently go through one of two processes before either going home, or being admitted into hospital.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYNkd9S0DnjgwAuRRg8KLg.jpeg" /><figcaption>Yellow boxes — resources, orange diamond — decision tree, green boxes — ‘sinks’ (entity exit points).</figcaption></figure><p>Note that this proposed system can indeed be altered and added to depending on the needs and wants of the project. The level of detail required will need to be be carefully considered. An overly simplified depiction of a system will produce unrealistic results and won’t reflect reality, while we need to be careful not to excessively model aspects of a system that go beyond our scope.</p><p>There are up to four points in our diagram where a queue can develop, while certain elements are also subject to a degree of randomness. These are highlighted by red dashed boarders and are mainly associated with processes in our system. For instance, the interval time between patient arrivals, and the time spent with a nurse or doctor, can all be <em>stochastically</em> modelled. In other words, be characterised be a degree of randomness in our model.</p><p>The system depicted above greatly lends itself to being modelled via DES. We will utilise the Python package <em>SimPy</em> to do this.</p><h4>Code Template</h4><p>Here, we will go through a template one can follow to code a DES model in <em>SimPy</em>. We will utilise an <em>object orientated</em> approach to solve this coding problem, as this facilitates the development of user friendly, readable code, particularly as the model gets bigger.</p><p>The code will constitute three main classes, as follows:</p><ul><li>A class simply holding key variables used to manipulate the model, or test <em>what-if</em> scenarios.</li><li>An entity class used to hold key information about entities passing through the system. In this case, a patient class.</li><li>And a class representing our system, and the processes that characterise it.</li></ul><p>In addition to the above, we may wish to include further classes for utility like purposes, such as tracking metrics.</p><p>Here, we will include only key elements of the code, displaying the three main classes above. The full code can be viewed <a href="https://github.com/Ya5s3r/Discrete-Event-Sim-AE-Department"><strong>here</strong></a>.</p><h4>Parameters and Variables</h4><p>We will include a class that simply acts as a placeholder for key variables and values that define our model. This allows for ease of access and manipulation. Note we have included information around resource levels and mean times, which will feed into the <em>stochastic</em> elements of the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359a6f4327ae147aa25208d42bbe3ec2/href">https://medium.com/media/359a6f4327ae147aa25208d42bbe3ec2/href</a></iframe><h4>Patients</h4><p>The patient class represents patients coming into our system. It is <em>instantiated</em> with a patient ID and a placeholder for the time spent in our system. It will also hold two methods, one to determine the priority the patients holds, indicative of severity, and a triage decision method, utilised during the triage process to determine which pathway the patient flows down. These methods will be used at appropriate places in our main model code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96d6109e665c1a7f1ef0af6212b6511/href">https://medium.com/media/d96d6109e665c1a7f1ef0af6212b6511/href</a></iframe><h4>System Class</h4><p>The final defining class of our code can be described as the <em>system</em>, or <em>model</em> class. This is where key processes are defined and represents the pathway(s) through which our entities flow.</p><p>I will break this class up into a few main chunks, given it is somewhat longer than the other classes. Firstly, upon <em>instantiation</em>…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbd23a3628397269dbf1a8ef2e088741/href">https://medium.com/media/bbd23a3628397269dbf1a8ef2e088741/href</a></iframe><p>The first important step here is to set up our SimPy environment. The environment manages the simulation, stepping through time on an event to event basis. In addition to time, the environment manages the scheduling and processing of events. These are all critical components of a DES, which you would otherwise need to code manually. SimPy thus greatly simplifies implementation.</p><p>In addition to the environment, we assign a patient counter, which also acts as the patient ID.</p><p>The resources (the yellow boxes in our flow chart) are also defined at this point. These are critical elements of our model, and largely determine how efficient our system is at processing entities. We have two types of resources defined, which are derived from functionality offered by SimPy. The first, most basic type, are the Resource class. We set a certain capacity for these resources, and they work on a <em>first in first out</em> (FIFO) basis. That is, entities are dealt with on a first come, first serve basis. In our system, the triage nurse is one such resource, hence self.nurse = simpy.Resource. Another type of resource SimPy allows you to define is a <em>priority resource. </em>These resources deal with entities based on a level of priority the entity is associated with, as opposed to a FIFO queue system. In our model, we ranked entities in terms of priority from 1 to 5, with 1 being the most critical and 5 the least. Examples of priority resources in our system are doctors and cubicles.</p><p>Following the instantiation of our key model variables, we move onto the first <em>process</em> function. The first process we want to define is that of arrivals into our system, and we can do that as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b60aa54b23d7558be01186e0354b074/href">https://medium.com/media/6b60aa54b23d7558be01186e0354b074/href</a></iframe><p>We generate patients with the use of an infinite while loop, which iterates on the patient counter to give us a new patient ID for each patient. We then initiate the patient with our AEPatient class, defined above, and subsequently send the patient through our main emergency department processes, which we will define later. The other main component of our function is the samples_interarrival variable, which randomly generates the time to the next entity arrival, utilising an <em>exponential</em> distribution to sample from. This distribution is commonly used to model time between arrivals. We feed into the exponential function the mean time between arrivals, which in our case we have predetermined, but in reality you would want to determine from real data.</p><p>The arrival process is then frozen for the sampled amount of time, following which the next patient is generated. This is achieved using yield self.env.timeout.</p><p>The while loop runs until the SimPy environment ends, which we will define later.</p><p>The next process in our system class is the attend_ed process, in which we define the possible journeys a patient might take through a system.</p><p>The comments in the code below describe the pathways through which the patient might travel, and follow the flow chart defined above. I will therefore below explain some of the key components of the code, which you will notice are utilised multiple times through the processes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a382f624f9cc53c8ee4328d87428d0/href">https://medium.com/media/90a382f624f9cc53c8ee4328d87428d0/href</a></iframe><p>In the context of SimPy, we can use a with block to request a specific resource, as shown in the code. One of the first things we do within this block is yield the request, which tells the process to request the resource, and if it is not available, the process will freeze in place until it is available (handily, SimPy takes care of this for us). In our system, once the resource is available, we typically then sample a consultation time, whether it be with the nurse or the doctor. For this purpose, we utilise a <em>lognormal</em> distribution. A random variable that is lognormally distributed will take only positive real values, and as such is useful for modelling process times in fields such as engineering, where negative values are not possible, as well as in finance to model income distributions. It is characterised by a right skew, in other words, with a long tail towards the right¹. <a href="https://towardsdatascience.com/log-normal-distribution-a-simple-explanation-7605864fb67c">This article</a> gives a great overview. Its characteristics also make it well suited to model our consultation times. As such, you will note that our process durations utilise a custom function² that generates a random number from a lognormal distribution. We then utilise the timeout function of the SimPy environment class to pause the process for the sampled amount of time.</p><p>Notice that if a patient goes through to the emergency department or to the Minor Injury Unit (MIU), a request is first made for a cubicle. Within this with block, is another with block where a request is made for a doctor. This means that only once the patient is in a cubicle will a doctor be requested, and only once the doctor is finished will the cubicle be released, in effect, where the cubicle with clause finishes. This is a really neat way to build a relationship between two related resources. Another thing to note is as the cubicle and doctor are priority resources, we indicate what priority we are using in the resource function parameter. The end of the attend_ae function represents the end of our system, any point at which a patient can leave is depicted in our flow chart above in green.</p><p>The last method in our class is run and is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c60c2c0492c4905be94e220ce276596f/href">https://medium.com/media/c60c2c0492c4905be94e220ce276596f/href</a></iframe><p>This method is what we use later to begin our environment. We start the first process, which is the generator function that produces patients and use the environment’s run function to run our simulation for a specified time.</p><p>The complete code includes additional aspects predominantly related to tracking some key metrics and plotting results. I have omitted these here for the sake of brevity.</p><p>Outside of the code blocks above, we would utilise a <em>for loop</em> to run the simulation a specified number of times, and include any additional elements to track progress as required. A simple example is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6886193bca2c4bd3a535818bde6d190f/href">https://medium.com/media/6886193bca2c4bd3a535818bde6d190f/href</a></iframe><h4>Outputs</h4><p>In our complete code, we track some metrics that help us determine the overall performance of our system. These include average wait in minutes (across all runs) for the resources in our system, including the nurse, cubicle and doctors. In addition, we also track queue lengths throughout simulation time for some key services, in an attempt to identify bottlenecks.</p><p>Given we set a priority to each patient as they enter our system, we can also visualise metrics based on priority.</p><p>We can begin with our overall results, showing average wait times in minutes, for model parameters set as above (as a reminder, we have 3 doctors, 2 nurses and 7 accident &amp; emergency (AE) cubicles, see above for other inputs).</p><pre># average results across all runs of our model<br>The average number of patients served by the system was 55<br>The overall average wait across all runs for a triage nurse was 31.4 minutes<br>The overall average wait across all runs for a cubicle was 62.3 minutes<br>The overall average wait across all runs for a doctor was 17.2 minutes<br>The overall average wait across all runs for a MIU doctor was 0.2 minutes<br>The mean patient time in the system across all runs was 132.5 minutes</pre><p>We can see the largest wait is for a cubicle, while on average each patients spends about 130 minutes getting through the system.</p><p>There is virtually no pressure on our MIU, this is because with our default settings, our simulation isn’t utilising this unit a great deal.</p><p>A nice way to visualise bottlenecks is to chart the numbers of patients waiting for a resource at any given time in our simulator. The chart below shows this, focusing only on AE components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8pVypwOZDB5I1cC_MODDNQ.png" /><figcaption>Chart showing average queue length for three main resources throughout simulator — mean number across all runs. Shaded areas represent upper and lower quartiles.</figcaption></figure><p>We see quite a queue build up for a cubicle, which is clearly one of the bottlenecks in our system and thus contributing to the long time it takes for a patient to pass through.</p><p>Again, with our default parameters, we can also visualise the mean time in our system by patient priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dKQtxEm_Gn7bum4csM4uFw.png" /><figcaption>Mean time in system by priority — red numbers indicate average number of patients associated with each priority group. Error bars indicative of standard deviation.</figcaption></figure><p>Given the way we set up our model, most patients will be priority 3. The priority based queue, as well as our system dictating that priority 5 patients can go to the MIU or home, mean high priorities and very low priorities get processed quicker.</p><h4>What-If?</h4><p>Now we have a simulated system, we can test <em>what-if</em> scenarios, <em>prior</em> to real-world application. In addition, we can test operational changes in an attempt to optimise our system. This is one of the great uses of DES, and here, we will look at potential scenarios.</p><p>Our default system is producing quite an extensive total process time of on average over two hours!</p><p>Imagine we are approached by an operational manager, hoping to reduce the amount of time it takes for patients to pass through the AE department. It is known that patients are waiting a long time to access a cubicle. Will simply adding more cubicles resolve the problem?</p><p>Let’s find out by adding two more cubicles and comparing the results.</p><pre>The average number of patients served by the system was 56<br>The overall average wait across all runs for a triage nurse was 30.1 minutes<br>The overall average wait across all runs for a cubicle was 59.2 minutes<br>The overall average wait across all runs for a doctor was 30.5 minutes<br>The mean patient time in the system across all runs was 137.2 minutes</pre><p>This hasn’t helped much! The average wait for a cubicle has very slightly gone done, while the overall time has actually slightly increased.</p><p>However, experience leads us to think that perhaps the number of cubicles isn’t the problem, but the problems lies in how efficiently we process patients once they are in a cubicle. Perhaps you noticed that only adding more cubicles actually increased the time it takes to be seen by a doctor, as the same number of doctors now have more cubicles to get through.</p><p>We propose that the problem lies <em>upstream</em> of the cubicles. In other words, having more doctors, will allow us to clear cubicles at a quicker rate, and thus get patients home quicker. So lets revert the number of cubicles to their default value and instead increase the number of doctors.</p><p>Below we see the results of increasing the number of doctors by one, so we now have four doctors.</p><pre>The average number of patients served by the system was 63<br>The overall average wait across all runs for a triage nurse was 29.6 minutes<br>The overall average wait across all runs for a cubicle was 44.5 minutes<br>The overall average wait across all runs for a doctor was 5.2 minutes<br>The overall average wait across all runs for a MIU doctor was 0.2 minutes<br>The mean patient time in the system across all runs was 117.8 minutes</pre><p>By adding one doctor we have reduced average total process times by about 20 minutes. It has also relieved the pressure on the cubicles.</p><p>You may have noticed that another upstream pressure in our default system is quite significant. This being the average amount of time it takes for a patient who requires admission to be found an inpatient bed, and thus (in our system), leave an AE cubicle. Although only 30% of our priority 4 and below patients require this, they are having to wait on average 90 minutes to be allocated an inpatient bed. To demonstrate the impact of upstream pressures on our AE system, we simulate a reduction in this average time to 45 minutes. The results are show below.</p><pre>The average number of patients served by the system was 72<br>The overall average wait across all runs for a triage nurse was 33.8 minutes<br>The overall average wait across all runs for a cubicle was 33.0 minutes<br>The overall average wait across all runs for a doctor was 10.3 minutes<br>The overall average wait across all runs for a MIU doctor was 0.3 minutes<br>The mean patient time in the system across all runs was 110.1 minutes</pre><p>The average wait times for a cubicle have reduced down to about 30 minutes! remember this was at about 60 minutes with our default system. We can see below also that the number of patients queuing for cubicles throughout our simulator has also reduced, from almost 40 patients waiting to now about 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_EKQV5Ox_b3jjmXUEsfxag.png" /></figure><p>Quite remarkable given we have only added one AE resource to our model! Clearly, inefficiencies in the inpatient systems are having a bearing on AE performance, in our simulator. Indeed this is a well known phenomenon³.</p><p>We could go on, but we can conclude here having demonstrated the immense usefulness of SimPy in developing DES models with relative ease. To take this further, we could certainly add further complexity to our system to achieve a better reflection of a real-world emergency care system.</p><p><strong>Try out this Streamlit </strong><a href="https://ya5s3r-discrete-event-sim-app-hello-oykuyx.streamlit.app/"><strong>app</strong></a><strong> I developed for an interactive demonstration of the simulation!</strong></p><h4>Acknowledgments</h4><p><em>All images unless otherwise noted are by the author.</em></p><p>Thanks to colleagues from the <a href="https://arc-swp.nihr.ac.uk/research-and-implementation/research-teams/penchord/">Peninsula Collaboration for Health Operational Research and Data Science</a> (PenCHORD) for their support during our work in the <a href="https://arc-swp.nihr.ac.uk/training-type/health-service-modelling-associates-programme-hsma/">Health Service Modelling Programme (HSMA)</a> we are currently enrolled on<em>. Some HSMA resources can be viewed at the following links.</em></p><p>GitHub repos:</p><ul><li><a href="https://github.com/hsma5/3a_introduction_to_discrete_event_simulation">GitHub - hsma5/3a_introduction_to_discrete_event_simulation</a></li><li><a href="https://github.com/hsma5/3b_simpy_part_1">GitHub - hsma5/3b_simpy_part_1</a></li><li><a href="https://github.com/hsma5/3c_simpy_part_2">GitHub - hsma5/3c_simpy_part_2</a></li></ul><p>There are also some YouTube videos available:<br><a href="https://www.youtube.com/channel/UCCY9_Gxg6kM-xjk9vV0mzIQ/videos">https://www.youtube.com/channel/UCCY9_Gxg6kM-xjk9vV0mzIQ/videos</a></p><h4>References</h4><ol><li><a href="https://towardsdatascience.com/log-normal-distribution-a-simple-explanation-7605864fb67c">https://towardsdatascience.com/log-normal-distribution-a-simple-explanation-7605864fb67c</a></li><li>Custom function that produces a random number from a lognormal distribution kindly shared by <a href="https://medicine.exeter.ac.uk/people/profile/index.php?web_id=Thomas_Monks">Thomas Monks</a>, Associate Professor of Health Data Science at The University of Exeter.</li><li>Spill Over Effects of Inpatient Bed Capacity on Accident and Emergency Performance in England. R Friebel and R M.Juarez.<a href="https://www.sciencedirect.com/science/article/abs/pii/S0168851020301901#!">https://www.sciencedirect.com/science/article/abs/pii/S0168851020301901#!</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ad82f5f6e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/object-oriented-discrete-event-simulation-with-simpy-53ad82f5f6e2">Object-Oriented Discrete Event Simulation — with SimPy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discrete Event Simulation — SimPly Put]]></title>
            <link>https://medium.com/@yasser.mushtaq/discrete-event-simulation-simply-put-4ae9f098a809?source=rss-4d8667382cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae9f098a809</guid>
            <category><![CDATA[simpy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[discrete-event-simulation]]></category>
            <dc:creator><![CDATA[Yasser Mushtaq]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 12:00:37 GMT</pubDate>
            <atom:updated>2022-11-02T12:00:37.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discrete Event Simulation — SimPly Put</h3><h4>A brief introduction to Discrete Event Simulation and SimPy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B7h_OWQxahm6Hir3" /><figcaption>Photo by <a href="https://unsplash.com/@mparzuchowski?utm_source=medium&amp;utm_medium=referral">Michał Parzuchowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Discrete Event Simulation</em> (DES) is a commonly deployed methodology used to simulate real-life situations and processes. DES models events in a system as <em>discrete sequences of events</em> that occur at particular time intervals and represent a change of state in the system. Think of these events as discrete variables, that maintain a fixed state between periods of change. This contrasts with models based on <em>continuous variables,</em> that continually change overtime [1].</p><p>In DES, between each event, the system is considered to be in a fixed state, unaffected by other external, real-world influences. It can therefore be said that DES allows us to create simplified models of systems, that focus on key processes of significant influence, without the concern of low level details. Critically in operational decisions making, this allows us to formulate simulations of real-world systems, which we can then test and manipulate to determine outcomes, all in a safe, simulated environment. This removes the anxiety of testing changes to processes in the actual, real-world system. Introducing a new process in a model say, will allow us to determine the impact on the entire system, before implementation in the real-world.</p><h4>Key Components</h4><p>Below we will list key components commonly attributed to DES models.</p><ol><li>Entities — these are <em>things </em>that flow through the sequence of events in our system. They can be customers, patients, or objects such as cars.</li><li>Generators — the methods by which such entities enter the model. Generators produce entities at certain rates (<em>don’t confuse with python generator functions</em>!).</li><li>Inter-arrival times — relate to the time between entities entering the model. This can be modelled using a <em>probability distribution</em>.</li><li>Servers — these can be described as an activity that occurs within the system and that act upon the entities.</li><li>Server time — the amount of time it takes for servers to complete an action upon an entity, in other words, the activity times. Like inter-arrival times, can be modelled to introduce <em>randomness</em> to our process.</li><li>Resources — required to complete activities or servers. Examples includes customer service agents, doctors, or a continuous homogenous resource such as a fuel tank.</li><li>Queues — where entities wait until the activity has the required resource to perform the necessary action.</li><li>Sinks — describe how entities leave the system or model.</li></ol><h4>An Example</h4><p>Take an example of patients arriving at a vaccine clinic. We can assume there are a number of key points within this process. Firstly, patients will arrive at the clinic, they will then see the receptionist, before waiting in the waiting room before being seen by one of multiple nurses who then administer the vaccine. Using DES, we can simulate each of these steps. If we have historic data, we can determine the mean number of patients that arrive at the clinic per <em>time interval. </em>Within the model, we can simulate these patients being <em>served </em>by the receptionist, including the estimations of the amount of time it takes for the receptionist to serve them. A <em>queue</em> in the waiting area would then depend on the efficiency of the nurses administering the vaccines. This would in turn depend on the number of nurses available and the time it takes for vaccine administration. The nurses here represent a model <em>resource</em>.</p><p>Another key component of a DES model is the capability to leverage <em>stochastic</em> processes. This relates to the randomisation of aspects of the simulation, and in our example, can include the frequency at which patients arrive at the clinic, and the amount of time it takes for the receptionist and nurses to serve them. We can refer to these elements of the model as <em>non-deterministic</em>,<em> </em>given we cannot definitively indicate how these model processes will change overtime. Not including randomised events, and instead incorporating these as fixed elements would not accurately reflect the randomness that is often a key characteristic within real-world systems.</p><p>We would want the randomness we introduce into the model to be reasonable, however. Leveraging averages either from historic data or assumed numbers for proposed systems, we can thus utilise <em>probability distributions. </em>For instance we could model the number of patients arriving at our simulated clinic using an <em>exponential distribution. </em>Further, we could potentially model the time spent with the receptionist or nurse using a <em>normal distribution.</em></p><p>When modelling processes in our simulation, we generally need to find a balance between <em>simplicity</em> and <em>complexity</em>. A model that doesn’t include enough key components won’t be a good reflection of the real-world system, whereas we also don’t want to over-complicate our model unnecessarily. In our example, we could potentially go as far as including <em>the weather</em> as an influence on patient arrivals. However, depending on our need from the analysis, this may be overkill.</p><h4>Model Implementation</h4><p>A now popular method by which we can implement DES simulations is the Python package SimPy. This employs a particular type of DES, termed process-based DES [1]. This involves the fragmentation of a simulation into distinct processes. In our example, we would simulate the arrival of patients, and in separate processes, simulate the <em>servers</em> in the system, the receptionist and nurses. SimPy makes use of Python generator functions to manage processes and the completion of events. These functions are characterised by yield statements, that allow for a function to be ‘paused’ at a particular point, and then pick up again when needed at that same point. This is useful when, for example, needing to pause a process due to a wait for some resources to be freed-up.</p><p>SimPy is made up of key components, namely an Environment, which manages the simulation time, events, and process functions. The process functions are where simulation behaviour is really defined, and where events are <em>yielded. </em>This is where the python generator functions come in — SimPy utilises these to yield events. Processes can interact with other processes and call on <em>shared resources. </em>These resources define the capacity in the model, and are requested by a process, which may then need to wait to gain access, depending on the level of capacity [2].</p><p>Other interesting aspects of the resource elements include being able to define priorities to requesters of resources, and as such not be limited to <em>First In First Out</em> (FIFO) principals. There is also the concept of <em>containers, </em>that allow the inclusion of a finite resource that can be utilised and refilled as required. An example from the documentation is that of a gas station, where a storage of gas is modelled as a <em>container </em>from which a car can take and a tanker can replenish [3].</p><h4>Summary</h4><p>In summary, DES provides a simulated environment in which we can replicate real-world systems. Starting with a clear definition of the important processes in our systems, we can incorporate these elements into our model, which allows us to model the randomness they often exhibit via stochastic processes. Once we have a model that replicates our real-world systems with a good level of accuracy, we now have an environment in which we can test process changes, and various ‘what-if’ scenarios. In addition, we can also identify bottle necks in our system and find solutions to service optimisation problems.</p><h4>Future Aim</h4><p>In the near future, I hope to write-up an example simulation using the SimPy package, while expanding on some of the ideas introduced above. <em>Check back later for updates!</em></p><p><em>This blog is part of a series I’m hoping to write to present some key learnings from a programme I’m currently enrolled on (UK based), named the </em><a href="https://arc-swp.nihr.ac.uk/training-type/health-service-modelling-associates-programme-hsma/"><em>Health Service Modelling Programme (HSMA)</em></a><em>.</em></p><h4>References</h4><ol><li>Introduction to Discrete-Event Simulation and the SimPy Language. Norm Matloff. [<a href="https://web.cs.ucdavis.edu/~matloff/matloff/public_html/156/PLN/DESimIntro.pdf">https://web.cs.ucdavis.edu/~matloff/matloff/public_html/156/PLN/DESimIntro.pdf</a>]</li><li><a href="https://simpy.readthedocs.io/en/latest/contents.html">https://simpy.readthedocs.io/en/latest/contents.html</a></li><li><a href="https://simpy.readthedocs.io/en/latest/topical_guides/resources.html">https://simpy.readthedocs.io/en/latest/topical_guides/resources.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae9f098a809" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Tweepy to Topic Modelling with K-Means Clustering]]></title>
            <link>https://medium.com/@yasser.mushtaq/from-tweepy-to-topic-modelling-with-k-means-clustering-9e5a5a839417?source=rss-4d8667382cb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5a5a839417</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Yasser Mushtaq]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 21:44:17 GMT</pubDate>
            <atom:updated>2022-10-18T21:44:17.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>Does Twitter data pertaining to a major sporting event give insight into key outcomes?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A1kw5iOmpMvV4NRX" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Developing text analytics project presents numerous challenges, the first of which is typically sourcing rich datasets. To this end, here I will present an outline by which anyone can access and analyse Twitter tweet data. Twitter holds a vast amount of text data, which is quite unique in nature, given it is ever-growing, nuanced and original. For a text mining project, a user could request a dataset that is highly refined to their use case, and as such develop a unique project. The opportunities are therefore quite limitless!</p><p>For anyone keen to further their Natural Language Processing (NLP) skill set, a useful string in their bow is being able to access and work with Twitter data. The Twitter API provides a framework by which we can programmatically access Twitter data. To make it easier to work with this API, there exist Python packages that include functionality to assist a user in extraction. One such package is Tweepy, an open-source package that includes numerous functions and classes that help mitigate challenges such as authentication and rate limits. Below, we will go through the steps required to authenticate and request data via this useful package.</p><p>The first thing to note is that you will need a Twitter account, and once you have signed-up, you are then required to register as a developer <a href="https://developer.twitter.com/en/portal/dashboard.">https://developer.twitter.com.</a> While registering as a developer, you will run through a series of questions to determine your need to access Twitter data. Once this is complete, you can then create an app, which holds your credentials used when making API calls. Under ‘keys and tokens’ you will find a bearer token, which for Twitter API v2, is all you need. There are more comprehensive details here: <a href="https://developer.twitter.com/en/support/twitter-api/developer-account">https://developer.twitter.com/en/support/twitter-api/developer-account</a></p><p>As stated in the link, it is likely you will require elevated access.</p><h4><strong>Project goal</strong></h4><p>When thinking of a project based on Twitter data, I can’t help but be drawn to a personal interest — football (soccer), and in particular Arsenal Football Club. Following tweets during a game is often an event in itself. This makes we wonder whether anything useful can be gleaned from these tweets (maybe a bit optimistic!?). As opposed to analysing sentiment at this point, another area of NLP interest is topic modelling. Therefore, would it be possible to determine the key topics and themes that characterised a specific game purely based on user tweets relating to that game? We dig into Twitter to find out!</p><h4><strong>Working with Tweepy</strong></h4><p>Now that we have registered for the Twitter developer account, we now need to install (pip install tweepy) and learn how to utilise Tweepy to access the API. The first step required is authentication. Client is Tweepy’s interface for Twitter API v2 and takes your Bearer Token (obtained from your <em>keys and tokens</em> tab in the developer portal).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6902c2f2f455b896a69b24659bbd3a9/href">https://medium.com/media/a6902c2f2f455b896a69b24659bbd3a9/href</a></iframe><p>Note the other parameter included is wait_on_rate_limit. This usefully handles our request if we breach the rate limits set by the API, that is, the number of requests we are permitted to make within a given window. This parameter pauses the request if the rate limit is reached.</p><p>The next element is defining our search query. This search query will be used to filter for relevant tweets, and can include terms, operators and booleans to arrive at a highly refined subset. Below for instance, we search for terms such as “arsenal” and we negate terms such as “nuclear”, given this term is often paired with “arsenal”. Likewise, we have included and negated other terms to help us narrow in on what we need. In addition to key terms, we have also included a conjunction type operator of -is:retweet, with the minus indicating a negation. This removes retweets from our request, and is key to return original tweets. The lang:en operator returns only tweets Twitter has tagged as being in English. There are a host of other operators, and I would suggest referring to the documentation for more. This link provides a useful overview of how to build a query: <a href="https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query">https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query</a></p><p>Not included in our search query are the useful annotations Twitter adds to many tweets. These include adding tags for entities mentioned in the tweet, as well as context annotations, which Twitter adds to tweets to help understand contextual information about the tweet. These are searched for using the context operator. These themselves are the result of semantic analysis, and there are a series of domains one can pick from. A full list of all the context domains can be found here <a href="https://github.com/twitterdev/twitter-context-annotations.">https://github.com/twitterdev/twitter-context-annotations.</a> For instance, we could add the following to our search query: context:3.10027427957, where 3 is the domain and the entity is “Barclays Premier League Football”. This would be a potential method by which we can remove irrelevant tweets. However, only a subset of tweets are tagged in this way, so we would be omitting a large number of relevant tweets. For this reason, we didn’t include this in our query.</p><p>Below we now have a query to search with, as a starter perhaps we want to see how many tweets would fit these parameters over the last seven days, which is what the recent_tweets_count refers to. We can see a big spike in the number of tweets on a match day, October 1st, 2022.</p><p>Also shown are some examples of other relevant contexts, entities and search parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f62e040586708cbbee098a504aa549c6/href">https://medium.com/media/f62e040586708cbbee098a504aa549c6/href</a></iframe><blockquote>the total number of tweets on game day 01–10–22, was 124560</blockquote><p>This is the day we are going to narrow in on, as a game occurred upon this day, and in particular a game between Arsenal and their rivals Tottenham. Going back to our original question, we will extract tweets according to our search query that occurred during a game, to see if we can extract the key events/topics from the game! To do this, we will use two requests to the API, one for the first half and another for the second.</p><p>Below we can see the request for the first half. Note the use of the Paginator function, into which you pass the required search function and parameters. This is required if you wish to retrieve more than the maximum of 100 results per request. It has a useful function to flatten all the pages into one, and where you also specify the total number of tweets you want. Note this is a maximum and Twitter may return less.</p><p>We have added some additional parameters, such as the data fields we want to return and the time-frame we want to search within.</p><p>The Paginator function returns a generator, which we then convert to a list to allow us to view and manipulate the results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8b29aff1c8b3ae2e8917f22035d551/href">https://medium.com/media/5c8b29aff1c8b3ae2e8917f22035d551/href</a></iframe><h4>Cleaning Twitter Data</h4><p>Now we have our tweet data, we will go through a process of cleaning and manipulating the tweets in readiness for some text analytics work, namely, topic modelling. Remember, we are ultimately trying to determine if we can extract the key events from each half of the game.</p><p>Twitter text data, like other social media text, has some particular features you may not deal with in other domains. These particulars are dealt with by the clean_tweet function below. The function includes a series of steps to transform our tweet data into a usable format. Note that some of these steps are relevant in the context of topic modelling. For other types of analysis, we may need to adjust how we clean the data. Each step in the function includes a brief, but hopefully sufficient explanation! We utilise a mixture of regular expression operations to substitute elements of the string, as well as some really useful pre-processing functions available in the textacy library. I would encourage you to look at other available functions to clean text in this package, below a few are included as alternatives to regular expression.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74578ca90e8a91e79b5c95d199b2361/href">https://medium.com/media/d74578ca90e8a91e79b5c95d199b2361/href</a></iframe><h4><strong>Tokenization</strong></h4><p>The process of tokenization relates to the segmentation of documents, or in this case tweets into individual tokens, namely words or punctuations. There are numerous methods by which we can tokenize text data, and the choice of which to use will depend on the requirements of the analysis you are undertaking, as well as the nature of the text you are working with. Tokenization is a step required to build up a set of vocabulary, which in turn will allow us to vectorize our text data, which we will do later. A great deal of thought should go into how we tokenize. For instance, do we want to keep special characters, emojis and emoticons, which can be used in sentiment analysis?</p><p>This is particularly true when working with social media derived user text inputs, which will often include such entities. For our use here, we are interested in key topics and themes in each tweet. Usually, emoticons, emojis and perhaps even hashtags, won’t add much to the topic being articulated. It is really just the body of the text we need. Therefore, we have gone with quite a rudimentary tokenizer below, which returns sequences of two or more alphanumeric characters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd8976900e165a62f9af4646914ff26c/href">https://medium.com/media/fd8976900e165a62f9af4646914ff26c/href</a></iframe><p>It’s worth pointing out that the package nltk has a convenient TweetTokenizer function, which tokenizes tweets while retaining items such as emojis. Below is a demonstration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/892b6e9071f5de63f7dfc6bdd1a8a4e0/href">https://medium.com/media/892b6e9071f5de63f7dfc6bdd1a8a4e0/href</a></iframe><h4>Stopwords</h4><p>The next step in our pipeline is to remove what are known as stopwords. These are words that appear frequently in language, such as ‘the’, and don’t (often) add much to meaning. Many NLP libraries include a list of stopwords. Here we have used a list from nltk. The function simply filters out all the stopwords from the list of tokens. It is worth noting though, that words such as ‘do’ and ‘not’ are included in stopwords, and in the context of semantic analysis, this will have a significant impact on meaning. For example, if we removed these words from the statement, “I do not like ice-cream”, you can see the problem this will cause! We therefore should be careful about what stopwords we remove, and we may want to customise the list, so it is in accordance with the domain we are working in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4456412d28139d78a70e767564b9083/href">https://medium.com/media/b4456412d28139d78a70e767564b9083/href</a></iframe><p>We can now combine these functions into a pipeline through which our tweets will pass, to be cleaned and tokenized in the process. We can then loop through all of our tweets and append the cleaned tweets to a new list, choosing to keep only tweets with more than two tokens, given there seemed to be some quite meaningless single- or two-word tweets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce63d0550c078bc19b6320d74a0fd409/href">https://medium.com/media/ce63d0550c078bc19b6320d74a0fd409/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c618f119775ee4d955ecb2bfc2ee8c0f/href">https://medium.com/media/c618f119775ee4d955ecb2bfc2ee8c0f/href</a></iframe><h4><strong>Vectorisation</strong></h4><p>For our tweets, now in the form of individual tokens, to be usable for a machine learning model, we need to convert the tweets into vectorised form. This meaning vectors with numbers indicating the presence of features, which in the context of NLP, are tokens, or words. A basic implementation would involve developing a vocabulary of unique words from our corpus of tweets, and converting our tweets to vectors the length of our vocabulary, indicating the presence or absence of each word. Indeed, there are multiple methods we could employ to vectorize our text data. A simple and common method is termed the ‘bag-of-words’ model, which counts the frequency of word occurrence. A draw-back of this method is that commonly used words will be attributed high weights, although they may not convey much additional meaning. Particularly if we want to extract nuanced topics, we could perhaps emphasize less commonly occurring words the author might use to draw our attention to something.</p><p>This is the idea behind the Term Frequency-Inverse Document Frequency (TF-IDF) model, which will increase the weight of uncommon words and reduce the weight of common words. So, words that are particular to a group of tweets, focusing on a particular topic, but don’t appear frequently across the entire corpus, will be elevated in weight. In our context, tweets discussing a key event in a game, such as a penalty, will have particular vocabulary not used in the general corpus, and as such those words will be of increased importance to those tweets in this model.</p><p>We therefore below utilise the TfidfVectorizer from sklearn, which vectorises the tweets for us, via a TF-IDF based algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/712bb21e705dea3d566d414730ec358c/href">https://medium.com/media/712bb21e705dea3d566d414730ec358c/href</a></iframe><p>Note some key parameters included when the vectorizer is instantiated. The two names max_df and min_df assist at refining our list of features. min_df removes words occurring less than twice, which is reasonable as words only occurring once in the whole corpus likely add little to clustering or grouping tweets. Indeed, we could probably increase this to 3 or 4. It is worth attempting this and visualising the change in results, as well as the numbers of features included, which can be seen above. In any given corpus, some words are likely to be used repeatedly, nearly in every document, or tweet. These may be context specific, and therefore may not be included in a list of stopwords. Such words will also help little in clustering texts. As such, the max_df argument allows us to omit features that occur frequently in our corpus, and here we are removing features that are found in 80% or more of the tweets. The ngram_range indicates we are interested unigrams, bigrams and trigrams. The max_features argument allows us to limit the number of features, if need be (not applied here).</p><p>Above we can see the dimensions of the sparse matrix that is produced. We can see there are approximately 10k features in our vectorised dataset. Adjusting the parameters in the TfidfVectorizer will likely change the number of features. This is worth experimenting with.</p><p>Now we have out tweet data in vector format! This can be utilised in machine learning models, to extract patterns and make predictions.</p><h4><strong>Topic Modelling with K-means Clustering</strong></h4><p>We can deploy a K-means clustering algorithm here to try and identify clusters within our corpus. These clusters we hope will be characterised by certain topics and themes derived from our tweets about this game of football. We need to specify the number of clusters we want our tweets to be grouped into, represented by k=15. This is quite arbitrary at this point and can be changed depending on the results. The algorithm will allocate each tweet into one cluster, or topic. This kind of hard clustering may not be ideal for longer documents, with multiple topics. However, user tweets often centre around one topic, given the need to condense what needs to be conveyed down to a small number of characters. We will see if this comes across with the results of this clustering exercise.</p><p>Below we initiate the model with our vectors, extract the most prominent features in each centroid and save the feature names. We then write the results to a local file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e43f1e22776791c3486c018f538685a/href">https://medium.com/media/0e43f1e22776791c3486c018f538685a/href</a></iframe><p>Now we repeat the same process for the second half tweets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d349bf45617f70fecefa126c6cdff8a3/href">https://medium.com/media/d349bf45617f70fecefa126c6cdff8a3/href</a></iframe><h4>Results</h4><p>Remember our original intention was to attempt to utilise Tweepy to obtain tweets pertinent to a specific event. In this case, a game of football. We then wanted to determine if we could extract the key events and themes form that game via some form of topic modelling. The game we focused on was a Premier League match between Arsenal and Tottenham, that took place on October 1st, 2022. For those who are not aware, the key events were quite clear, the Arsenal player Thomas Partey scoring a great goal in the first half, following a period a domination by Arsenal. This was followed by the Tottenham player Harry Kane equalising via a penalty kick. In the second half, Arsenal again played well and took the lead via Gabriel Jesus. There was then a red card for a Tottenham player and finally a goal by Granit Xhaka. Let’s see if we can identify these key themes in our clusters!</p><p>To visually aid our analysis, we can display our TF-IDF vectors as two dimensional scatter plots. This will help us visualise if we have some clear clusters, and therefore the applicability of K-means clustering to this dataset. It will also help determine whether we need to tweak our model parameters further. To do this, we can use Principal Component Analysis (PCA) to reduce our high dimensional vectors of TF-IDF scores to a lower dimension matrix suitable for plotting. PCA is a popular dimensionality reduction algorithm that will transform the data into a lower number of dimensions while retaining as much variance as possible. We will then be able to plot this reduced dataset as a scatterplot in order to visualise key clusters.</p><p>Below, we use PCA to reduce our TF-IDF vectors into two components for each tweet . This provides us with x and y values which we then plot as a scatter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ecce8531b9165dde2172777b3a78a0/href">https://medium.com/media/11ecce8531b9165dde2172777b3a78a0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*tzl5HfA7OVSRSxaKjwyyLg.png" /></figure><p>You can see the corresponding cluster numbers in the legend. There is a mixture here of some defined clusters, as well as a great deal of overlap. We can look at the key terms per cluster we extracted earlier to see if any of the above clusters correspond to anything insightful.</p><p>Firstly, perhaps there is a central cluster of red dots, this is cluster 1, for which we extracted the following key features:</p><blockquote>Cluster 1<br> goal<br> arsenal tottenham<br> tottenham<br> goal arsenal<br> arsenal goal<br> kane<br> tottenham hotspur<br> hotspur<br> arsenal tottenham hotspur<br> harry</blockquote><p>This reflects the goals scored in the first half. Clearly the Arsenal goal, and perhaps one scored by Harry Kane. In addition to this, clusters 4, 5 and 10 appear prominent. Cluster 10 is the dark green streak to the left, which doesn’t appear as prominent in the visual, but for which the following key features were found to be most prominent, relating to the goal by Thomas Partey. In terms of key features, this is really well defined and relates to a key event in the first half.</p><blockquote>Cluster 10<br> partey<br> thomas<br> thomas parted<br> goal<br> partey arsenal<br> partey goal<br> goal thomas<br> thomas partey arsenal<br> goal thomas partey<br> lead</blockquote><p>Probably the most defined cluster is that of number 5. These tweets actually relate to links to live streaming of the game! You can see the key features in the GitHub link below. Clearly in terms of topic, this cluster is well distinguished from the others.</p><p>It should be added however, that there is a great deal of overlap centrally, which is difficult to differentiate. This may reflect a lack of clarity in the tweets, but also perhaps a need to further refine our analysis. Perhaps our stopword removal step removed some important information from our tweets. It would be worth customising our stopword list for this domain, as to retain key detail while processing.</p><p>Below we run the same analysis and visualisation for the second half tweets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99cf8fa4bd5c307e3fd03baebeacf6a1/href">https://medium.com/media/99cf8fa4bd5c307e3fd03baebeacf6a1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*XTBSehBr3ryHSMGkas7YoQ.png" /></figure><p>The second half plot is far more pronounced, perhaps reflecting this is where the game was decided and thus where users shared there feelings more acutely. We have some clusters such as 8, where fans share some optimistic sentiment.</p><blockquote>Cluster 8<br> league<br> win<br> winning<br> arsenal winning<br> arsenal win<br> win league<br> winning league<br> arsenal winning league<br> arsenal win league<br> arsenal league</blockquote><p>The dark green cluster, 10, is indicative of the following features. Again some positive sentiment, a commonly used jibe of North London being red.</p><blockquote>Cluster 10<br> london<br> north<br> north london<br> london red<br> red<br> north london red<br> london derby<br> north london derby<br> derby<br> arsenal north</blockquote><p>I was also drawn to the brown cluster in the chart above, which was caused by a key event that took place.</p><blockquote>Cluster 4<br> red<br> card<br> red card<br> card arsenal<br> red card arsenal<br> emerson<br> royal<br> emerson royal<br> arsenal red<br> game</blockquote><p>Although this cluster isn’t as prominent in the plot as i expected. The more prominent clusters appeared to relate to sentiments, rather than key events, perhaps due to a greater volume of tweets reflecting sentiment or the use of language in such tweets being more nuanced, and thus holding higher weights in a TF-IDF approach. Despite this, we were clearly able to extract some key event detail from both halves.</p><p><em>To see all the prominent features by cluster, click </em><a href="https://github.com/Ya5s3r/tweet-topic-modelling"><em>here</em></a><em>.</em></p><h4>Closing remarks</h4><p>So we have successfully drawn some key topics from our tweet data! In addition to this, we have discovered the prominence of sentiment based tweets in our corpus. The results above show us that as well as being able to highlight key events that occurred during the match, tweet data gives us insight into user sentiment towards an event or team. Perhaps due to the type of vocabulary used in such tweets, they appear prominently in a TF-IDF based approach. We were even able to highlight a cluster of tweets that seemed to include, perhaps unlawfully, links to live steams of the game.</p><p>In addition, some slightly vaguer clusters appeared during our modelling. To improve the model, we could perhaps enhance out tokenisation methods, as well as utilise a more customised stopword list, as we may have removed some important information. We could have also defined our feature list a bit more, potentially by using word lemmas — that is, the roots of words as opposed to the actual wording used in the tweet. This will give us a more precise feature list.</p><p>Another conclusion we could draw is the effectiveness of K-means clustering to group tweets into key topics. The nature of tweets, particularly their succinct nature, may often drive users to emphasize one topic per tweet. Longer documents may require other more advanced methods of topic modelling. The second half visual in particular displays some very clear clusters, although much of this reflected the sentiment of the tweeter, rather than key events in the game. The clustering method used was able to extract both types of information.</p><p>The code used here could easily be adjusted to analyse other events, both in the sporting world and other contexts. The Twitter data proved very insightful for this analysis — there were a huge number of tweets relating to this event. Perhaps another potential use for this data would be semantic analysis of player performance.</p><p><em>Thanks for reading.</em></p><h4>References</h4><p>The following resource was invaluable and helped particularly in processing the tweets.</p><p>Jens Albrecht, Sidharth Ramachandran &amp; Christian Winkler. <a href="https://www.oreilly.com/library/view/blueprints-for-text/9781492074076/">Blueprints for Text Analytics Using Python</a> (2020)</p><p>The following video assisted with the plotting of PCA values.</p><p><a href="https://www.youtube.com/watch?v=B0BkUNMqfSo&amp;list=PL2VXyKi-KpYttggRATQVmgFcQst3z6OlX&amp;index=7&amp;t=536s">https://www.youtube.com/watch?v=B0BkUNMqfSo&amp;list=PL2VXyKi-KpYttggRATQVmgFcQst3z6OlX&amp;index=7&amp;t=536s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5a5a839417" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>