<?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[ADL AI &amp; Analytics Corner - Medium]]></title>
        <description><![CDATA[Meet the AI &amp; Analytics team at Axiata Digital Labs as they bring a series of blogs to keep you updated with cutting-edge trends, breakthroughs, and advancements in the ever-evolving fields of artificial intelligence and analytics. - Medium]]></description>
        <link>https://medium.com/the-ai-analytics-corner?source=rss----871d9f25b75c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>ADL AI &amp;amp; Analytics Corner - Medium</title>
            <link>https://medium.com/the-ai-analytics-corner?source=rss----871d9f25b75c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:39:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-ai-analytics-corner" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DBT Core Introduction for Data Engineering]]></title>
            <link>https://medium.com/the-ai-analytics-corner/dbt-core-introduction-for-data-engineering-f5a2e2cacf7d?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f5a2e2cacf7d</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[dbt-labs]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Wikasitha S Herath]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 10:43:03 GMT</pubDate>
            <atom:updated>2024-03-07T11:03:05.499Z</atom:updated>
            <content:encoded><![CDATA[<h4>DBT Core Fundamentals</h4><p><strong>D</strong>ata <strong>B</strong>uild <strong>T</strong>ool known as DBT is a command line utility that assists data engineers in transforming data.</p><p>The field of data engineering is always changing, and DBT (Data Build Tool) is one of the most important tools to come out in the last few years. But what does DBT mean, and how can it help data engineers? The goal of this blog post is to answer these questions by giving a full overview of DBT Core.</p><p>In this article, I will discuss the principles of DBT Core and how it enables data engineers to construct strong data pipelines in an efficient manner.</p><p><strong>1: What is DBT?</strong></p><ul><li>DBT allows us to write SQL queries without having to worry about dependencies.</li><li>Built in SQL</li><li>It also utilizes template engines such as Jinja SQL</li><li>We also can retrieve, rearrange and organize your data using additional logic and SQL.</li><li>DBT can save our time</li><li>It can simply optimize your data workflow</li></ul><p>We know below are the common general requirements that data engineers expect from an analytic tool:</p><ul><li>Explore dependencies between models</li><li>Data quality tests</li><li>Error reporting</li><li>Molding changes are easy to follow and revert</li><li>Incremental load of tables</li><li>Track the history of dimension tables</li><li>Easy to access documentation</li></ul><p>DBT can fulfill those well and it can manage and facilitate those nicely.</p><p><strong>2: DBT overview</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*mUHBEom5Rdqur8OGnetuqg.png" /><figcaption>Fig:1: DBT overview</figcaption></figure><p><strong>3: Different DBT options /DBT products</strong></p><p>We can access DBT using DBT Core or DBT Cloud. DBT Cloud is built around DBT Core</p><ul><li>DBT core (CLI)</li><li>DBT cloud</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*8bHInRF798OQTy9SHB_w8A.png" /><figcaption>Table 1: DBT core Vs DBT cloud</figcaption></figure><p>Here, via this article we will discuss major key facts and introduction regarding only DBT core.</p><p><strong>4: What’s DBT core?</strong></p><p>DBT Core is free and open source. Individuals and companies wanting a cost-effective data transformation solution might consider DBT core.</p><p>What to expect from DBT Core:</p><ul><li>Command-Line Interface (CLI): DBT Core operates primarily through a command-line interface, offering a familiar and efficient way to manage data transformations.</li><li>Data Source Flexibility: DBT Core supports a wide range of data sources, including popular cloud data warehouses like Amazon Redshift, Snowflake, and Google BigQuery.</li><li>Modular SQL: DBT Core leverages SQL as its primary language for data transformation, allowing data engineers to leverage their existing SQL expertise.</li><li>Testing and Documentation: Similar to the full DBT offering, DBT Core empowers data engineers to implement automated data testing and document their data models comprehensively.</li></ul><p>However, it’s important to note that DBT Core requires a bit more technical setup and configuration compared to the cloud-based solution. This might involve managing dependencies and setting up connections to data warehouses manually.</p><p><strong>5: DBT core major prerequisites</strong></p><p>We can perform DBT on any OS like Windows, Mac or Linux.</p><p>To transform data in our project we must have a data warehouse (Snowflake, AWS Redshift, BigQuery etc.) DBT can create a connection to the data warehouse and run SQL codes against the warehouse. The below image shows the DBT supportive Data warehouse solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScqIkCSLCE5_3Uefdf-jDA.png" /><figcaption>Fig 2: DBT supported Data warehouse solutions</figcaption></figure><p>Version control system — To manage our code (Git, Git Lab, Azure Dev-ops)</p><ul><li>We can have a set of usages for DBT from version control system like rolling back to previous versions, tracking changes, maintaining history, integration with CI/CD pipelines and collaboration and conflict resolution.</li></ul><p><strong>6: Special DBT tips you must know</strong></p><p>Here are some of the tips we should be aware of DBT before starting the project.</p><ul><li>DBT is compatible with Python 3.7, 3.8, 3.9, 3.10, and 3.11</li><li>But it would be better to install python 3.11 to match the latest Snowflake version (latest data warehouse version). [Here I used Snowflake as the data warehouse].</li><li>Don’t use python 3.12 since at this moment DBT doesn’t support it.</li><li>Use &amp; activate the python virtual environment.</li><li>Ensure you have adequate permissions to create and manage database objects within your data warehouse.</li><li>If we experienced any issue on DBT, then we can easily figure it out from under /target/run directory</li></ul><p><strong>7: DBT core project main steps</strong></p><ul><li>Data warehouse creation &amp; registration — [ex: Snowflake registration]</li><li>Dataset import</li><li>DBT core installation</li><li>DBT setup and data warehouse connection establishment (Snowflake connection)</li><li>DBT model implementation and tastings</li><li>Setting up DBT documentation server</li></ul><p>By following the above main steps, you’ll be able to set up a DBT Core project, import your datasets, define data transformations, test your models, and generate documentation to support your data engineering and analytics workflows</p><p><strong>8: What DBT can do for our data pipelines</strong></p><ul><li>Quickly and easily provide clean, transformed data ready for analysis.</li><li>DBT can enable data analysts to custom-write transformations through SQL SELECT statements.</li><li>Apply software engineering practice, such as version control, testing, and continuous integration/continuous deployment (CI/CD)</li><li>Build reusable and modular code using Jinja</li><li>Maintain data documentation and definitions within DBT as they build and develop lineage graphs.</li><li>Perform simplified data refreshes within DBT Cloud</li><li>Perform automated testing</li></ul><p><strong>9: DBT core installation</strong></p><p>Here are the commands we need to execute to install DBT core on Linux (Ubuntu 20.04).</p><p>First, we should go into the project directory location and activate the python virtual environment.</p><p>Hint: We should have DBT supportive latest python version like python 3.11.7</p><p>Note: At this moment DBT doesn’t support python 3.12. So here I used python 3.11.7</p><pre>python --version  <br><br>         Python 3.11.7 </pre><ul><li>DBT can be installed via simple pip package,</li></ul><p>Hint: If we are using Snowflake, we should give the most recent version for that</p><pre>pip install DBT-Snowflake==1.7.1 </pre><ul><li>Next, we need to create a DBT configuration (DBT profile) folder under your home directory.</li></ul><pre>mkdir ~/.dbt</pre><ul><li>Then we can create a DBT project from the command below.</li></ul><pre>dbt init test_dbt </pre><ul><li>After executing the above command, it may ask from you about your Data warehouse details. Here I just tried with test example and “<strong>test_dbt”</strong> is our DBT project name.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6B3a3JX_WBpAdj5nQahywA.png" /><figcaption>Fig 3: DBT project initialization</figcaption></figure><p>Hint: We should give correct data warehouse name &amp; our database name etc. Database means here, when we import data into our data warehouse(Snowflake) we must create database there. On the other hand, a database should have been created in our Data warehouse. Once you create the DBT project you need to verify whether it’s working or not by running DBT debug command.</p><pre>dbt debug</pre><ul><li>If everything is fine (including DBT — data warehouse connection), then you might see it like in Fig 4.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*xpxfn6vY74hF8v1bAy00qQ.png" /><figcaption>Fig 4: DBT connection tests</figcaption></figure><ul><li>As per the above image(Fig 4) if all the tests are passed then we can start to work with DBT. Before starting to work with DBT there are a few key factors that we should have clear awareness of. Let’s look at the DBT project structure from the image (Fig 5). YAML files are commonly used here for configuration settings. (<strong><em>dbt_project.yml</em></strong>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*RwuvdQtLDAvKRhoHzUyyXg.png" /><figcaption>Fig 5: DBT project structure</figcaption></figure><p>Let’s have a look on <strong><em>dbt_project.yml </em></strong>now (Fig 6). It has all the global configurations of our DBT project.</p><p>Note: Here our DBT project name is DBTlearn2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5JLSKARtQTWuiQJsRPEeA.png" /><figcaption>Fig 6: DBT_project.yml file</figcaption></figure><p>Inside <strong><em>dbt_project.yml</em></strong> file, there are included our DBT project name, DBT version, internal config version, DBT profile name and set of default folders named analyses, DBT packages, logs, macros, models, seeds, snapshots, target and tests. Before starting a DBT project for our use cases, we must have clear knowledge &amp; understanding of the above major default folders created by DBT.</p><p><strong>10: DBT core key facts</strong></p><p><strong>10.1: DBT Model</strong></p><ul><li>Models are the basic building block of your business logic</li><li>Materialized as tables, views, etc.</li><li>They live in SQL files in the ‘models’ folder</li><li>Models can reference each other and use templates and macros</li><li>We must use CTE (Common Table Expressions) to build the DBT model</li></ul><p><strong>10.1.1: CTE (Common Table Expressions)</strong></p><pre>--Syntax  <br><br>With &lt;name of the result set&gt; ([column_names]) <br><br>AS <br><br>( <br><br>    &lt;cte_query&gt; <br><br>) <br><br>&lt;reference_the_CTE&gt; </pre><p>The “<strong>with</strong>” clause tells the database we will create a common table expression. The “<strong>column _names” </strong>are completely optional, and they can be used to set up aliases for the column names that come out of the common table expression. The “<strong>cte_query”</strong> is a just select statement and it is just a temporary table that will be referenced from the <strong>“from’</strong> clause. Furthermore, the example below can convey a very clear idea of CTE.</p><pre>WITH raw_reviews<br>AS<br>(<br> SELECT * FROM airbnb.raw.raw_reviews<br>)<br>SELECT<br>  listing_id,<br>  date AS review_date,<br>  reviewer_name,<br>  comments AS review_text, <br>  sentiment AS review_sentiment <br><br>FROM <br><br>    raw_reviews </pre><p><strong>10.2: Materialization</strong></p><p>Materializations are different ways, how our DBT model can store and manage in data warehouse. There are four built in materializations in DBT. View, Table, Incremental and Ephemeral are those types, and the default materialization format is view. We can config these in <strong><em>dbt_project.yml</em></strong><em> </em>and you can see it from the bottom line at Fig 6.</p><p>If you pick one of them (view, table, incremental and ephemeral), then your DBT model will represent it. (ex: if you choose table as the materialization technique, then you can create a DBT model as a table, it can clearly be visible on DBT documentation home page in (Fig 14), will discuss it in later section)</p><p>Let’s see a nice comparison among those options (Fig 7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWXwv023TqapJ40G8kEoJg.png" /><figcaption>Fig 7: DBT materialization types</figcaption></figure><ul><li>When we don’t need actual materialization for our model, then we can use Ephemeral materialization.</li></ul><p><strong>10.3: Seeds &amp; Sources</strong></p><p>When we do data modeling, input data can come in two ways.</p><p>1: Data is ready from integration /ETL tools /ETL process.</p><p>2: Data set is ready in our pc/lap (only if you have small data set)</p><ul><li>Seeds are the local files (from our local laptop) that we upload to the data warehouse from DBT.</li><li>Source is an abstraction layer on top of your input tables.</li><li>If you have already data in data warehouse, then it can be called source in DBT.</li><li>To make sure if our sources are up to date and get alerts, source freshness can do it.</li></ul><p><strong>10.4: Snapshots</strong></p><p>Here we need to know about type-2 slowly changing dimensions.</p><p>Let’s assume that we must update a record, but we don’t only need to overwrite it, but we need to keep the history of the changes. This is something very known best practice in Data warehousing world and we call it slowly changing dimensions. So, what might be happening there, let’s see the below image, and it clearly describes it Fig 8 ,9 &amp;10.</p><figure><img alt="Fig8: Old record" src="https://cdn-images-1.medium.com/max/908/1*C25eYkhmo3kVlOieTASJmw.png" /><figcaption>Fig 8: Old record</figcaption></figure><p>Need to update like this &gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*uCgxUzoUFnh9-sH1Ksawdg.png" /><figcaption>Fig 9: New updated record</figcaption></figure><p>Then what DBT does in Data warehouse is like below. This is the DBT snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*q0XaTvtw3u4e6kkb1nwajw.png" /><figcaption>Fig 10 : DBT snapshot</figcaption></figure><p>Here, <strong>“DBT_valid_from” </strong>means the date and time when the change happened, or initial data imported date. <strong>“DBT_valid_to”</strong> column has the details for when the last change happened. We can check the current version of data from column name called<strong> “DBT_valid_to”</strong>. If its value is null, then it means no changes happened (it might be the updated new record). If there is a value under column named <strong>“DBT_valid_to”,</strong> it should be an old record and it must have a new updated record. Fig 10, is called DBT snapshot.</p><p><strong>10.5 Tests</strong></p><p>Two types of tests are available in DBT. Singular &amp; Generic.</p><p>Singular tests are SQL queries stored in the test folder.</p><p>DBT has four built-in generic tests</p><ul><li>Unique : For a certain column we can define uniqueness constraints</li><li>not null : For a certain column we can define not null constraints</li><li>accepted_values : We can pass a list of values and those will be the only values that a column will accept.</li><li>relationships : When we take a column, and we need to make sure that every record in certain column is a valid reference to another record to another column in another table.</li></ul><p>We can also define our own custom tests in DBT.</p><p><strong>10.6 Macro &amp; DBT test packages</strong></p><ul><li>Macros are Jinja templates created under the macro folder.</li><li>Also, there are many built-in macros in DBT.</li><li>We can use macros in model definitions and tests.</li><li>A special macro called test can be used for implementing our own generic tests.</li><li>Macros can be used for custom tests and for implementing reusable SQL code.</li></ul><p><strong>10.7 Documentation</strong></p><ul><li>Here what documentation can do is we can keep documentation as close to the actual source codes.</li><li>It can be done in two ways(1 &amp; 2).</li><li>1&gt; In YAML files</li><li>2&gt; In standalone markdown files</li><li>DBT ships with a lightweight documentation web server</li><li>We can add our own assets (images) to a special project folder</li><li>DBT documentation keeps the doc as close to the project’s source code.</li><li>We can generate DBT documentation via DBT docs generate command.</li><li>Here then what happens is after executing this command, it checks all our YAML files and picks up the documentation sections and compiles it into the home page of documentation server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TZh1WPMOI9RlLTH2dnX8g.png" /><figcaption>Fig 11: DBT documentation catalog JSON file</figcaption></figure><ul><li>After creating the JSON file, we can start documentation server with it.</li><li>We can run DBT docs to serve up the documentation server portal.</li><li><strong><em>dbt docs serve &gt;</em></strong> output is below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*ObPq_Sthq_eQJabJXDHIgg.png" /><figcaption>Fig 12: DBT docs serve output</figcaption></figure><p>Here we need to make sure to check whether port 8080 is acquired by another process or not since we need to keep release port 8080 for DBT documentation server. And only if your DBT core implementation (models, tests, macro, snapshots etc)are successfully completed can you up the documentation server. Below is a sample view (Fig 13) of DBT documentation home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*r_5CIjKS0oxymp71XAVsjg.png" /><figcaption>Fig 13: DBT documentation server home page</figcaption></figure><p>We can see everything what we did in DBT core previously in shell via documentation server. All the project details, database details, tables, SQL codes, compiled codes, and data lineage (Fig 15). From the (Fig 14) we can see our created DBT model name is “<strong>dim_listings_cleansed” </strong>and its materialization type is table. It is clearly visible here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*0GzHqh1jqjjo2gB_mqyNyQ.png" /><figcaption>Fig 14: DBT doc server home page full view</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2Uteg_vil7Vp0ZJPWhvmw.png" /><figcaption>Fig 15: DBT data lineage</figcaption></figure><p>Furthermore, from the overview tab in DBT documentation server it gives a detailed chart for the relationships among the data warehouse tables. (Fig 16)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*HiHE_OtmLJbLKZamj9vYhQ.png" /><figcaption>Fig 16: DBT doc overview tab</figcaption></figure><p><strong>10.9: Extending SQL with Jinja</strong></p><ul><li>A Python based template engine is used in DBT to write code and leverage open-source innovations.</li><li>Jinja can be used in combination with SQL to create dynamic and flexible SQL queries.</li><li>You can see Jinja syntax from the images below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qlXbACGbPQsaTh8aoG40oA.png" /><figcaption>Fig 17: Jinja syntax</figcaption></figure><p><strong>11: Useful DBT commands</strong></p><ul><li><strong><em>dbt init </em></strong>: Initializes a new DBT project directory</li><li><strong><em>dbt run </em></strong>: Executes all SQL files within your project, effectively running your data transformations.</li><li><strong><em>dbt test </em></strong>: Runs any tests defined within your project to ensure data quality and consistency.</li><li><strong><em>dbt build </em></strong>: Combines the functionality of DBT run, DBT test, and optionally DBT seed in a specific order (run, test, seed) to mimic a production deployment workflow.</li><li><strong><em>dbt snapshot </em></strong>: Generates and compares snapshots of your data models to identify any discrepancies.</li><li><strong><em>dbt show </em></strong>: Displays information about specific resources like models, tests, or seeds.</li><li><strong><em>dbt source </em></strong>: Compiles your DBT project code into a single SQL script for specific use cases.</li><li><strong><em>dbt docs generate </em></strong>: to generate DBT documentation Json file</li><li><strong><em>dbt docs serve </em></strong>: To start the DBT documentation server</li></ul><pre>dbt show  <br><br>09:29:21 Running with DBT=1.7.7 <br><br>09:29:21 Registered adapter: Snowflake=1.7.1 </pre><p><strong>12: Troubleshooting</strong></p><p>If we experienced any issue on DBT core project, then we can identify by executing <strong><em>dbt run</em></strong> command. And error points will indicate in red color font. Then we might have to check under /<strong>target </strong>directory there we can see two directories called run and compiled. Under <strong>/run </strong>directory we can choose our project and go inside it and we can see the model, seeds, snapshots etc. Then we can check and figure out the root course for the issue and we can do troubleshooting there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI9tS5KnM3Ca6IwXkyN7xg.png" /><figcaption>Fig 18: DBT run error handling</figcaption></figure><p><strong>Conclusion</strong></p><p>By utilizing the data warehouse’s built-in capabilities, DBT can significantly improve data workflows. Data engineers may optimize and enhance their data workflow efficiency with DBT cloud and DBT core. We should understand the DBT core, its key factors, and how to install and debug DBT before we start using it, so I’ve done my best to explain that in this first article about DBT.</p><p><strong>Reference:</strong></p><ul><li><a href="https://docs.getdbt.com/guides/manual-install?step=1">Quickstart for dbt Core from a manual install | dbt Developer Hub</a></li><li><a href="https://docs.getdbt.com/docs/introduction">What is dbt? | dbt Developer Hub</a></li></ul><p><strong>Visit our website to find out more about our products and services.</strong></p><figure><a href="https://www.axiatadigitallabs.com/"><img alt="" src="https://cdn-images-1.medium.com/max/900/1*zs0gOvtiLpD5f3t6DvmunQ.png" /></a></figure><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a2e2cacf7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/dbt-core-introduction-for-data-engineering-f5a2e2cacf7d">DBT Core Introduction for Data Engineering</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Essential Azure Data Engineering Services for Data Engineers]]></title>
            <link>https://medium.com/the-ai-analytics-corner/top-10-essential-azure-data-engineering-services-for-data-engineers-9b56e5c57b7f?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/9b56e5c57b7f</guid>
            <category><![CDATA[azure-storage]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[azure-data-engineering]]></category>
            <category><![CDATA[data-science-training]]></category>
            <category><![CDATA[data-processing]]></category>
            <dc:creator><![CDATA[Vidushraj Chandrasekaran]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 04:37:22 GMT</pubDate>
            <atom:updated>2023-12-12T04:37:22.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-6qOi7USPc1vL57EYP6EOA.jpeg" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/microsoft-azure-cloud-services-techlearnindia/">https://www.linkedin.com/pulse/microsoft-azure-cloud-services-techlearnindia/</a></figcaption></figure><h4>Introduction to Data Engineering in Azure</h4><p>Data engineering is the backbone of data-driven decision-making, focusing on the collection, transformation, and storage of vast amounts of data. In this era, where information reigns supreme, cloud computing has become essential. It offers unparalleled scalability and efficiency in storing massive datasets and performing complex data processing tasks. Among the leading cloud service providers AWS, Azure, and GCP data engineers rely on these platforms’ robust infrastructures to harness data’s potential. In this article I will delve into the top services offered by Azure, crucial for data engineers in architecting and managing modern data ecosystems.</p><h3>10. Azure Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*ncpSDKtGG0snpgIjGz9LFw.jpeg" /><figcaption>Azure Storage Services</figcaption></figure><p>Azure offers a diverse array of data storage services, catering to the varied needs of modern data management. Azure storage is divided into four main categories they are Blob storage, File storage, Table storage, and Queue storage.</p><p>Blob Storage</p><ol><li>Stands for Binary Large Object</li><li>Storing unstructured data (Text, Images, Videos, and so on..)</li><li>Unlimited storage services.</li><li>A massively scalable object store for text and binary data. Also includes support for big data analytics through Data Lake Storage Gen2.</li><li>Use cases: When your application wants to support streaming and random access scenarios, when you want your data to be accessible from anywhere, and when to build an enterprise data lake on Azure and perform big data analytics.</li></ol><p>File Storage</p><ol><li>Managed file shares for cloud or on-premises deployments.</li><li>Enables you to set up highly available network file shares that can be accessed by using the industry standard <a href="https://learn.microsoft.com/en-us/windows/win32/fileio/microsoft-smb-protocol-and-cifs-protocol-overview">Server Message Block (SMB) protocol</a>, <a href="https://en.wikipedia.org/wiki/Network_File_System">Network File System (NFS) protocol</a>, and <a href="https://learn.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api">Azure Files REST API</a>.</li><li>Use cases: When you want to store development and debugging tools that need to be accessed from many virtual machines When you want to replace or supplement on-premises file servers or NAS devices.</li></ol><p>Queue Storage</p><ol><li>A messaging store for reliable messaging between application components.</li><li>Stores data in FIFO rule.</li></ol><p>Table Storage</p><ol><li>A NoSQL store for schemaless storage of structured data.</li><li>NoSQL key-value storage.</li><li>No fixed schema.</li></ol><h3>09. Azure SQL DB</h3><p>Azure SQL Database is a fully managed relational database service offered by Microsoft Azure. It’s designed to host SQL databases in the cloud without the hassle of managing infrastructure. This service ensures high availability, scalability, and robust security features for your data.</p><p>Azure SQL Database provides three deployment options:</p><ol><li>Single is a fully managed, isolated database.</li><li>Elastic Pool is a collection of single databases with a shared set of resources.</li><li>A managed Instance is a fully managed instance of the SQL server.</li></ol><p>SQL Database offers a lot of available features like Automatic backups, Point-in-time restores, Active geo-replication, Auto-failover groups, and Zone-redundant databases.</p><h3>08. Azure Cosmos DB</h3><p>Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft Azure. It’s designed to handle vast amounts of structured and unstructured data, allowing developers to build highly responsive and scalable applications. Applies to NoSQL, MongoDB, Cassandra, Gremlin, Table, and PostgreSQL. Azure Cosmos DB can simplify and expedite your development by being the single AI database for your applications. Azure Cosmos DB is a fully managed NoSQL and relational database for modern app development including; AI, digital commerce, Internet of Things, booking management, and other types of solutions.</p><p>Key Benefits</p><ul><li>Guaranteed speed at any scale</li><li>Simplified application development</li><li>Mission-critical ready</li><li>Fully managed and cost-effective</li></ul><h3>07. Azure HDInsight</h3><p>Azure HDInsight is a fully managed cloud service from Microsoft Azure that offers Apache Hadoop and Apache Spark clusters. It provides a scalable, reliable, and high-performance environment for processing large volumes of data. HDInsight is a cloud distribution of Hadoop components. HDInsight lets you run Apache Spark, Apache Hive, Apache Kafka, Apache HBase, and more in the cloud.</p><h3>06. Azure Data Lake Storage</h3><p>Azure Data Lake Storage is a highly scalable and secure cloud storage service from Microsoft Azure designed specifically for big data analytics. It enables users to store and analyze large amounts of structured and unstructured data at any scale. Azure Data Lake Storage Gen2 is an evolution of Data Lake Storage Gen1 built on top of Blob Storage. A data lake is a single, centralized repository where you can store all your data, both structured and unstructured. Data Lake Storage Gen2 includes the following capabilities Hadoop-compatible access, Hierarchical directory structure, Optimized cost and performance, Finer grain security model, and Massive scalability.</p><h3>05. Azure Stream Analytics</h3><p>Azure Stream Analytics is a fully managed (PaaS) offering on Azure. Azure Stream Analytics is a real-time stream processing and analytics service designed to handle high-volume data with sub-millisecond latency.</p><p>Key Features</p><ul><li>Real-time processing — Analyze data streams as they occur and empower businesses to gain valuable insights, detect anomalies, and trigger actions swiftly, making it a valuable tool for real-time analytics and decision-making.</li><li>Scalability</li><li>Ease of use — A few clicks is enough to connect multiple sources and sinks, and create an end-to-end pipeline. To ingest streaming data into Azure Stream Analytics we can use Azure Event Hub and Azure IoT Hub as well as historical data from Azure Blob Storage. In the same way, we can route the output from stream jobs into Azure Blob storage, Azure SQL Database, Azure Data Lake Store, and Azure Cosmos DB. It offers a no-code editor.</li><li>Versatility — Low-latency dashboarding, Streaming analytics, Real-time alerting, Geospatial analytics, Predictive maintenance, and Clickstream analytics.</li></ul><h3>04. Azure Machine Learning</h3><p>Azure ML is a cloud-based service provided by Azure to empower data scientists and developers to build, deploy, and manage high-quality machine learning models faster and with confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*9_5ziRNO-po64grogpMfQw.jpeg" /><figcaption>Graphic Credit: Microsoft Azure ML Service Documentation</figcaption></figure><p>The workspace contains all related assets related to ML such as Compute, Storage, Data, Scripts, Notebooks, Experiments, Metrics, Pipelines, and Models. It seamlessly integrates with other Azure services, enabling users to deploy models as web services or containers, monitor model performance, and implement continuous integration/continuous deployment (CI/CD) pipelines for efficient model updates.</p><p>Key Features</p><ol><li>Potential to auto-train and auto-tune a model.</li><li>The model trained locally can be deployed.</li></ol><h3>03. Azure Data Factory</h3><p>1. Azure Data Factory — Code-free ETL as a service that provides, data ingestion, Control flow, data flow, schedule, and monitor.</p><p>2. Integration Runtime — Provides the compute infrastructure that is used by ADF to run data flow and do data transformation. Three types of IR are available they are Azure, Self-hosted, and Azure-SSIS.</p><p>3. Triggers — Used to automatically run the pipeline during a certain frequency, scheduled time, or when some specific event happened. Types of triggers are Schedule triggers, Tumbling Window triggers, and Event-based triggers.</p><p>4. Mapping Data Flow — Visually designed data transformations in ADF.</p><p>5. Azure Key Vault — Used to store secure secrets.</p><p>ADF is the cloud-based ETL and data integration service that allows you to create data-driven workflows for orchestrating data movement and transforming data at scale. Azure Data Factory is composed of the following key components: Pipelines, Activities, Datasets, Linked services, Data Flows and Integration Runtimes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF-eO3xfseqhCy2_uYMaGg.png" /><figcaption>Source:<a href="https://medium.com/javarevisited/azure-data-factory-as-an-etl-tool-and-its-use-cases-f36a7a421cee">https://medium.com/javarevisited/azure-data-factory-as-an-etl-tool-and-its-use-cases-f36a7a421cee</a></figcaption></figure><h3>02. Azure Synapse Analytics</h3><p>Commonly known as Azure SQL Data Warehouse it’s a cloud-based analytic service provided by Azure. Supports both structured and unstructured data sources from all different data sources and allows users to process large amounts of data for analytical workloads. It supports massive parallel processing (MPP) architecture, enabling high-performance querying and processing of large datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*3quLWdc90lych_dtST_qwQ.png" /></figure><h3>01. Azure Data Bricks</h3><p>Azure Data Bricks is a unified analytics engine for big data processing. Azure Databricks is a fast, collaborative, and Apache Spark-based analytics platform offered by Microsoft Azure. It’s designed to simplify big data analytics and AI workflows by providing an interactive workspace for data engineers, data scientists, and analysts to collaborate and perform data processing, exploration, and machine learning tasks. It supports multiple languages such as Scala, Python, R, Java, and SQL. Azure Databricks offers three environments SQL, Data science and engineering, and Machine learning. The platform leverages Apache Spark’s distributed computing power, allowing users to scale resources dynamically based on workload requirements. It supports real-time analytics, batch processing, and ETL (Extract, Transform, Load) operations, providing versatility in data processing tasks.</p><h3>Resources</h3><ol><li><a href="https://learn.microsoft.com/en-us/azure/storage/common/storage-introduction">https://learn.microsoft.com/en-us/azure/storage/common/storage-introduction</a></li><li><a href="https://learn.microsoft.com/en-us/azure/azure-sql/database/sql-database-paas-overview?view=azuresql">https://learn.microsoft.com/en-us/azure/azure-sql/database/sql-database-paas-overview?view=azuresql</a></li><li><a href="https://azure.microsoft.com/en-us/products/cosmos-db">https://azure.microsoft.com/en-us/products/cosmos-db</a></li><li><a href="https://learn.microsoft.com/en-us/azure/hdinsight/">https://learn.microsoft.com/en-us/azure/hdinsight/</a></li><li><a href="https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction">https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction</a></li><li><a href="https://learn.microsoft.com/en-us/azure/stream-analytics/stream-analytics-introduction">https://learn.microsoft.com/en-us/azure/stream-analytics/stream-analytics-introduction</a></li><li><a href="https://towardsdatascience.com/azure-machine-learning-service-part-1-an-introduction-739620d1127b">https://towardsdatascience.com/azure-machine-learning-service-part-1-an-introduction-739620d1127b</a></li><li><a href="https://k21academy.com/microsoft-azure/dp-100/azure-machine-learning-service-workflow-for-beginners/">https://k21academy.com/microsoft-azure/dp-100/azure-machine-learning-service-workflow-for-beginners/</a></li><li><a href="https://learn.microsoft.com/en-us/azure/synapse-analytics/overview-what-is">https://learn.microsoft.com/en-us/azure/synapse-analytics/overview-what-is</a></li></ol><p>10. <a href="https://k21academy.com/microsoft-azure/data-engineer/azure-databricks/">https://k21academy.com/microsoft-azure/data-engineer/azure-databricks/</a></p><p><strong>Visit our </strong><a href="https://www.axiatadigitallabs.com/"><strong>website</strong></a><strong> to find out more about our products and services.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*RhLXc1ChgdNMXgrg8thAhg.png" /><figcaption><a href="https://www.axiatadigitallabs.com/">https://www.axiatadigitallabs.com/</a></figcaption></figure><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b56e5c57b7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/top-10-essential-azure-data-engineering-services-for-data-engineers-9b56e5c57b7f">Top 10 Essential Azure Data Engineering Services for Data Engineers</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 3]]></title>
            <link>https://medium.com/the-ai-analytics-corner/deploy-a-dask-cluster-on-kubernetes-using-minikube-on-wsl-part-3-d0a29872709a?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0a29872709a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[dask-sql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nirajkanth Ravichandran]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 14:06:01 GMT</pubDate>
            <atom:updated>2023-09-22T14:06:01.735Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 3</h3><h4>Harnessing Dask-SQL for Machine Learning on Kubernetes</h4><p><strong>Introduction</strong></p><p>In the ever-evolving landscape of data science and machine learning, the ability to efficiently process and analyze large datasets is crucial. Dask, a flexible parallel computing library in Python, provides a powerful solution to tackle big data challenges by allowing users to create parallel algorithms with familiar APIs. When combined with Kubernetes, an open-source container orchestration platform, Dask can further scale its capabilities. This article delves into the integration of Dask-SQL with a Dask Kubernetes cluster for machine learning tasks, showcasing the process through the example of training a classifier model on the popular IRIS dataset.</p><p>The code I employed for the experiment is available in this <a href="https://github.com/Nirajkanth/Dask/blob/master/dask_sql_1.ipynb">notebook</a>.</p><p><strong>Setting Up the Kubernetes Cluster</strong></p><p>Before diving into Dask-SQL and machine learning, it’s essential to have a functional Kubernetes cluster. If you’re not familiar with setting up a cluster, you can refer to my <a href="https://medium.com/p/f8155324b00e/edit">previous article</a> on how to configure a Kubernetes cluster in your local machine.</p><p><strong>Introducing Dask-SQL</strong></p><p>Dask-SQL is an extension of Dask that allows SQL queries to be executed directly on Dask dataframes. This seamless integration between Dask and SQL empowers data scientists with SQL’s expressive querying capabilities while leveraging Dask’s parallel processing abilities. The integration of Dask-SQL within a Kubernetes-based Dask cluster opens doors to processing vast datasets efficiently and performing complex analytical tasks.</p><p><strong>Machine Learning with Dask-SQL on Kubernetes</strong></p><p>Let’s walk through a practical application of Dask-SQL for machine learning within the Kubernetes environment. We’ll use the IRIS dataset for simplicity, but the same approach can be extended to larger datasets.</p><p>To begin our exploration, let’s initiate Dask-Kubernetes, which is also referred to as KubeClusters, as demonstrated in the code examples below. Please be aware that if you come across any packages that are not found on the scheduler, you can install them using extra pip/conda packages.</p><pre>from dask_kubernetes.operator import KubeCluster<br><br>cluster = KubeCluster(name=&quot;daskmlcluster&quot;,<br>                      image=&#39;ghcr.io/dask/dask:2023.7.0-py3.10&#39;,<br>                      n_workers=2,<br>                      resources={&quot;requests&quot;: {&quot;memory&quot;: &quot;0.5Gi&quot;}, &quot;limits&quot;: {&quot;memory&quot;: &quot;1.5Gi&quot;}},<br>                      env={<br>                       &#39;EXTRA_PIP_PACKAGES&#39;:&quot;dask-sql==2023.8.0 dask-ml==2023.3.24 scikit-learn==1.3.0&quot;<br>                           }<br>                     )<br>cluster</pre><pre>from dask.distributed import Client<br># Connect Dask to the cluster<br>client = Client(cluster)<br>client</pre><p><strong>Data Loading and Exploration</strong></p><p>Before loading the data, it is necessary to initiate context class form Dask-SQL which provides an environment where you can execute SQL queries on Dask dataframes.</p><pre>from dask_sql import Context<br>c = Context()  # Python equivalent to a SQL database</pre><ul><li>Read the data from internet and register the data as iris in the dask_sql.context that we created above.</li></ul><pre>c.sql(&quot;&quot;&quot;CREATE OR REPLACE TABLE iris WITH (<br>    location = &#39;https://datahub.io/machine-learning/iris/r/iris.csv&#39;,<br>    persist = True)&quot;&quot;&quot;<br>)</pre><p>· Let’s verify whether the data registration is successful.</p><pre>c.sql(&quot;&quot;&quot;SHOW TABLES FROM root&quot;&quot;&quot;).compute()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ivRLdF2zkVJnLSb0RfcR5Q.png" /></figure><p>As we can see, the data has been registered successfully with named ‘iris’.</p><p>· Let’s visualize how the data looks.</p><pre>c.sql(&quot;&quot;&quot;SELECT * From iris&quot;&quot;&quot;).compute()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Q32ebqNANSEpoOHAxC0gBQ.png" /></figure><ul><li>Given that the ‘class’ column is a categorical variable, it’s crucial to examine its distinct values. You can accomplish this by using the following code:</li></ul><pre>c.sql(&quot;&quot;&quot;SELECT * From iris&quot;&quot;&quot;).compute()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Uo9mHIquQvjA-oIqMvWAuQ.png" /></figure><p><strong>Model Training</strong></p><p>Dask-SQL provides support for Scikit-Learn-based machine learning models. In this specific experiment, I am utilizing the GradientBoostingClassifier from the Scikit-Learn library. Given that we are working with the Iris dataset, the transformation of a categorical column into a numerical format becomes crucial. To achieve this, a simple SQL query can be applied while the model training process as follows.</p><pre>c.sql(&quot;&quot;&quot;<br>    CREATE MODEL sql_model WITH (<br>        model_class = &#39;sklearn.ensemble.GradientBoostingClassifier&#39;,<br>        wrap_predict = True,<br>        target_column = &#39;target&#39;<br>    ) AS (<br>        SELECT sepallength, sepalwidth, petallength, petalwidth, <br>            CASE<br>                WHEN class = &#39;Iris-setosa&#39; THEN 0<br>                WHEN class = &#39;Iris-versicolor&#39; THEN 1<br>                WHEN class = &#39;Iris-virginica&#39; THEN 2<br>            END AS target<br>        FROM iris<br>        LIMIT 100<br>    )<br>&quot;&quot;&quot;)</pre><p>This will train the model and store within the Dask-SQL context under the name ‘sql_model’. We can verify as follows.</p><pre>c.sql(&quot;&quot;&quot;SHOW MODELS&quot;&quot;&quot;).compute()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*6v7Cytk6FpR8w_g3WtzUfQ.png" /></figure><p><strong>Hyperparameter Tuning</strong></p><p>Following the initial model training, lets employ Dask’s parallel computing capabilities for hyperparameter tuning. Utilize Dask’s distributed computing to execute hyperparameter searches across the Kubernetes cluster. By parallelizing this process, you speed up the search for optimal hyperparameters, enhancing the model’s performance.</p><pre>query = &quot;&quot;&quot;<br>CREATE EXPERIMENT my_exp WITH (<br>   model_class = &#39;sklearn.ensemble.GradientBoostingClassifier&#39;,<br>   experiment_class = &#39;sklearn.model_selection.GridSearchCV&#39;,<br>   tune_parameters = (n_estimators = ARRAY [16, 32, 2],<br>                   learning_rate = ARRAY [0.1,0.01,0.001],<br>                  max_depth = ARRAY [3,4,5,10]<br>                  ),<br>   target_column = &#39;target&#39;<br>   ) AS (<br>      SELECT sepallength, sepalwidth, petallength, petalwidth,<br>            CASE<br>                WHEN class = &#39;Iris-setosa&#39; THEN 0<br>                WHEN class = &#39;Iris-versicolor&#39; THEN 1<br>                WHEN class = &#39;Iris-virginica&#39; THEN 2<br>            END AS target<br>        FROM iris<br>        LIMIT 100<br>   )<br>&quot;&quot;&quot;<br>result1 = c.sql(query)</pre><p>The provided code snippet will train multiple models using the specified parameters and save the best-performing model with the identifier ‘my_exp’.</p><p>Additionally, you have the capability to access all the models that were trained during the hyperparameter tuning process, as demonstrated in the following code snippets.</p><pre>sorted_r = result1.sort_values(by=&#39;mean_test_score&#39;, ascending=False)<br>sorted_r.compute().head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*IWlrMH_Bh6b-fDL1TYgHlQ.png" /></figure><p>We can observe the Dask dashboard, which illustrates the distributed training occurring across the cluster as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*c9SbEnB02JT9mm2pPCvYbw.png" /></figure><p>· Verify the stored model</p><pre>c.sql(&quot;&quot;&quot;SHOW MODELS&quot;&quot;&quot;).compute()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*KXbxZEkAJJFCPQ_pUi1Tyw.png" /></figure><p>Now we can see there are two model has been registered in the Dask-SQL context which are model without hyperparameter tuning (sql_model) and model with hyperparameter tuning (my_exp).</p><p><strong>Model Prediction</strong></p><p>Once the model is trained and tuned, predictions can be done from the stored model as follows.</p><pre>c.sql(&quot;&quot;&quot;<br>    SELECT * FROM PREDICT (<br>        MODEL my_exp,<br>        SELECT sepallength, sepalwidth, petallength, petalwidth,<br>        CASE<br>            WHEN class = &#39;Iris-setosa&#39; THEN 0<br>            WHEN class = &#39;Iris-versicolor&#39; THEN 1<br>            WHEN class = &#39;Iris-virginica&#39; THEN 2<br>        END AS actual<br>        FROM iris<br>        OFFSET 50<br>    )<br>&quot;&quot;&quot;).compute()</pre><p>Here are the predictions. It is clear that, there is room for further improvement through various optimization techniques. However, it’s important to note that the primary focus of this article is to showcase Dask-SQL machine learning on a Kubernetes cluster. Therefore, for the purpose of this article, we will skip delving into the optimization techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*18vo6J6vIZIBXfcjYnDsUA.png" /></figure><p>Conclusion</p><p>In this article, the integration of Dask-SQL with a Kubernetes-driven Dask cluster has been demonstrated, showcasing its prowess in efficient and scalable machine learning workflows. The fusion of Dask’s parallel processing with SQL querying via Dask-SQL enables streamlined data analysis, as exemplified by training a Gradient Boosting Classifier on the Iris dataset. Leveraging Dask’s dynamic scaling and Kubernetes’ resource management, the collaboration empowers data scientists to handle extensive datasets adeptly. While optimization techniques are pertinent for further enhancement, this article’s focus remains on illustrating the potential of Dask-SQL machine learning within the Kubernetes context, offering a pathway for effective, parallelized, and scalable data analysis and machine learning in the era of significant data challenges.</p><p><strong>Visit </strong><a href="https://www.axiatadigitallabs.com/"><strong>Axiata Digital Labs</strong></a><strong> to find out more about our products and services.</strong></p><figure><img alt="https://www.axiatadigitallabs.com/" src="https://cdn-images-1.medium.com/max/376/1*-WXvF8AtCSJ70lg8Zp1MMQ.png" /><figcaption><a href="https://www.axiatadigitallabs.com/"><em>.</em></a></figcaption></figure><p>References</p><p>1. <a href="https://dask-sql.readthedocs.io/en/latest/machine_learning.html">https://dask-sql.readthedocs.io/en/latest/machine_learning.html</a></p><p>2. <a href="https://kubernetes.dask.org/en/latest/">https://kubernetes.dask.org/en/latest/</a></p><p>3. <a href="https://datahub.io/machine-learning/iris">https://datahub.io/machine-learning/iris</a></p><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a29872709a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/deploy-a-dask-cluster-on-kubernetes-using-minikube-on-wsl-part-3-d0a29872709a">Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 3</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 2]]></title>
            <link>https://medium.com/the-ai-analytics-corner/deploy-a-dask-cluster-on-kubernetes-using-minikube-on-wsl-part-2-5f181bbc7e5e?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/5f181bbc7e5e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cluster-management]]></category>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Nirajkanth Ravichandran]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 11:18:27 GMT</pubDate>
            <atom:updated>2023-09-19T11:18:27.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 2</h3><h4>Exploring Dask Machine Learning on Kubernetes</h4><p>In recent years, machine learning has seen tremendous growth, enabling data scientists and researchers to tackle complex problems more efficiently. However, as datasets and models become larger, the need for scalable and distributed computing arises. Dask, a flexible parallel computing library, and Kubernetes, a container orchestration platform, offer a potent combination for tackling such challenges. In this article, we’ll explore how to harness the capabilities of Dask and Kubernetes to train a Support Vector Regressor (SVR) model on a popular house pricing dataset.</p><p>The code I employed for the experiment is available in this <a href="https://github.com/Nirajkanth/Dask/blob/master/dask_ml_reg.ipynb">notebook</a>.</p><p>You can find the step-by-step guide for setting up a local, single-node Kubernetes environment in my <a href="https://medium.com/p/f8155324b00e/edit">preceding article</a>. Let’s assume that you’ve already got your Kubernetes cluster up and running, for the rest of this article.</p><p>To kickstart our journey, let’s initialize the Dask-Kubernetes, also known as KubeClusters, as shown in the following code snippets.</p><pre>from dask_kubernetes.operator import KubeCluster<br><br>extra_pip_packages =  &quot;&quot;&quot;scikit-learn==1.3.0<br>                         dask-ml==2023.3.24&quot;&quot;&quot;<br>cluster = KubeCluster(name=&quot;daskmlcluster&quot;,<br>                      image=&#39;ghcr.io/dask/dask:2023.7.0-py3.10&#39;,<br>                      n_workers=2,<br>                      env={<br>                      &#39;EXTRA_PIP_PACKAGES&#39;: extra_pip_packages<br>                           },<br>                      resources={&quot;requests&quot;: {&quot;memory&quot;: &quot;0.5Gi&quot;}, &quot;limits&quot;: {&quot;memory&quot;: &quot;1.5Gi&quot;}},<br>                     )<br>cluster</pre><pre>from dask.distributed import Client<br># Connect Dask to the cluster<br>client = Client(cluster)<br>client</pre><p>Note: Scikit-learn library isn’t pre-installed in the Dask Docker image. Consequently, it’s essential to install scikit-learn as an extra package via pip or conda, as indicated in the <a href="https://kubernetes.dask.org/en/latest/kubecluster.html">Dask documentation</a></p><p><strong>Dataset and Preprocessing</strong></p><p>For this demonstration, we’ll use a well-known <a href="https://www.kaggle.com/datasets/yasserh/housing-prices-dataset">house pricing</a> dataset. Our goal is to predict house prices based on various features. To prepare the data, we’ll employ the scikit-learn library. Let’s do step by step data analysis.</p><ul><li>Import required libraries</li></ul><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.metrics import r2_score, mean_squared_error<br>from sklearn.svm import SVR<br>import seaborn as sns</pre><ul><li>Read the dataset</li></ul><pre>df = pd.read_csv(&#39;/mnt/d/codes/Dask/Housing.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tYT8aQtxCMggSGkacLuZ6Q.png" /></figure><ul><li>Exploring each column</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*hfoge5_7CBUOmfxZKif23g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*dJuSPmCPpLcnEMIG6MjmqA.png" /></figure><ul><li>Extract all categorical columns</li></ul><pre>#extracting categorical colums <br>cat_cols = [col for col in df.columns if df[col].dtype == &#39;object&#39;]<br>cat_cols</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gKLn-RkhOkJwznJ3OdJXHw.png" /></figure><ul><li>Convert categorical columns to numerical columns using LabelEncoder</li></ul><pre>df_encoded = df.copy()<br><br>le = LabelEncoder()<br>for col in cat_cols:<br>    df_encoded[col] = le.fit_transform(df_encoded[col])<br>df_encoded.head()</pre><ul><li>Split the dataset</li></ul><pre>x = df_encoded.drop([&#39;price&#39;], axis=1)<br>y = df_encoded[&#39;price&#39;]<br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3)</pre><p><strong>Hyperparameter Tuning</strong></p><p>Hyperparameter tuning plays a vital role in optimizing the performance of machine learning models. We’ll employ scikit-learn grid search to explore different combinations of hyperparameters for our SVC regression model. This step ensures that our model is performing at its best.</p><p>Let’s define the parameter grid as follows.</p><pre># Define the parameter grid for hyperparameter tuning<br>param_grid = {<br>    &#39;C&#39;: [0.1, 1, 3, 10,],<br>    &#39;epsilon&#39;: [0.001, 0.01, 0.1, 0.2],<br>    &#39;kernel&#39;: [&#39;linear&#39;, &#39;poly&#39;, &#39;rbf&#39;, &#39;sigmoid&#39;]<br>}</pre><p><strong>Joblib with KubeCluster</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*DhJeW1HqkoNuG2IBo3VfEw.png" /><figcaption>Source: <a href="https://ml.dask.org/joblib.html">https://ml.dask.org/joblib.html</a></figcaption></figure><p>Here’s where the magic of Dask truly shines. By utilizing the power of Joblib in conjunction with Kubernetes, we parallelize the training process even further. Joblib, a popular library for lightweight pipelining in Python, integrates seamlessly with Dask to distribute tasks across the cluster. This union of technologies maximizes efficiency and accelerates the model training procedure.</p><pre>svr = SVR()<br>grid_search = GridSearchCV(svr, param_grid, cv=5, scoring=&#39;neg_mean_squared_error&#39;)<br><br># Fit the grid search to the data, use dask kubecluster as backend<br>import joblib<br>with joblib.parallel_backend(&#39;dask&#39;):<br>    grid_search.fit(x_train, y_train)</pre><p>While executing the above code snippets, you can observe dask dashboard as in the following figure; where you can observer how tasks are distributed across the workers/threads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*uEYcCT_00ue242N5Sn0Vvw.png" /></figure><p><strong>Model prediction</strong></p><p>Let’s perform model prediction on the test data and evaluate the model using mean squared error and r2_score.</p><p>Code</p><pre># Get the best parameters and best estimator<br>best_params = grid_search.best_params_<br>best_svr = grid_search.best_estimator_<br><br># Make predictions on the test set<br>y_pred = best_svr.predict(x_test)<br>mse = mean_squared_error(y_test, y_pred)<br>r2 = r2_score(y_test, y_pred)<br><br>print(f&quot;Mean squared error: {mse}&quot;)<br>print(f&quot;R-squared score: {r2}&quot;)</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*l5Dot_ljCth15CdHu4PkAg.png" /></figure><p>As you can see, there’s potential to enhance the r2_score even further through normalization and a few other optimization techniques. Nevertheless, it’s important to note that the primary focus of this article is to run machine learning via Dask’s Kubernetes cluster. Thus, for the purpose of this article, we will stay here, without dive into evaluation metric enhancement.</p><p><strong>Conclusion</strong></p><p>In this article, we’ve explored how to leverage the power of Dask and Kubernetes for distributed machine learning. By combining Dask’s parallelism and dynamic task scheduling with Kubernetes’ container orchestration, we can efficiently train a complex machine learning model like an SVC regression model on a large dataset. This approach not only reduces training time but also enables us to work with datasets that would be impractical to handle on a single machine.</p><p><strong>Visit </strong><a href="https://www.axiatadigitallabs.com/"><strong>Axiata Digital Labs</strong></a><strong> to find out more about our products and services.</strong></p><figure><img alt="https://www.axiatadigitallabs.com/" src="https://cdn-images-1.medium.com/max/376/1*-WXvF8AtCSJ70lg8Zp1MMQ.png" /><figcaption><a href="https://www.axiatadigitallabs.com/"><em>.</em></a></figcaption></figure><p>References</p><p>1. <a href="https://ml.dask.org/joblib.html">https://ml.dask.org/joblib.html</a></p><p>2. <a href="https://kubernetes.dask.org/en/latest/">https://kubernetes.dask.org/en/latest/</a></p><p>3. <a href="https://scikit-learn.org/stable/modules/grid_search.html">https://scikit-learn.org/stable/modules/grid_search.html</a></p><p>4. <a href="https://ml.dask.org/">https://ml.dask.org/</a></p><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f181bbc7e5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/deploy-a-dask-cluster-on-kubernetes-using-minikube-on-wsl-part-2-5f181bbc7e5e">Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 2</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 1]]></title>
            <link>https://medium.com/the-ai-analytics-corner/deploy-a-dask-cluster-on-kubernetes-using-minikube-on-wsl-f8155324b00e?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f8155324b00e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[minikube-installation]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-engineering-101]]></category>
            <dc:creator><![CDATA[Nirajkanth Ravichandran]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 20:51:39 GMT</pubDate>
            <atom:updated>2023-09-18T03:25:43.745Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick &amp; easy guide to set up dask kubernetes cluster on your local machine using Minikube</h4><p>In the realm of data-intensive applications and large-scale data processing, the need for efficient and scalable computing resources is paramount. Kubernetes, an open-source container orchestration platform, has emerged as a powerful tool for managing and scaling containerized applications. When combined with Dask, a flexible parallel computing library in Python, you have the potential to create a highly resilient and dynamic data processing environment. In this article, we’ll explore the process of deploying a Dask cluster on top of a Kubernetes cluster, utilizing Minikube within the Windows Subsystem for Linux (WSL) environment.</p><p><strong>Setting Up the Kubernetes Cluster</strong></p><p>Before diving into deploying a Dask cluster, we need to have a Kubernetes cluster up and running on our local machine. While Minikube is a popular choice, setting it up within the WSL environment provides a powerful development setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nwlFaDD-woJlzy3P6zLK-A.png" /><figcaption><strong>Images from : https://codecrux.com/blog/minikube-tips.html</strong></figcaption></figure><p><strong>Selecting Minikube for Local Kubernetes in WSL</strong></p><p>Minikube is an ideal choice for local Kubernetes development due to its simplicity and rapid setup. When combined with WSL, it enables a seamless Linux environment within a Windows operating system.</p><p>To begin, we need to meet the minimum requirements set by Minikube:</p><ul><li>At least 2 CPU cores</li><li>2 GB of available memory</li><li>20 GB of available disk space</li><li>An active internet connection</li><li>A container or virtual machine manager (For our guide, we’ll use Docker.)</li></ul><p><strong>Installing and Configuring Minikube</strong></p><p>To install Minikube within the WSL environment, follow these steps:</p><ol><li>Enable WSL: Ensure that you have Windows Subsystem for Linux (WSL) enabled on your Windows machine. You can follow the official <a href="https://learn.microsoft.com/en-us/windows/wsl/install">Microsoft documentation</a> to set this up.</li><li>Install Docker Desktop: Install <a href="https://docs.docker.com/desktop/install/windows-install/">Docker Desktop for Windows</a>, which will be used to manage containers within the WSL environment. Then, enable the ‘Use the WSL2 based engine’ and ‘wsl distribution’ in the setting as shown in the following figures in my case it is ubuntu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ND40FTHdB09Qjk3uGQ9jhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*x3Y-8gze9qNi1ra-PJzSyg.png" /></figure><p>3. Install kubectl: Kubectl is the command-line tool used to interact with Kubernetes clusters. Install it within your WSL environment according to the instructions for Linux.</p><pre>curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl<br><br>chmod +x ./kubectl<br>sudo mv ./kubectl /usr/local/bin/kubectl</pre><p>4. Install Minikube: Open a WSL terminal and <a href="https://minikube.sigs.k8s.io/docs/start/">install Minikube</a> using a package manager or by downloading the binary from the official GitHub repository. You can simply use following commands.</p><pre>curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64<br>sudo install minikube-linux-amd64 /usr/local/bin/minikube</pre><p>5. Verify Minikube installation by version checking and start Minikube cluster as follows,</p><pre>minikube version<br>minikube start --driver=docker</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*BXi61vOnT4RS4IXjaeDgeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*ZQajIGQqGamieEbPIkkrzg.png" /></figure><p>6. Verify Cluster Status: After a successful startup, you can verify the status of your cluster as:</p><pre>minikube status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*oTxO9ec0718vY9LDVdbpYA.png" /></figure><p><strong>Deploying a Dask Cluster on Kubernetes within WSL</strong></p><p>With our Minikube Kubernetes cluster up and running within the WSL environment, we can proceed to deploy a Dask cluster onto this infrastructure.</p><p><strong>Understanding Dask</strong></p><p>Dask is a Python library that allows parallel and distributed computing. It enables us to scale our computations from a single machine to a cluster of machines, making it suitable for processing large datasets and complex computations.</p><p><strong>Deploying Dask on Kubernetes within WSL</strong></p><p>There are two primary methods for running a Kubernetes cluster: the classic approach and the operator method. However, it’s important to note that the classic approach is becoming deprecated. Therefore, for the purposes of this guide, I recommend opting for the operator-based approach.</p><p>To employ the Dask operator, the initial step involves installing a custom resource definition (CRD). This task can be accomplished through Helm, the package manager, following these steps:</p><ol><li>Install Helm: Helm is a package manager for Kubernetes applications. We’ll use it to deploy Dask using pre-configured Helm charts. Install Helm within your WSL environment according to the <a href="https://helm.sh/docs/intro/install/">official documentation</a> for Linux.</li><li>Add Dask Helm Repository: Add the Dask Helm repository to your Helm configuration within the WSL terminal:</li></ol><pre>helm install --repo https://helm.dask.org --create-namespace -n dask-operator --generate-name dask-kubernetes-operator</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*0A1EllDKVB7DalazCNRVRw.png" /></figure><p><strong>Verifying the Kubernetes Cluster</strong></p><p>Before proceeding further, let’s perform a quick check to ensure that our Kubernetes cluster is set up successfully. You can run the following Python code snippet within your preferred Python/Jupyter environment:</p><p>Verify dask-operator is running as follows.</p><pre>kubectl get pods -A</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*GQ9ynlMvlqNjxOeJYYNY0w.png" /></figure><p>Then execute the following code in jupyter environment where we need to install dask and dask-kubernetes.</p><pre>from dask_kubernetes.operator import KubeCluster<br>cluster = KubeCluster(name=&quot;daskmlcluster&quot;,<br> image=&#39;ghcr.io/dask/dask:latest&#39;,<br> n_workers=2,<br> resources={&quot;requests&quot;: {&quot;memory&quot;: &quot;0.5Gi&quot;}, &quot;limits&quot;: {&quot;memory&quot;: &quot;1.5Gi&quot;}},<br> env={&quot;FOO&quot; : &quot;barr&quot;}<br> )<br>cluster</pre><p>Let’s check again the details of pods, as shown in this figure we can observer mycluster-scheduler, and 2 workers under default namespace which ensures the dask Kubernetes cluster is running successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*-FLlpj0W7ztQpKaTldaCag.png" /></figure><p>Great! now we have completed deploying a Dask Cluster on Kubernetes using Minikube on WSL</p><p><strong>Conclusion</strong></p><p>In this article, we’ve explored the process of deploying a Dask cluster on top of a Kubernetes cluster using the operator method, utilizing Minikube within the Windows Subsystem for Linux (WSL) environment. By combining the strengths of Kubernetes’ container orchestration capabilities with Dask’s parallel computing functionalities, we’ve created a powerful setup for processing large datasets and complex computations. This deployment allows us to harness the benefits of distributed computing within a seamless Linux environment on a Windows machine, without the complexities of managing the underlying infrastructure. As you delve deeper into the world of Kubernetes and Dask, you’ll find endless possibilities for optimizing your data processing workflows.</p><p><strong>Visit </strong><a href="https://www.axiatadigitallabs.com/"><strong>Axiata Digital Labs</strong></a><strong> to find out more about our products and services.</strong></p><figure><img alt="https://www.axiatadigitallabs.com/" src="https://cdn-images-1.medium.com/max/376/1*-WXvF8AtCSJ70lg8Zp1MMQ.png" /><figcaption><a href="https://www.axiatadigitallabs.com/"><em>.</em></a></figcaption></figure><p><strong>References</strong></p><ol><li><a href="https://kubernetes.dask.org/">https://kubernetes.dask.org/</a></li><li><a href="https://docs.dask.org/en/stable/install.html">https://docs.dask.org/en/stable/install.html</a></li><li><a href="https://minikube.sigs.k8s.io/docs/start/">https://minikube.sigs.k8s.io/docs/start/</a></li><li><a href="https://docs.docker.com/desktop/install/windows-install/">https://docs.docker.com/desktop/install/windows-install/</a></li><li><a href="https://helm.sh/docs/intro/install/">https://helm.sh/docs/intro/install/</a></li><li><a href="https://learn.microsoft.com/en-us/windows/wsl/install">https://learn.microsoft.com/en-us/windows/wsl/install</a></li></ol><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8155324b00e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/deploy-a-dask-cluster-on-kubernetes-using-minikube-on-wsl-f8155324b00e">Deploy a Dask Cluster on Kubernetes using Minikube on WSL — Part 1</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aerospike Evaluation on Python SDK]]></title>
            <link>https://medium.com/the-ai-analytics-corner/aerospike-evaluation-on-python-sdk-b47c32ae2f55?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/b47c32ae2f55</guid>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spring-data-aerospike]]></category>
            <category><![CDATA[data-platforms]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Suranga Nanayakkara]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 08:12:10 GMT</pubDate>
            <atom:updated>2023-08-03T08:12:10.107Z</atom:updated>
            <content:encoded><![CDATA[<h4>Wanna know a quick overview of Aerospike? Let’s see my view of it!</h4><p>On a fine morning, I got an email saying that I was assigned to evaluate Aerospike, and I researched Aerospike. I thought of sharing my experience, which I got from the Aerospike documentation, and my experience on my local PC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kRphokL-7F-0cJoDH7tlA.png" /><figcaption>Image by the author</figcaption></figure><p><strong>Advantages and What is Aerospike ❤</strong></p><p>Aerospike is a high-performance distributed NoSQL database. It provides high performance via the DRams and SSD flash storage. It’s the architecture of scaling horizontally across nodes with low latency and high throughput that attracts many real-time data solutions to Aerospike. When it comes to databases like MongoDB provides Horizontal scaling, but it should be configured Aerospike does this in an automatic way. When it comes to data models, Aerospike supports many. The main ones are key-value stores and document types, and various defined types are there, which is one of the added advantages of Aerospike. Maps, lists, and hyperlogs are some of those. When it comes to real-time applications, high availability is one of the key features, and Aerospike provides it in a guaranteed structure and supports automatic failovers with data durability guarantees as well. Finally, I saw in Aerospike that the consistency model is configurable, and it can be configured for whatever the application is based on the requirements as well.</p><p><strong>Key Features that I Saw and my evaluation of those using Python ✌</strong></p><p><strong>· Performance</strong></p><p>Aerospike provides high performance and low latency, which make it ideal for real-time data processing and fast data access.</p><p><strong>· Scalability</strong></p><p>Aerospike is designed to be highly scalable, and it can handle large volumes of data and traffic loads.</p><p><strong>· Data model</strong></p><p>The key value data model is simple and flexible; it allows you to store and retrieve data quickly and efficiently as well.</p><p><strong>· Consistency</strong></p><p>Aerospike guarantees strong consistency, ensuring that all nodes in the cluster see the same version of the data at all times.</p><p><strong>· Ease of use</strong></p><p>Designed to be easy to use and integrate with existing applications and frameworks. Frameworks like Kafka and Hadoop Scala are supported by Aerospike.</p><p><strong>· Enterprise Grade Security</strong></p><p>Aerospike also provides comprehensive security features, including encryption at rest in transit, access controls, and auditing.</p><p><strong>This is how I Tested Aerospike 😎</strong></p><p>Aerospike provides a 60-day trial access to the Aerospike Enterprise Server at this link.</p><p><a href="https://aerospike.com/get-started-aerospike-database/">https://aerospike.com/get-started-aerospike-database/</a></p><p>I tried to install the Aerospike container on my Windows Docker container, but due to some administrative privileges, I couldn’t do it. Then I tried the same with my personal laptop, which is a MacBook, and it turned out well. Since I requested the trial, I had the key file with me. So, I added that to the aerospike’s file and built the aerospike image. Finally, I run the Docker image once the Aerospike build is complete. These are the terminal codes that I used;</p><pre>FROM aerospike/aerospike-server:latest<br><br>ENV AEROSPIKE_NAMESPACE mynamespace<br>ENV AEROSPIKE_SERVICE_PORT 3000<br><br>ADD aerospike.conf /etc/aerospike/aerospike.conf<br><br>docker build -t aerospike .<br><br>docker run -d --name aerospike -p 3000:3000 aerospike</pre><p>After its run, you can see it in the docker container area with a green icon saying it’s running and it’s running on port 3000 Also, you can easily telnet and see if it’s running. Then the setup part is done. Now let’s take a look at the Python code.</p><p>Forease of the demo, I have used Jupyter Notebook as the IDE, and this is how I started.</p><pre># These are the libraries that I used<br>import pandas as pd<br>from tqdm import tqdm<br>import time<br>import random<br>import pymongo<br>import aerospike<br>import pprint<br>pp = pprint.PrettyPrinter(indent=2)<br><br># Configuration adding<br>config = {<br>    &#39;hosts&#39;: [(&#39;localhost&#39;, 3000)]<br>}<br>client = aerospike.client(config).connect()</pre><p>This is how I defined the Aerospike client, configured it, and got it connected. By default, there is no password, but you can configure a username and password for the aerospike.</p><pre># Create a test namespace and set<br>namespace = &#39;test&#39;<br>set_name = &#39;demo&#39;</pre><p>This is how I defined my namespace and the key-value store set name. And now I’m going to generate 100,000 dummy data points for this exercise.</p><pre># Generate some sample data<br>num_records = 100000<br>records = []<br>for i in range(num_records):<br>    key = (namespace, set_name, str(i))<br>    record = {<br>        &#39;name&#39;: &#39;Test user&#39;,<br>        &#39;age&#39;: 25,<br>        &#39;email&#39;: &#39;user@usereee.com&#39;<br>    }<br>    records.append((key, record))</pre><p>And then I tried to insert this data into Aerospike. It took 1 minute and 31 seconds on my local Mac to insert this data using this method.</p><pre># Write the data to Aerospike<br>start_time = time.time()<br>for key, record in tqdm(records):<br>    client.put(key, record)<br>write_time = time.time() - start_time<br>print(f&quot;Inserted {num_records} records in {write_time:.2f} seconds&quot;)</pre><p>Also, read the data from the aerospike I used this query, and it took around 0.54 seconds to read 100,000 rows of data.</p><pre># Read the data from Aerospike<br>start_time = time.time()<br>def process_record(key, metadata, record):<br>    try:<br>        print (key, metadata, record)<br>        # Process the record here<br>        pass<br>    except Exception as e:<br>        # Print the exception and continue iterating<br>        traceback.print_exc()<br>        pass<br><br>client.scan(namespace, set_name).select(&#39;name&#39;,&#39;age&#39;,&#39;email&#39;).results()<br>read_time = time.time() - start_time<br>print(f&quot;Read {num_records} records in {read_time:.2f} seconds&quot;)</pre><p>Then finally, I cleaned up the aerospike and closed the connection using the below code. Even though it took some time to insert, the data retrieval part is pretty fast locally. I’m sure that these numbers will definitely change in cloud environments Also, the Aerospike team requests servers with SSDs, so it will be an additional factor for fast data retrieval or handling and working with multiple nodes as well. But in this, I have used my local machine with a single node without any SSDs.</p><pre># Cleanup<br>for key, _ in records:<br>    client.remove(key)<br><br>client.close()</pre><p>And the next awesome thing I wanted to try out was to check how it worked compared to other NoSQL databases. So, I took MongoDB to test Aerospike, and for those who wanted to think why MongoDB is because it is also a NoSQL database that caters to the same use case but is an open-source one, in the same way, I installed a MongoDB server on my Mac through a local one. Then this is how I benchmark Aerospike and MongoDB.</p><pre># Connect to MongoDB<br>mongo_client = pymongo.MongoClient(&#39;mongodb://localhost:27017/&#39;)<br>mongo_db = mongo_client[&#39;test1&#39;]<br>mongo_coll = mongo_db[&#39;demo&#39;]<br><br># Connect to Aerospike<br>config = {<br>    &#39;hosts&#39;: [(&#39;localhost&#39;, 3000)]<br>}<br>aero_client = aerospike.client(config).connect()<br>namespace = &#39;test&#39;<br>set_name = &#39;demo&#39;</pre><p>Again, I’m defining and configuring both Aerospike and MongoDB configurations. And then I generate 100,000 records as a sample, as in the previous example in the below code.</p><pre># Generate some sample data<br>num_records = 100000<br>records = []<br>for i in range(num_records):<br>    key = (namespace, set_name, str(i))<br>    record = {<br>        &#39;name&#39;: &#39;John Doe&#39;,<br>        &#39;age&#39;: random.randint(18, 50),<br>        &#39;email&#39;: @example.com&quot;&gt;f&#39;johndoe{i}@example.com&#39;<br>    }<br>    records.append((key, record))</pre><p>First, I tried MongoDB, and it took 1.53 seconds to insert data into MongoDB. This is the code that I used.</p><pre># Insert the data into MongoDB <br>start_time = time.time()<br>mongo_coll.insert_many([{&#39;_id&#39;: str(i), &#39;data&#39;: record} for i, (_, record) in enumerate(records)])<br>write_time = time.time() - start_time<br>print (f&quot;Inserted {num_records} records to Mongo DB in {write_time:.2f} seconds&quot;)</pre><p>Then I generated key values and inserted data into the aerospike, and it took 1 minute and 60 seconds to add data. What I see here mainly is that MongoDB itself has a batch processing method, which we used as “insert_many” in Aerospike. There is also a batch processing method, but I couldn’t try that out. Anyway, in Python, a for loop is an expensive call, and it might take some time for this, in my opinion.</p><pre># Create a list of (key, record) tuples<br>records = [(str(i), {&#39;name&#39;: f&#39;name{i}&#39;, &#39;age&#39;: i}) for i in range(num_records)]<br><br># Insert the data into Aerospike<br>start_time = time.time()<br>for key, record in tqdm(records):<br>    aero_client.put((namespace, set_name, key), record)<br>    <br># client.batch_write(records)<br><br>write_time = time.time() - start_time<br>print (f&quot;Inserted {num_records} records to Aerospike in {write_time:.2f} seconds&quot;)</pre><p>So that is the benchmarking of inserting values into the database, and now we are going to look at how we benchmark the reading of data by comparing Aerospike and MongoDB. First, I tried to use MongoDB to read 100,000 records, and it took 30.70 seconds. This is my code.</p><pre># Benchmark read performance for MongoDB<br>start_time = time.time() <br>for i in range(num_records):<br>    doc = mongo_coll.find_one({&#39;_id&#39;: str(i)})<br>read_time_mongo = time.time() - start_time<br>print (f&quot;Read {num_records} records from MongoDB in {read_time_mongo:.2f} seconds&quot;)</pre><p>Then I tried the same with Aerospike, and it took 0.68 seconds to read from Aerospike.</p><pre># Benchmark read performance for Aerospike<br>start_time = time.time()<br>aero_client.scan(namespace, set_name).select(&#39;name&#39;,&#39;age&#39;,&#39;email&#39;).results()<br>read_time_aero = time.time() - start_time<br>print (f&quot;Read {num_records} records from Aerospike in {read_time_aero:.2f} seconds&quot;)</pre><p>Overall, this is the finding that I got by benchmarking these two databases.</p><pre><br>+----------------+----------------+---------------+<br>|   Operation    |   Aerospike    |    MongoDB    |<br>+----------------+----------------+---------------+<br>| Reading data   | 0.68 seconds   | 30.70 seconds |<br>| Inserting data | 110.60 seconds | 1.53 seconds  |<br>+----------------+----------------+---------------+</pre><p>Also, one of the main advantages that I learned about Aerospike is its SQL-like language.</p><p><strong>Limitations that I see from Aerospike 😢</strong></p><p>1. Data modeling complexity</p><p>Aerospike requires careful data modeling to ensure optimal performance, which can be challenging for some use cases. Because it takes some time to convert a dataset into key-value stores. To mitigate this, we can use various alternatives, as shown below.</p><p><em>a. Using AS-Loader (load the data from CSV files)</em></p><p><em>b. Python &amp; Spark Scripts</em></p><p><em>c. Using Kafka, JMS, and Pulsor connectors</em></p><p><em>d. Using partner solutions for CDC-based migration.</em></p><p>2. Limited SQL Support</p><p>Aerospike generally supports a limited subset of SQL, which may be difficult for full-featured SQL users. However, you can use the Trino/Starburst Connector to run complex queries in Aerospike. You can also call the Trino/Starburst JDBC in your Python program in order to run SQL queries (however, I would recommend the Aerospike Python client library with filter expressions). Below is a screenshot connecting Trino through DBeaver to execute complex SQL queries on Aerospike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_a4CpUM8-YgmBWFd6-EiRg.png" /></figure><p>3. No Built-in Backup and Restore method</p><p>Aerospike does not provide any built-in backup and restore functionality, This could be a limitation to ensure data durability and recoverability. However, for DR, we can use the<strong> XDR f</strong>eature of Aerospike.</p><p>4. Limited community support</p><p>It is not as widely used or supported as some other databases, which can make it more challenging to find help and resources. That’s one of the reasons that I wanted to contribute to the community by writing the article as well.</p><p>5. Database Querying tools or Database diagram tools support</p><p>Aerospike requires no join, and sets (tables) are dynamic, i.e., the column definition changes record by record. Depicting it on a data diagram is not easy. However, you can try <a href="https://dbeaver.io/">DBeaver</a> (an open-source tool) for static sets only using Aerospike JDBC connectivity. Below is a screenshot from DBeaver to display the DB diagram on Aerospike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UG37NO8RmkOu5DB3NHY1Og.png" /></figure><p>Also, you can try connecting tools like DataGrip by using the JDBC driver.</p><p>6. Distributed Nature</p><p>Its distributed architecture may need an expert to operate and manage. But it can be monitored in multiple ways.</p><p>a. Commandline interface (asadm tool)</p><p>b. Using pre-built monitoring reports on Grafana &amp; Prometheus</p><p><a href="https://apc01.safelinks.protection.outlook.com/?url=https%3A%2F%2Faerospike.com%2Fproducts%2Fmonitoring-stack%2F&amp;data=05%7C01%7Csuranga.nanayakkara%40axiatadigitallabs.com%7C3e1cb7676a46489e02f008db40867f5a%7C8fa597a5c35645628d88cbf99fc8dd45%7C0%7C0%7C638174718704093742%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=RN3P%2F91FhbuvNN5mDz8WqRHPj67OytfpGTIWnitjAPk%3D&amp;reserved=0">https://aerospike.com/products/monitoring-stack/</a></p><p>c. Aerospike Management Console → Roadmap to upgrade for monitoring &amp; observability</p><p>7. Architecture</p><p>It could be better and faster for reading and writing, but it may not be well-suited for complex data analytics and reporting. Aerospike is designed for OLTP queries with faster read/write performance and low latencies. For AI and ML, Aerospike has Spark connectors that help offload data on Spark to run the models and ingest the output back into Aerospike. It avoids OLAP queries in Aerospike directly; however, if it is required, we recommend it through the TRINO and Starburst connectors.</p><p><strong>References 👍</strong></p><p><a href="https://aerospike.com/">Aerospike Homepage</a></p><p><a href="https://apc01.safelinks.protection.outlook.com/?url=https%3A%2F%2Faerospike.com%2Fproducts%2Fconnect-for-spark%2F&amp;data=05%7C01%7Csuranga.nanayakkara%40axiatadigitallabs.com%7C3e1cb7676a46489e02f008db40867f5a%7C8fa597a5c35645628d88cbf99fc8dd45%7C0%7C0%7C638174718704093742%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=bnxJV%2F5Fze7SL0YYvBpE%2B6yqJUq2KvGgM6EWmg%2B5cTI%3D&amp;reserved=0">https://aerospike.com/products/connect-for-spark/</a></p><p><a href="https://apc01.safelinks.protection.outlook.com/?url=https%3A%2F%2Faerospike.com%2Fproducts%2Fsql%2F&amp;data=05%7C01%7Csuranga.nanayakkara%40axiatadigitallabs.com%7C3e1cb7676a46489e02f008db40867f5a%7C8fa597a5c35645628d88cbf99fc8dd45%7C0%7C0%7C638174718704093742%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&amp;sdata=xDss90nDhYu8wqkKFO9rO0X%2Bsz0s%2FT5xHXJLQTt3XY8%3D&amp;reserved=0">https://aerospike.com/products/sql/</a></p><p><strong>Disclaimer</strong>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</p><p><em>Visit </em><a href="https://www.axiatadigitallabs.com/"><em>Axiata Digital Labs</em></a><em> to find out more about our products &amp; services.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b47c32ae2f55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/aerospike-evaluation-on-python-sdk-b47c32ae2f55">Aerospike Evaluation on Python SDK</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger UI to your Python Flask API]]></title>
            <link>https://medium.com/the-ai-analytics-corner/swagger-ui-to-your-python-flask-api-9bf1c8fc0178?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/9bf1c8fc0178</guid>
            <category><![CDATA[flask-api]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-applications]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dinithi Dissanayake]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 03:06:01 GMT</pubDate>
            <atom:updated>2023-07-10T03:06:01.095Z</atom:updated>
            <content:encoded><![CDATA[<h4>Adding a visual sensation to your ML Flask application</h4><p>Flask is the go-to library for API development in Python, mostly because of its light weight and already implemented development server and debugging tool. Swagger in the other hand is a set of tools helping API developers tackle its lifecycle. Among its suite of tools, Swagger-UI gives us an interactive web UI to test the created API, similar to what we do using Postman. Some of the API gateways use the capabilities of the swagger UI to give a visual sensation of the created API to the users.</p><p>Unlike spring boot swagger UI generators there is no easy way of generating swaggers for flask-based python APIs. I have put together the use of the library <strong>flasgger </strong>to build an interactive UI for your flask application.</p><p>Let’s first create a simple flask API.</p><p><strong>Flask API for Wine Quality Prediction</strong></p><p>I have trained a simple regression model which predicts the quality of a wine when given the following features,</p><ol><li>fixed acidity</li><li>volatile acidity</li><li>citric acid</li><li>residual sugar</li><li>chlorides</li><li>free sulfur dioxide</li><li>total sulfur dioxide</li><li>density</li><li>pH</li><li>sulphates</li><li>alcohol</li></ol><p>The dataset was obtained from<a href="https://www.kaggle.com/datasets/uciml/red-wine-quality-cortez-et-al-2009"> https://www.kaggle.com/datasets/uciml/red-wine-quality-cortez-et-al-2009</a>.</p><p>Let’s create a simple API to input these parameters and receive the wine quality as the output.</p><pre>from flask import Flask, render_template, Response, jsonify, request<br>import flask <br>from flask import Flask, request, jsonify<br>from flask import Blueprint<br>from flasgger import Swagger, LazyString, LazyJSONEncoder<br>from flasgger import swag_from<br>import joblib<br>import sklearn<br>import numpy as np<br>import json<br><br>app = Flask(__name__)<br>app.json_encoder = LazyJSONEncoder<br><br>model= joblib.load(&#39;wqmodel.sav&#39;)<br>        <br>#################################################################################################################################################################################<br>@app.route(&quot;/predict&quot;,methods = [&quot;POST&quot;]) <br>def predict():<br>    data = {} # dictionary to store result <br>    data[&#39;code&#39;] = 1<br>    data_n = request.get_json()<br>    if request.method == &quot;POST&quot;:<br>        try:<br>            array= np.array(data_n[&quot;array&quot;])<br>            <br>        #for invalid data keys<br>        except KeyError:<br>            return jsonify({&quot;responseCode&quot;: &quot;2&quot;,&quot;responseDesc&quot;: &quot;Invalid data Key&quot;}), 400<br>        <br>        #if the input is empty                    <br>        if array is None:<br>            print(&quot;Array Input Failed..&quot;)<br>            data[&#39;response&#39;] = &#39;Input Reading Error: Input is Empty&#39;<br>            return jsonify({&quot;responseCode&quot;: &quot;3&quot;,&quot;responseDesc&quot;: &quot;Input Reading Error: Input is Empty&quot;}), 400<br>        <br>        #if the input array is not the required size<br>        elif len(array)!=11:<br>            print(&quot;Array Input InComplete..&quot;)<br>            data[&#39;response&#39;] = &#39;Input Reading Error: Input is Incomplete&#39;<br>            return jsonify({&quot;responseCode&quot;: &quot;3&quot;,&quot;responseDesc&quot;: &quot;Input Reading Error: Input is Incomplete&quot;}), 400 <br><br>        else:<br>            array=array.reshape(1,11)<br>            #prediction<br>            prediction = model.predict(array)<br>            data[&#39;code&#39;] = 0<br>            data[&#39;response&#39;] = &#39;Model prediction PASSED&#39;<br>            data[&#39;prediction&#39;] = prediction<br>            response={&quot;responseCode&quot;: &quot;0&quot;,&quot;responseDesc&quot;: &quot;SUCCESS&quot;,&quot;Wine Quality&quot;: prediction[0]}       <br>            return jsonify(response),200<br>               <br>    else:<br>        return jsonify({&quot;responseCode&quot;: &quot;1&quot;,&quot;responseDesc&quot;: &quot;Method Not Allowed&quot;}), 405<br><br>if __name__ == &#39;__main__&#39;:<br>    print((&quot;* Loading model and Flask starting server...&quot;<br>                &quot;please wait until server has fully started&quot;)) <br>    app.run(host=&#39;0.0.0.0&#39;, threaded=True, port=8085 , debug=False)</pre><p>I have trained a simple Elastic Net model to predict the wine quality and when this app receives the following POST request it will give the wine quality prediction as depicted below.</p><pre>curl --location &#39;http://localhost:5000/predict&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>    &quot;array&quot;: [7, 0.27, 0.36, 20.7, 0.045, 45, 170, 1.001, 3, 0.45, 6]<br>}&#39;</pre><pre>{<br>    &quot;Wine Quality&quot;: 4.939022628389594,<br>    &quot;responseCode&quot;: &quot;0&quot;,<br>    &quot;responseDesc&quot;: &quot;SUCCESS&quot;<br>}</pre><p>You can easily check the functioning with the aid of any API platform like Postman. Now I will show how you can create a swagger UI for inbuilt testing of this flask API without the need of any external platform.</p><p><strong>Building the swagger UI</strong></p><p>When using flasgger we should add the API specification as yaml either in the same python script or using an externel yaml file. I have used a separate yaml file since it is easy to debug and does not clutter the API file.</p><p>The separate yaml file(located at ../docs/predict.yaml) is as follows.</p><pre>description: &quot;This API will be used to predict the class of the uploaded image&quot;<br>tags:<br>  - name: Predict the Wine Quality<br>consumes:<br>  - application/json<br>produces:<br>  - application/json<br>parameters:<br>  - description: &quot;The body should contain the array containing the 11 input parameters in the order of: <br>  fixed acidity, volatile acidity, citric acid, residual sugar, chlorides, free sulfur dioxide, total sulfur dioxide, <br>  density, ph, sulphates, alcohol&quot;<br>    in: &quot;body&quot;<br>    name: &quot;body&quot;<br>    schema:<br>      title: predict<br>      type: object<br>      properties:<br>        array:<br>          type: array<br>          description: Input Array<br>      example:<br>        array : [7, 0.27, 0.36, 20.7, 0.045, 45, 170, 1.001, 3, 0.45, 6]<br>    required: true<br>responses:<br>    &quot;200&quot;:<br>      description: Successful response<br>      schema:<br>        title: Valid Prediction Response<br>        type: object<br>        example:<br>          Wine Quality: 4.939022628389594<br>          responseCode: 0<br>          responseDesc: SUCCESS<br>    &quot;400&quot;:<br>      description: Bad request<br>      schema:<br>        title: Invalid data Key<br>        type: object<br>        example:<br>          responseCode: 2<br>          responseDesc: Invalid data Key<br>    &quot;401&quot;:<br>      description: Bad request<br>      schema:<br>        title: Input is not an array of size 11<br>        type: object<br>        example:<br>          responseCode: 3<br>          responseDesc: &quot;Input Reading Error: Input is Incomplete&quot;<br>  <br>    &quot;405&quot;:<br>      description: Method Not Allowed<br>      schema:<br>        title: Method Not Allowed<br>        type: object<br>        example:<br>          responseCode: 1<br>          responseDesc: Method Not Allowed</pre><p>You should create a yaml file for each of the endpoints(routes) in your API, including what the endpoint consumes and produces. You can include examples so that the swagger UI will give you the chance to try it out. More descriptive you are in creating the yaml file, more appealing and descriptive your UI will be.</p><p>After creating your yaml file your python script should include additional swagger configurations. I will give you a basic example, so that you can edit the information to suit your need.</p><pre>from flask import Flask, render_template, Response, jsonify, request<br>import flask <br>from flask import Flask, request, jsonify<br>from flask import Blueprint<br>from flasgger import Swagger, LazyString, LazyJSONEncoder<br>from flasgger import swag_from<br>import joblib<br>import sklearn<br>import numpy as np<br>import json<br><br>app = Flask(__name__)<br>app.json_encoder = LazyJSONEncoder<br><br>swagger_template ={<br>    &quot;swagger&quot;: &quot;2.0&quot;,<br>    &quot;info&quot;: {<br>      &quot;title&quot;: &quot;Wine Quality Prediction&quot;,<br>      &quot;description&quot;: &quot;API Documentation for Wine Quality Prediction&quot;,<br>      &quot;contact&quot;: {<br>        &quot;name&quot;: &quot;Admin&quot;,<br>        &quot;email&quot;: &quot;dinithi@axiatadigitallabs.com&quot;,<br>        &quot;url&quot;: &quot;http://www.axiatadigitallabs.com&quot;,<br>        },<br>      &quot;termsOfService&quot;: &quot;Terms of services&quot;,<br>      &quot;version&quot;: &quot;1.0&quot;,<br>      &quot;host&quot;:&quot;Wine_Quality_Prediction&quot;,<br>      &quot;basePath&quot;:&quot;http://localhost:5000&quot;,<br>      &quot;license&quot;:{<br>        &quot;name&quot;:&quot;License of API&quot;,<br>        &quot;url&quot;:&quot;API license URL&quot;<br>      }<br>              },<br>    &quot;schemes&quot;: [<br>        &quot;http&quot;,<br>        &quot;https&quot;<br>    ],<br>      }<br><br>swagger_config = {<br>    &quot;headers&quot;: [<br>        (&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;),<br>        (&#39;Access-Control-Allow-Methods&#39;, &quot;GET, POST&quot;),<br>    ],<br>    &quot;specs&quot;: [<br>        {<br>            &quot;endpoint&quot;: &#39;Wine_Quality_Prediction&#39;,<br>            &quot;route&quot;: &#39;/Wine_Quality_Prediction.json&#39;,<br>            &quot;rule_filter&quot;: lambda rule: True,<br>            &quot;model_filter&quot;: lambda tag: True,<br>        }<br>    ],<br>    &quot;static_url_path&quot;: &quot;/flasgger_static&quot;,<br>    &quot;swagger_ui&quot;: True,<br>    &quot;specs_route&quot;: &quot;/apidocs/&quot;,<br>    <br>}<br>swagger = Swagger(app, template=swagger_template,config=swagger_config)<br><br>model= joblib.load(&#39;wqmodel.sav&#39;)<br><br>#################################################################################################################################################################################<br>@swag_from(&quot;docs/predict.yaml&quot; )<br>@app.route(&quot;/predict&quot;,methods = [&quot;POST&quot;]) <br>def predict():<br>    data = {} # dictionary to store result <br>    data[&#39;code&#39;] = 1<br>    data_n = request.get_json()<br>    if request.method == &quot;POST&quot;:<br>        try:<br>            array= np.array(data_n[&quot;array&quot;])<br>            <br>        except KeyError:<br>            return jsonify({&quot;responseCode&quot;: &quot;2&quot;,&quot;responseDesc&quot;: &quot;Invalid data Key&quot;}), 400<br>                        <br>        if len(array)!=11:<br>            print(&quot;Array Input InComplete..&quot;)<br>            data[&#39;response&#39;] = &#39;Input Reading Error: Input is Incomplete&#39;<br>            return jsonify({&quot;responseCode&quot;: &quot;3&quot;,&quot;responseDesc&quot;: &quot;Input Reading Error: Input is Incomplete&quot;}), 401<br><br>        else:<br>            array=array.reshape(1,11)<br>            prediction = model.predict(array)<br>            data[&#39;code&#39;] = 0<br>            data[&#39;response&#39;] = &#39;Model prediction PASSED&#39;<br>            data[&#39;prediction&#39;] = prediction<br>            response={&quot;responseCode&quot;: &quot;0&quot;,&quot;responseDesc&quot;: &quot;SUCCESS&quot;,&quot;Wine Quality&quot;: prediction[0]}       <br>            return jsonify(response),200<br>               <br>    else:<br>        return jsonify({&quot;responseCode&quot;: &quot;1&quot;,&quot;responseDesc&quot;: &quot;Method Not Allowed&quot;}), 405<br><br>if __name__ == &#39;__main__&#39;:<br>    print((&quot;* Loading model and Flask starting server...&quot;<br>                &quot;please wait until server has fully started&quot;)) <br>    app.run(host=&#39;0.0.0.0&#39;, threaded=True, port=8085 , debug=False)</pre><p>You can access your swagger UI at you “base path” + “specs route” mentioned in the script. My one would be, <a href="http://localhost:5000/apidocs/">http://localhost:5000/apidocs/</a>. The following figure depicts the UI you can visit using the above link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVXWQ4x-4mqN8NU7jpTdFw.png" /><figcaption>Swagger UI</figcaption></figure><p>When you click on top of the /predict widget it collapses and shows your specifications to the extent you mentioned in the yaml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*IO-ReTsPjcQ4QOj_6dY97w.png" /><figcaption>Swagger UI Expanded</figcaption></figure><p>Let’s try out the predict endpoint!</p><p>Once you click the<strong> try it out </strong>button you will get the example in an editable area, and you can edit and execute it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*hnXEH9-KqILrCD5Ae6xCYA.png" /><figcaption>Trying out the predict API</figcaption></figure><p>The UI outputs the wine quality successfully.</p><p>You can receive the documentation for this API at <a href="http://localhost:5000/Wine_Quality_Prediction.json">http://localhost:5000/Wine_Quality_Prediction.json</a> , same as we specified in the swagger template.</p><p>It is possible to include security features, auth tokens, and any type of input and output data differing to the ones we used here. Hope this helps you to figure out an easy way to document and build a UI to test your python flask API.</p><p><strong>References</strong></p><ol><li><a href="https://pypi.org/project/flasgger/">flasgger · PyPI</a></li></ol><p><a href="https://www.kaggle.com/datasets/uciml/red-wine-quality-cortez-et-al-2009">2. https://medium.com/r/?url=https%3A%2F%2Fwww.kaggle.com%2Fdatasets%2Fuciml%2Fred-wine-quality-cortez-et-al-2009</a></p><p>3. <a href="https://swagger.io/">API Documentation &amp; Design Tools for Teams | Swagger</a></p><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused byanyofthearticlesto internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bf1c8fc0178" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/swagger-ui-to-your-python-flask-api-9bf1c8fc0178">Swagger UI to your Python Flask API</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Power of Language Models: The Climax of Deep Learning - Part 02]]></title>
            <link>https://medium.com/the-ai-analytics-corner/demystifying-chatgpt-part-01-the-history-of-llm-nlp-53d6084758e8?source=rss----871d9f25b75c---4</link>
            <guid isPermaLink="false">https://medium.com/p/53d6084758e8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Isuru Alagiyawanna]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 03:02:18 GMT</pubDate>
            <atom:updated>2023-10-09T09:26:47.558Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s Recap the History</h4><p>Convolutional Neural Networks (CNNs) have their roots in the field of computer vision, dating back to the 1980s. The first successful application of CNNs to computer vision was the LeNet-5 architecture, developed by Yann LeCun et al. in 1998. This architecture used a series of convolutional layers followed by fully connected layers to classify handwritten digits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*b7bK6FY_kCIN9Kzf6DlP-g.png" /><figcaption>LeNet-5 Architecture</figcaption></figure><p>In the years that followed, CNNs continued to be refined and applied to a wide range of computer vision tasks, including object detection, image segmentation, and facial recognition. In 2012, a team of researchers led by Alex Krizhevsky achieved a breakthrough in image classification by using a deep CNN architecture, called AlexNet, to win the ImageNet Large Scale Visual Recognition Challenge.</p><h3>The birth of Recurrent Neural Networks (RNNs)</h3><p>In the late 1990s, a new type of RNN called Long Short-Term Memory (LSTM) was introduced by Hochreiter and Schmidhuber. LSTMs addressed the vanishing gradient problem by using a gating mechanism to control the flow of information through the network, allowing it to selectively remember or forget information from previous timesteps.</p><p>While CNNs have been highly successful in the domain of computer vision, they are not well-suited for processing text data. The reason for this is that text data is inherently sequential, with each word or character depending on the ones that came before it. CNNs, on the other hand, are designed to operate on fixed-size inputs and are not naturally suited for processing variable-length sequences.</p><p>To process text data, researchers have instead turned to RNNs and their variants, such as LSTMs and Gated Recurrent Units (GRUs). These models are designed to handle sequential data and are able to capture long-term dependencies in the data, making them well-suited for a wide range of natural language processing tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*w80AHYzJtKUkMWSXeyxBxw.png" /><figcaption>Vanilla RNN vs LSTM vs GRU</figcaption></figure><h3>The Big Picture</h3><p>The following Image Indicates the major landmarks and the introduced architectures in each of the phases. Now we saw the Birth of RNNs and Next we going to look around the Game Changer of entire deep-learning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAAgPaLKl3I5yS3OpN30kQ.png" /><figcaption>The Major History of NLP / LLM</figcaption></figure><h3>The Man, The Myth, The Legend, The Transformers</h3><p>The Transformer architecture was introduced as a solution to some of the limitations of traditional sequence-to-sequence (Seq2Seq) models in natural language processing (NLP). Seq2Seq models are a class of neural networks that are used to map variable-length input sequences to variable-length output sequences. They consist of two components: an encoder that processes the input sequence and a decoder that generates the output sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*fyW9gVk86JHHQ-f0i9JmuA.png" /><figcaption>Seq2Seq Architecture for NMT</figcaption></figure><p>One of the most popular applications of Seq2Seq models is neural machine translation (NMT). NMT systems using Seq2Seq models were able to achieve impressive results in translating text from one language to another. However, these models had some limitations that made them less effective for certain types of translation tasks.</p><p>One of the main limitations of Seq2Seq models is that they rely on fixed-length vectors to represent the input and output sequences. This can be a problem when dealing with long sequences, as it can be difficult to capture all of the relevant information in a single vector. In addition, Seq2Seq models have difficulty handling long-term dependencies between the input and output sequences, which can result in translations that are overly literal or contain grammatical errors.</p><p>The Transformer architecture was introduced as a solution to these limitations. The key innovation in the Transformer architecture is the self-attention mechanism, which allows the model to weigh the importance of different parts of the input sequence when making predictions. This mechanism enables the model to capture long-range dependencies and make better use of contextual information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*oSnp7Pgb-bNPh0R7xAigyQ.png" /><figcaption>The Transformers Architecture</figcaption></figure><p>When applied to NMT, the Transformer architecture achieved significant improvements over Seq2Seq models. This was due in part to the self-attention mechanism, which allowed the model to better capture the context of each word in the input sentence. The Transformer also introduced a novel technique called positional encoding, which allows the model to encode the position of each word in the input sequence, further improving its ability to capture long-range dependencies.</p><p>Overall, while Seq2Seq models were successful in many NLP tasks, they were not well-suited for neural machine translation, particularly for longer sequences. The Transformer architecture addressed many of the limitations of Seq2Seq models and enabled significant improvements in NMT performance.</p><p>In the next part, we are going to see the Transformer Architecture in more detail and different Transformer variants including BERT, and T5.</p><p>Check my <a href="https://www.linkedin.com/in/isuru-alagiyawanna-536881121/">LinkedIn</a> for Insightful details about LLMs and Generative AI.</p><p><strong><em>Disclaimer</em></strong><em>: ADL is not responsible for any damage caused by any of the articles to any internal or external parties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53d6084758e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-ai-analytics-corner/demystifying-chatgpt-part-01-the-history-of-llm-nlp-53d6084758e8">Unleashing the Power of Language Models: The Climax of Deep Learning - Part 02</a> was originally published in <a href="https://medium.com/the-ai-analytics-corner">ADL AI &amp; Analytics Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>