<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jonathan Bogerd on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Bogerd on Medium]]></description>
        <link>https://medium.com/@jonathanbogerd?source=rss-3863776b2716------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*16ecuQumJiH06Z8McXHNtQ.png</url>
            <title>Stories by Jonathan Bogerd on Medium</title>
            <link>https://medium.com/@jonathanbogerd?source=rss-3863776b2716------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:53:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathanbogerd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[End-to-End Machine Learning in Azure]]></title>
            <link>https://medium.com/data-science/end-to-end-machine-learning-in-azure-1429528ecbe5?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/1429528ecbe5</guid>
            <category><![CDATA[azure-synapse-analytics]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 19:35:49 GMT</pubDate>
            <atom:updated>2024-02-20T19:35:49.051Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to train and deploy a machine learning model in Azure</h4><h4><strong>Introduction</strong></h4><p>In this article, we will go through an end-to-end example of a machine learning use case in Azure. We will discuss how to transform the data such that we can use it to train a model using Azure Synapse Analytics. Then we will train a model in Azure Machine Learning and score some test data with it. The purpose of this article is to give you an overview of what techniques and tools you need in Azure to do this and to show exactly how you do this. In researching this article, I found many conflicting code snippets of which most are outdated and contain bugs. Therefore, I hope this article gives you a good overview of techniques and tooling and a set of code snippets that help you to quickly start your machine learning journey in Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*No1UsP3fsA5Sm0eL" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Data and Objective</strong></h4><p>To build a Machine Learning example for this article, we need data. We will use a dataset I created on ice cream sales for every state in the US from 2017 to 2022. This dataset can be found <a href="https://github.com/jonathanbogerd/icecreamdata">here</a>. You are free to use it for your own machine learning test projects. The objective is to train a model to forecast the number of ice creams sold on a given day in a state. To achieve this goal, we will combine this dataset with population data from each state, sourced from <a href="https://usafacts.org/data/topics/people-society/population-and-demographics/population-data/population/">USAFacts</a>. It is shared under a Creative Commons license, which can be found <a href="https://usafacts.org/faq/">here</a>.</p><p>To build a machine learning model, several data transformation steps are required. First, data formats need to be aligned and both data sets have to be combined. We will perform these steps in Azure Synapse Analytics in the next section. Then we will split the data into train and test data to train and evaluate the machine learning model.</p><h4><strong>Azure</strong></h4><p>Microsoft Azure is a suite of cloud computing services offered by Microsoft to build and manage applications in the cloud. It includes many different services, including storage, computing, and analytics services. Specifically for machine learning, Azure provides a Machine Learning Service which we will use in this article. Next to that, Azure also contains Azure Synapse Analytics, a tool for data orchestration, storage, and transformation. Therefore, a typical machine learning workflow in Azure uses Synapse to retrieve, store, and transform data and to call the model for inference and uses Azure Machine Learning to train, save, and deploy machine learning models. This workflow will be demonstrated in this article.</p><h4><strong>Synapse</strong></h4><p>As already mentioned, Azure Synapse Analytics is a tool for data pipelines and storage. I assume you have already created a Synapse workspace and a Spark cluster. Details on how to do this can be found <a href="https://learn.microsoft.com/en-us/azure/synapse-analytics/get-started-create-workspace">here</a>.</p><p>Before making any transformation on the data, we first have to upload it to the storage account of Azure Synapse. Then, we create integration datasets for both source datasets. Integration datasets are references to your dataset and can be used in other activities. Let’s also create two integration datasets for the data when the transformations are done, such that we can use them as storage locations after transforming the data.</p><p>Now we can start transforming the data. We will use two steps for this: The first step is to clean both datasets and save the cleaned versions, and the second step is to combine both datasets into one. This setup follows the standard bronze, silver, and gold procedure.</p><h4><strong>Data Flow</strong></h4><p>For the first step, we will use Azure Data Flow. Data Flow is a no-code option for data transformations in Synapse. You can find it under the Develop tab. There, create a data flow Icecream with the source integration dataset of the ice cream data as a source and the sink integration data set as a sink. The only transformation we will do here is to create the date column with the standard toDate function. This casts the date to the correct format. In the sink data set, you can also rename columns under the mapping tab.</p><p>For the population data set, we will rename some columns and unpivot the columns. Note that you can do all this without writing code, making it an easy solution for quick data transformation and cleaning.</p><h4><strong>Spark</strong></h4><p>Now, we will use a Spark notebook to join the two datasets and save the result to be used by Azure Machine Learning. Notebooks can be used in several programming languages, all use the Spark API. In this example, we will use PySpark, the Python API for Spark as it is complete. After reading the file, we join the population data per year on the ice creamdata, split it into a train and test data set, and write the result to our storage account. The details can be found in the script below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3a22f770da716f3c3d3bf83f803f85c/href">https://medium.com/media/f3a22f770da716f3c3d3bf83f803f85c/href</a></iframe><p>Note that for using AutoML in Machine Learning, it is required to save the data sets as mltable format instead of parquet files. To do this, you can convert the parquets using the provided code snippet. You might need to authenticate with your Microsoft account in order to run this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e66995faf6468b8211473c956765181/href">https://medium.com/media/7e66995faf6468b8211473c956765181/href</a></iframe><h4><strong>Pipelines</strong></h4><p>Now that we have created all activities, we have to create a pipeline to run these activities. Pipelines in Synapse are used to execute activities in a specified order and trigger. This makes it possible to retrieve data for instance daily or to retrain your model automatically every month. Let’s create a pipeline with three activities, two dataflow activities, and a Notebook activity. The result should be something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*rTnIgdVcjeNoki4KWuVlww.png" /><figcaption>Image by Author</figcaption></figure><h4><strong>Machine Learning</strong></h4><p>Azure Machine Learning (AML) is a tool that enables the training, testing, and deploying of machine learning models. The tool has a UI in which you can run machine learning workloads without programming. However, it is often more convenient to build and train models using the Python SDK (v2). It allows for more control and allows you to work in your favorite programming environment. So, let’s first install all packages required to do this. You can simply pip install this requirements.txt file to follow along with this example. Note that we will use lightgbm to create a model. You do not need this package if you are going to use a different model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02122a9899bc549a57292183cc374b5d/href">https://medium.com/media/02122a9899bc549a57292183cc374b5d/href</a></iframe><p>Now let’s start using the Python SDK to train a model. First, we have to authenticate to Azure Machine Learning using either the default or interactive credential class to get an MLClient. This will lazily authenticate to AML, whenever you need access to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8763f9c0d6d1e24cbbfe53057ebe668/href">https://medium.com/media/d8763f9c0d6d1e24cbbfe53057ebe668/href</a></iframe><h4><strong>Compute</strong></h4><p>The next step is to create a compute, something to run the actual workload. AML has several types of compute you can use. Compute instances are well suited as a development environment or for training runs. Compute clusters are for larger training runs or inference. We will create both a compute instance and a compute cluster in this article: the first for training, and the second for inferencing. The code to create a compute instance can be found below, the compute cluster will be created when we deploy a model to an endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00618443c9aba47c752559530da44fee/href">https://medium.com/media/00618443c9aba47c752559530da44fee/href</a></iframe><p>It is also possible to use external clusters from for instance Databricks or Synapse. However, currently, Spark clusters from Synapse do not run a supported version for Azure Machine Learning. More information on clusters can be found <a href="https://learn.microsoft.com/en-us/azure/machine-learning/concept-compute-target?view=azureml-api-2">here</a>.</p><h4><strong>Environment</strong></h4><p>Training Machine Learning models on different machines can be challenging if you do not have a proper environment setup to run them. It is easy to miss a few dependencies or have slightly different versions. To solve this, AML uses the concept of a Environment, a Docker-backed Python environment to run your workloads. You can use existing Environments or create your own by selecting a Docker base image (or creating one yourself) and adding a conda.yaml file with all dependencies. For this article, we will create our environment from a Microsoft base image. The conda.yaml file and code to create an environment are provided.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c968499b23abe3274480b1d1560c78e/href">https://medium.com/media/7c968499b23abe3274480b1d1560c78e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35eeaafb97389cfde5426f4db7150be4/href">https://medium.com/media/35eeaafb97389cfde5426f4db7150be4/href</a></iframe><p>Do not forget to include the azureml-inference-server-http package. You do not need it to train a model, however it is required for inferencing. If you forget it now, you will get errors during scoring and you have to start from here again. In the AML UI, you can inspect the progress and the underlying Docker image. Environments are also versioned, such that you can always revert to the previous version if required.</p><h4><strong>Data</strong></h4><p>Now that we have an environment to run our machine learning workload, we need access to our dataset. In AML there are several ways to add data to the training run. We will use the option to register our training dataset before using it to train a model. In this way, we again have versioning of our data. Doing this is quite straightforward by using the following script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5328f45c4ee656a9b58704d7a5abbe9a/href">https://medium.com/media/5328f45c4ee656a9b58704d7a5abbe9a/href</a></iframe><h4><strong>Training</strong></h4><p>Finally, we can start building the training script for our lightgbm model. In AML, this training script runs in a command with all the required parameters. So, let’s set up the structure of this training script first. We will use MLFlow for logging, saving and packaging of the model. The main advantage of using MLFlow, is that all dependencies will be packaged in the model file. Therefore, when deploying, we do not need to specify any dependencies as they are part of the model. Following an example script for an MLFlow model provided by Microsoft, this is the basic structure of a training script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903924c8ec64593db0cc140c70f8acce/href">https://medium.com/media/903924c8ec64593db0cc140c70f8acce/href</a></iframe><p>Filling in this template, we start with adding the parameters of the lightgbm model. This includes the number of leaves and the number of iterations and we parse them in the parse_args method. Then we will read the provided parquet file in the data set that we registered above. For this example, we will drop the date and state columns, although you can use them to improve your model. Then we will create and train the model using a part of the data as our validation set. In the end, we save the model such that we can use it later to deploy it in AML. The full script can be found below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/822bb7d76e034728a6267085bfeba2d3/href">https://medium.com/media/822bb7d76e034728a6267085bfeba2d3/href</a></iframe><p>Now we have to upload this script to AML together with the dataset reference, environment, and the compute to use. In AML, this is done by creating a command with all these components and sending it to AML.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/727d98e277961f6d75eaa474d45d4173/href">https://medium.com/media/727d98e277961f6d75eaa474d45d4173/href</a></iframe><p>This will yield a URL to the training job. You can follow the status of training and the logging in the AML UI. Note that the cluster will not always start on its own. This at least happened to me sometimes. In that case, you can just manually start the compute instance via the UI. Training this model will take roughly a minute.</p><h4><strong>Endpoints</strong></h4><p>To use the model, we first need to create an endpoint for it. AML has two different types of endpoints. One, called an online endpoint is used for real-time inferencing. The other type is a batch endpoint, used for scoring batches of data. In this article, we will deploy the same model both to an online and a batch endpoint. To do this, we first need to create the endpoints. The code for creating an online endpoint is quite simple. This yields the following code for creating the endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83ff8cb96329ab8a11874bd52980d7ba/href">https://medium.com/media/83ff8cb96329ab8a11874bd52980d7ba/href</a></iframe><p>We only need a small change to create the batch endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89878fe1eab7a577b4398afabc801214/href">https://medium.com/media/89878fe1eab7a577b4398afabc801214/href</a></iframe><h4><strong>Deployment</strong></h4><p>Now that we have an endpoint, we need to deploy the model to this endpoint. Because we created an MLFlow model, the deployment is easier, because all requirements are packaged inside the model. The model needs to run on a compute cluster, we can create one while deploying the model to the endpoint. Deploying the model to the online endpoint will take roughly ten minutes. After the deployment, all traffic needs to be pointed to this deployment. This is done in the last lines of this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/090354aad75dfd25a63bc96a651a7637/href">https://medium.com/media/090354aad75dfd25a63bc96a651a7637/href</a></iframe><p>To deploy the same model to the batch endpoint, we first need to create a compute target. This target is then used to run the model on. Next, we create a deployment with deployment settings. In these settings, you can specify the batch size, concurrency settings, and the location for the output. After you have specified this, the steps are similar to deployment to an online endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/811c74c664fe04624ca43798ebf1c00b/href">https://medium.com/media/811c74c664fe04624ca43798ebf1c00b/href</a></iframe><h4><strong>Scoring with the Online Endpoint</strong></h4><p>Everything is now ready to use our model via the endpoints. Let’s first consume the model from the online endpoint. AML provides a sample scoring script that you can find in the endpoint section. However, creating the right format for the sample data can be slightly frustrating. The data needs to be sent in a nested JSON with the column indices, the indices of the sample, and the actual data. You can find a quick and dirty approach to do this in the example below. After you encode the data, you have to send it to the URL of the endpoint with the API key. You can find both in the endpoint menu. Note that you should <strong>never </strong>save the API key of your endpoint in your code. Azure provides a Key vault to save secrets. You can then reference the secret in your code to avoid saving it there directly. For more information see this link to the <a href="https://learn.microsoft.com/en-us/azure/key-vault/general/overview">Microsoft documentation</a>. The result variable will contain the predictions of your model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e4fd238dc66ad8f6135be48a6df2f08/href">https://medium.com/media/3e4fd238dc66ad8f6135be48a6df2f08/href</a></iframe><h4><strong>Scoring with the Batch Endpoint</strong></h4><p>Scoring data via the batch endpoint works a bit differently. Typically, it involves more data, therefore it can be useful to register a dataset for this in AML. We have done this before in this article for the training data. We will then create a scoring job with all the information and send this to our endpoint. During scoring, we can review the progress of the job and poll for instance its status. After the job is completed, we can download the results from the output location that we specified when creating the batch endpoint. In this case, we saved the results in a CSV file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d46f9a00db094f7d755230ccde9ebf8/href">https://medium.com/media/1d46f9a00db094f7d755230ccde9ebf8/href</a></iframe><p>Although we scored the data and received the output locally, we can run the same code in Azure Synapse Analytics to score the data from there. However, in most cases, I find it easier to first test everything locally before running it in Synapse.</p><h4><strong>Conclusion</strong></h4><p>We have reached the end of this article. To summarize, we imported data in Azure using Azure Synapse Analytics, transformed it using Synapse, and trained and deployed a machine learning model with this data in Azure Machine Learning. Last, we scored a dataset with both endpoints. I hope this article helped create an understanding of how to use Machine Learning in Azure. If you followed along, do not forget to delete endpoints, container registries and other resources you have created to avoid incurring costs for them.</p><h4><strong>Sources</strong></h4><ul><li><a href="https://usafacts.org/data/topics/people-society/population-and-demographics/population-data/population/">US population over time</a></li><li><a href="https://github.com/Azure/azureml-examples/blob/main/sdk/python/endpoints/batch/deploy-models/heart-classifier-mlflow/mlflow-for-batch-tabular.ipynb">azureml-examples/sdk/python/endpoints/batch/deploy-models/heart-classifier-mlflow/mlflow-for-batch-tabular.ipynb at main · Azure/azureml-examples</a></li><li><a href="https://github.com/Azure/azureml-examples/blob/main/tutorials/get-started-notebooks/quickstart.ipynb">azureml-examples/tutorials/get-started-notebooks/quickstart.ipynb at main · Azure/azureml-examples</a></li></ul><p><a href="https://learn.microsoft.com/en-us/azure/machine-learning">https://learn.microsoft.com/en-us/azure/machine-learning</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1429528ecbe5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/end-to-end-machine-learning-in-azure-1429528ecbe5">End-to-End Machine Learning in Azure</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning improved sorting algorithms]]></title>
            <link>https://medium.com/data-science/deep-reinforcement-learning-improved-sorting-algorithms-2f6a1969e3af?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f6a1969e3af</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[monte-carlo-tree-search]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 14:14:56 GMT</pubDate>
            <atom:updated>2023-06-13T14:14:56.276Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Google DeepMind created a more efficient sorting algorithm</h4><p>Last week, Google DeepMind published a paper in the journal Nature in which they claimed to have found a more efficient sorting algorithm by using Deep Reinforcement Learning (DLR). DeepMind is known for pushing the boundaries in Reinforcement Learning (RL). A few years ago, they beat the best player in the game of Go with their agent AlphaGo, after using a similar program to crush existing chess engines. In 2022 DeepMind introduced AlphaTensor, a program that found a more efficient matrix multiplication algorithm with DLR. The techniques used are similar to DeepMind’s newest achievement: improving a standard sorting algorithm. In this article, I will discuss how they achieved this by introducing Reinforcement Learning, Monte Carlo Tree Search, and the details of DeepMind’s approach and agent AlphaDev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7cvxbL_usOXtnlsw" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Sorting</strong></h4><p>Writing a sorting algorithm is simple: compare all values one by one to find the lowest (or highest) value, save this value at the first element of your return list, and continue to the next value until no more value is left. Although this algorithm will work, it is far from efficient. Because sorting is very common in computer programs, efficient sorting algorithms are subject to intensive research. DeepMind focused on two variants of sorting: Fixed sorting and variable sorting. Fixed sorting involves sorting a sequence of values with a fixed, predefined length. In variable sorting, the size of the list of values is not defined in advance. Only the maximum size of the list is provided. Both variants of sorting are used extensively in state-of-the-art sorting algorithms. Often, a large list is sorted by repeatedly sorting small sections of the list.</p><p>Current state-of-the-art algorithms use so-called sorting networks in both fixed and variable sorting. In this article, I will not discuss the details of sorting networks. You can find more information <a href="https://dl.acm.org/doi/pdf/10.1145/1468075.1468121">here</a>.</p><h4><strong>Reinforcement Learning</strong></h4><p>In this section, I will introduce the main concepts of Reinforcement Learning. Reinforcement Learning is a branch of Machine Learning, in which an agent is tasked with finding the best actions in an environment, given the current state. The state of an environment contains all relevant aspects of an environment that can or should influence the action to be taken. The best action is defined as the action that maximizes the (discounted) cumulative reward. Actions are taken sequentially, and after each action, the obtained reward and the new state are recorded. Usually, an environment has some termination criteria after which the next episode starts. Early versions of RL used tables to keep track of the value of certain states and actions with the idea of always taking the action with the highest value. Deep neural networks often replace these tables because they can generalize better and enumerating all states is often impossible. When deep neural networks are used for Reinforcement Learning, the term Deep Reinforcement Learning is used.</p><h4><strong>Monte Carlo Tree Search</strong></h4><p>AlphaDev is trained using Deep Reinforcement Learning and Monte Carlo Tree Search, which is a search algorithm to find the best action given some initial state. It is often combined with DRL, for instance in AlphaZero and AlphaGo. It deserves its own article, but a summary is provided here.</p><p>Monte Carlo Tree Search (MCTS) builds a tree of possible outcome states where the current state is the root node. For a given number of simulations, this tree will be explored to find the consequences of taking certain actions. In each simulation, a rollout (sometimes called playout) is used to expand one node into child nodes if the game is not terminated at that point. Which action to take is based on selection criteria. In our case, the probability of selecting an action is given by the policy network which will be discussed below. The value of a node is a measure of how good the state of that node is. It is determined by the value network, which is also discussed in a future section. If a terminal state is reached, the value is replaced by the true reward value of the environment.</p><p>The values are propagated up the search tree. In this way, the value of the current state depends on the value of the states that can be reached from the current state.</p><h4><strong>DeepMind’s Approach</strong></h4><p>The DRL agent of DeepMind that is trained to improve the sorting algorithm implementation is called AlphaDev. The task of AlphaDev is to write a more efficient sorting algorithm in Assembly. Assembly is the bridge between high-level languages such as C++, Java, and Python and machine code. If you use sort in C++, the compiler compiles your program into assembly code. The assembler then converts this code to machine code. AlphaDev is tasked with selecting a series of assembly instructions to create a sorting algorithm that is both correct and fast. This is a difficult task because adding one instruction can make the program completely wrong, even if it was correct before.</p><p>AlphaDev finds an efficient sorting algorithm by creating and solving the AssemblyGame. In each turn, it has to select one action corresponding to a CPU instruction. By formulating this problem as a game, it can easily fit the standard Reinforcement Learning framework.</p><h4><strong>Reinforcement Learning Formulation</strong></h4><p>A standard RL formulation contains states, actions, rewards, and a termination criterium.</p><h4><strong>State</strong></h4><p>The state of the AssemblyGame consists of two parts. First, a representation of the current program. AlphaDev uses the output of a Transformer, a neural network architecture, to represent the current algorithm. Transformers have had much success with large language models recently and are a suitable choice for encoding the current algorithm because it is text-based. The second part of the state is a representation of the state of the memory and registers after running the current algorithm. This is done by a conventional deep neural network.</p><h4><strong>Action</strong></h4><p>The actions of the AssemblyGame are appending a legal assembly instruction to the program. AlphaDev can choose to append any instruction as long as it is legal. DeepMind created the following six rules for legal actions:</p><ol><li>Memory locations are always read in incremental order</li><li>Registers are allocated in incremental order</li><li>Read and write to each memory location once</li><li>No consecutive compare instructions</li><li>No comparison or conditional moves to memory</li><li>Non-initialized registers cannot be used</li></ol><p>The last two actions are illegal from a programming standpoint, the others are enforced because they will not change the program. By removing these actions the search space is limited without affecting the algorithm.</p><h4><strong>Reward</strong></h4><p>The reward of the AssemblyGame is a combination of two parts. The first element of the reward is a correctness score. Based on a series of test sequences, the provided algorithm is evaluated. The closer the algorithm gets to properly sorting the test sequence, the higher the reward for correctness. The second element of the reward is the speed or latency of the program. This is measured by the number of lines of the program, if there are no conditional branches. In practice, this means that the length of the program is used for fixed sorting because no conditions are required for that program. For variable sorting, the algorithm has to condition on the actual length of the sequence. Because not all parts of the algorithm are used when sorting, the actual latency of the program is measured instead of the number of lines.</p><h4><strong>Termination and Goal</strong></h4><p>According to the paper released by DeepMind, they terminate the AssemblyGame after “a limited number of steps”. What this exactly means is unclear, but I assume they limit the number of steps based on the current human benchmark. The goal of the game is to find a correct and fast algorithm. If either an incorrect or a slow algorithm is provided by AlphaDev, the game is lost.</p><h4><strong>Policy and Value Networks</strong></h4><p>To use Monte Carlo Tree Search a policy and a value network are required. The policy network sets the probability for each action and the value network is trained to evaluate a state. The policy network is updated based on the number of visits of a certain state. This creates an iterative procedure, where the policy is used to perform MCTS and the policy network is updated with the number of visits of a state in MCTS.</p><p>The value network outputs two values, one for the correctness of the algorithm and one for the latency of the algorithm. According to DeepMind, this yields better results than combining these values in one score by the network. The value network is updated based on the obtained rewards.</p><h4><strong>Results</strong></h4><p>After training AlphaDev, it found shorter algorithms for fixed sorting with sequence lengths 3 and 5. For fixed sorting with length 4, it found the current implementation, so no improvement was made there. AlphaDev achieved these results for fixed sorting by applying two new ideas. These new ideas, called the swap and the copy move, result in fewer comparisons between values and therefore a faster algorithm. For fixed sorting with length 3, DeepMind proved that no shorter program exists by brute forcing through all options with a shorter program length. For longer programs, this approach is infeasible, as the search space grows exponentially.</p><p>For variable sorting, AlphaDev came up with a new design of the algorithm. For instance for variable sorting a sequence with a length at most 4, AlphaDev suggested to first sort 3 values and then perform a simplified version of sort for the last remaining element. The figure below shows the algorithm design for Varsort(4) given by AlphaDev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*HRG9YjZnHazlOEUX-2SU6w.png" /><figcaption>Image by D. Mankowitz et al. , Faster sorting algorithms discovered using deep reinforcement learning (2023), Nature</figcaption></figure><p>Overall, faster algorithms were found for fixed and variable sorting, proving that DRL can be used to implement efficient algorithms. The sorting implementation in C++ has been updated to use these new algorithms. Details on the performance gains achieved by AlphaDev can be found in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*vDRogvQNDzgGs7sPjLrKWg.png" /><figcaption>Table by D. Mankowitz et al. , Faster sorting algorithms discovered using deep reinforcement learning (2023), Nature</figcaption></figure><p>To test if this approach generalizes to other programming implementations, DeepMind also tested AlphaDev on a competitive coding challenge and a protocol buffer used by Google. In both cases, AlphaDev was able to come up with more efficient implementations, proving that DLR with Monte Carlo Tree Search is a valid approach to finding efficient implementations for common algorithms.</p><h4><strong>Conclusion</strong></h4><p>Deep Reinforcement Learning has shown to be successful in many different environments, from games like Go and Chess to algorithm implementation as seen here. Although the domain is challenging, often dependent on low-level implementation details, and hyperparameter choices, these successes show the results that can be achieved by this powerful concept.</p><p>I hope this article gave you an insight into the latest achievement in RL. If you want a more detailed explanation of Monte Carlo Tree Search or other algorithms that I discussed, please let me know!</p><h4><strong>Sources</strong></h4><p>[1] K. Batcher, Sorting networks and their applications (1968), Proceedings of the April 30 — May 2, 1968, spring joint computer conference (pp. 307–314)</p><p>[2] D. Mankowitz et al., Faster sorting algorithms discovered using deep reinforcement learning (2023), Nature 618.7964: 257–263</p><p>[3] D. Silver et al., Mastering chess and shogi by self-play with a general reinforcement learning algorithm (2017), arXiv preprint arXiv:1712.01815</p><p>[4] D. Silver et al., Mastering the game of Go with deep neural networks and tree search (2016), Nature 529.7587: 484–489</p><p>[5] A. Fawzi et al., Discovering faster matrix multiplication algorithms with reinforcement learning (2022), Nature 610.7930: 47–53</p><p>[6] C. Browne et al., A survey of monte carlo tree search methods (2012), IEEE Transactions on Computational Intelligence and AI in games 4.1: 1–43.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f6a1969e3af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-reinforcement-learning-improved-sorting-algorithms-2f6a1969e3af">Deep Reinforcement Learning improved sorting algorithms</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Azure Machine Learning Studio]]></title>
            <link>https://medium.com/data-science/azure-machine-learning-studio-a21abfc3b1aa?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21abfc3b1aa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 11:25:31 GMT</pubDate>
            <atom:updated>2024-02-12T13:11:50.294Z</atom:updated>
            <content:encoded><![CDATA[<h4>Model creation, deployment, and scoring</h4><p>In this article, we will cover all the required steps to create, deploy and consume a model in Azure Machine Learning Studio. In a previous series, I covered this topic already. However, in the last year, many updates were made to Azure Machine Learning Studio (AML Studio), including a new version of the Python SDK. Therefore an update of this series was required. The outline of this article is as follows: firstly we will present a general introduction to AML Studio, then we will create a compute and environment. Thirdly, we will create a data store and upload the data here. Then, for the remainder of this article, we will create a model, deploy it and test it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*53ibnrUPBSeClAeq" /><figcaption>Photo by <a href="https://unsplash.com/@rresenden?utm_source=medium&amp;utm_medium=referral">Ricardo Resende</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>General Introduction</strong></p><p>Azure Machine Learning Studio is the Machine Learning Suite in Microsofts Azure platform. It can be used to create, deploy and consume models, includes versioning of both data and models, and can be used with both low code and SDK options. In this article, we will go over the Python SDK (V2), but be sure to also check out the low code and AutoML functionality of AML Studio.</p><p>AML Studio contains notebooks to create scripts in which the SDK can be used to create a compute, environment, and model. To run a notebook, we will first need a compute, which you can create using the Compute tab. We will also show how to create a new compute using the SDK, but you first need a compute to run the required commands. Notebooks can be created and changed in AML Studio directly or you can connect to the workspace with Visual Studio Code if you prefer. Details on how to do this can be found <a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-setup-vs-code">here</a>.</p><p>In this article, we will create notebooks in AML Studio itself. Before we start, there is a very convenient shortcut to run all cells in a notebook: Alt+R. Before we can create anything within the workspace, we will first need to authenticate to the workspace to get a workspace handle. This can be done by running the following script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adeb7b368b6dc184f75b24f98e8bbaa4/href">https://medium.com/media/adeb7b368b6dc184f75b24f98e8bbaa4/href</a></iframe><p>This is required for all other notebooks we will create in this article, so always run this command first. Now let’s get started by creating a compute.</p><p><strong>Create a Compute</strong></p><p>A compute can be created with the UI, be sure to create a compute instance with the specifications you require. This compute can then be used to run for instance notebooks. The following code snippet can be used to create a new compute instance using the Python SDK:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c49d1e62d5bdfa02d5cdf6ba2ff595/href">https://medium.com/media/d4c49d1e62d5bdfa02d5cdf6ba2ff595/href</a></iframe><p>You can also create a compute cluster if you require more than one node. The code to do this is slightly different and can be found below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d5bf6c67f13e37264676198378e24a/href">https://medium.com/media/09d5bf6c67f13e37264676198378e24a/href</a></iframe><p><strong>Create an Environment</strong></p><p>In order to train and deploy a model, we also need an environment that specifies the required packages to install. You can also provide the package version to guarantee that your code will run as expected and only updates packages if you tested them first. Environments in AML Studio are very similar to for instance Conda environments. To create them, we will first create a subdirectory ‘dependencies’. Then we will create the .yml file that we need to train and deploy our model. Once this is done, we need to trigger the creation of the actual environment. Environments in AML Studio can be based on predefined images that are maintained by Microsoft. A detailed explanation is provided <a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-manage-environments-v2?tabs=python">here</a>.</p><p>The following code creates and registers an environment in AML Studio:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6681590cf1d122579af2f4f92a496c4/href">https://medium.com/media/d6681590cf1d122579af2f4f92a496c4/href</a></iframe><p><strong>Add Data</strong></p><p>In this article, we will use data from Kaggle to train a model. The dataset we use can be found <a href="https://www.kaggle.com/datasets/ahsan81/hotel-reservations-classification-dataset">here</a>, provided by Ahsan Raza, and is available under a Creative Commons 4.0 License.</p><p>The assignment is to predict if a customer will cancel the reservation or not. In order to use this dataset, we will first upload it to a container in the blob storage connected to the AML workspace. Once this is done, we can create a datastore, if this is not done already, by selecting the Data tab in AML Studio. There, register the datastore using the UI. Now we can access the file by using the new AzureMachineLearningFileSystem class. For this, the full URI of the dataset is required, which can be obtained by selecting the datastore, selecting the file, and copying the URI.</p><p>By default, the azureml-fsspec package is not installed, so before using it, we need to pip install this, by using the magic %pip command. For opening the file, this yields the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f756cdf55acb97d57809da60450db6ae/href">https://medium.com/media/f756cdf55acb97d57809da60450db6ae/href</a></iframe><p><strong>Create a Model</strong></p><p>In order to create a model, we need to create a Main.py file that contains the logic of training the model. For that, we first create a directory to store the file. Now, we will write the main file, similar to how we wrote the .yml file for the Environment. However, be sure to first test all components, before submitting it as a job. That will save you a lot of time, because the creation time of a job is quite long, around 10 minutes.</p><p>First, we need a way to add parameters to the training script. We will do this with the argparse module. For logging, we will use the mlflow module. The autolog method makes it possible to not write a score script because this will be done automatically. With that out of the way, let’s build the actual model!</p><p>We will use a very basic sklearn setup to create the model. Be sure to install sklearn if you did not do this yet. First, we split the dataset into the training and the test set. Because this is merely an example to show AML Studio, we will not use a validation set or use a complicated model. The dataset contains both numerical and categorical features. Therefore, we will use the OneHotEncoder and StandardScaler from sklearn. We save these in a pipeline with a Logistic Regression model. Creating a pipeline this way ensures that we will use the exact same transformations for training data and test data that we will send to the model later. After fitting the model and transformer, we save and register the model. This results in the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89aac7ab141bcc3d417d4eda3955f976/href">https://medium.com/media/89aac7ab141bcc3d417d4eda3955f976/href</a></iframe><p>Now that we have a Main.py file, we need to run a command to run the file and register the model. A command contains several elements and combines all the steps that we have taken so far. First, we provide inputs in a dictionary for all the variables of the Main.py file. Next, we specify the location of the code and the actual command. We need an environment in which this code can run, so we specify the environment we have created previously. The same applies to the compute. The last two parts of the command are the experiment and display name, used in AML Studio. After triggering this job, a link with the details page will be provided, in which you can follow the progress of the model. Most importantly, you can also see detailed logs for debugging any errors that you encounter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e3353ebad66872bc840221584b88273/href">https://medium.com/media/8e3353ebad66872bc840221584b88273/href</a></iframe><p><strong>Model Deployment</strong></p><p>Now that we have created a model, we need to deploy the model to an endpoint in order to use it. To do this, we need to take two steps. Firstly, we create an endpoint and secondly we deploy the model to the endpoint. In this article, we will create an online endpoint. If you need to score large volumes of data, it might be better to create a batch endpoint. The process to do this is quite similar, more details on batch endpoints can be found <a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-use-batch-endpoint?tabs=python">here</a>.</p><p>Creating the online endpoint is quite easy. You need to specify a name and can select methods to authenticate to the endpoint. The two provided options are key and aml_token. The main difference is that keys do not expire, whereas tokens do. In this example, we will use a key. It is possible to add tags to the endpoint to provide extra information on for instance the data used and the type of model. Tags need to be provided in a dictionary. Below you can find the code for creating an online endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01d26def9a567cb7a73fd46be9ca73f2/href">https://medium.com/media/01d26def9a567cb7a73fd46be9ca73f2/href</a></iframe><p>After the endpoint is created (this will take several minutes), we need to deploy the model to the endpoint. First, we retrieve the latest version of the model by name. Then we need to specify the deployment configuration. Note that the instance_type sets the type of compute used to run the endpoint on and it must be selected from the available list of instances. After specifying the configuration we need to run the deployment. This again will take several minutes to complete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e672d2a3bf07bdc08d07e3a30ca9ed48/href">https://medium.com/media/e672d2a3bf07bdc08d07e3a30ca9ed48/href</a></iframe><p><strong>Scoring</strong></p><p>Having created and deployed our model, it is time to test it! We can send request files to the endpoint and receive the prediction. The code and the key to do this from outside AML Studio can be found in the Endpoint tab. There, code to consume the model is provided for C#, Python and R. However, let’s first test the model directly from our AML Studio notebook. To do this, we create a JSON file with input_data. It requires three values. First, we specify the columns in a list. It is important to use the exact same column names as during the training of the model. Next, we specify a list of indices, counting the number of predictions we need. Last, we create a list with a list for each data input. It is important to use the same order for the data inputs as in the columns list. Below you can find the example for the model we created and the code required to send this file to the endpoint. Be sure to delete the endpoint and terminate the compute instance if you do not longer need it. The code to do this is provided in the same example, commented out on the last line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083b589106207aa5c578641fc9f9893d/href">https://medium.com/media/083b589106207aa5c578641fc9f9893d/href</a></iframe><p><strong>Conclusion</strong></p><p>In this article, we have created a compute, environment, and model using Azure Machine Learning Studio. Then, we deployed the model and tested it using sample data. Once again, do not forget to delete the endpoint and terminate the compute instance if you do not longer need it. That was it for now, have fun using AML Studio for your data science projects!</p><p><strong>Sources</strong></p><ul><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-model?tabs=python">Train ML models - Azure Machine Learning</a></li><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-access-data-interactive?tabs=adls">Access data from Azure cloud storage during interactive development - Azure Machine Learning</a></li><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-scikit-learn">Train scikit-learn machine learning models (v2) - Azure Machine Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21abfc3b1aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/azure-machine-learning-studio-a21abfc3b1aa">An Introduction to Azure Machine Learning Studio</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression: Multiple Variables]]></title>
            <link>https://medium.com/@jonathanbogerd/linear-regression-multiple-variables-3d078bdaf582?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d078bdaf582</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 09:18:54 GMT</pubDate>
            <atom:updated>2023-01-12T09:18:54.777Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In this article we will extend our discussion on linear regression to include multiple explanatory variables. This article is the last in a three part series on linear regression. If you want to read part 1, in which we derive the formulas for parameter estimation, please click <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430"><strong>here</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6jpMc-DHpBrsnKW_" /><figcaption>Photo by <a href="https://unsplash.com/@antoine1003?utm_source=medium&amp;utm_medium=referral">Antoine Dautry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Adapting our formulas</strong></p><p>Multivariable linear regression is very similar to regression with only one variable. Instead of predicting our variable of interest with only one factor, we create a model that includes multiple variables. For simplicity, we will use 2 factors in the example below. Our linear model can then be written as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FndawJCgraRytd7WGpZBu4C&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FndawJCgraRytd7WGpZBu4C&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="210" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/b78c418ee4c09f3561bfa6cac3ef2153/href">https://medium.com/media/b78c418ee4c09f3561bfa6cac3ef2153/href</a></iframe><p>In part 1 of our series on linear regression, we derived the formulas for a and b. If you are interested in the full derivation, please find the article <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430"><strong>here</strong></a><strong>.</strong></p><p>To account for multiple explanatory variables, we will use a vector and matrix representation of the above linear model. Let <strong>y </strong>be a vector containing n observations, <strong>X </strong>a matrix containing the k explanatory variables of n observations, <strong>b</strong> a vector of size k, containing the estimated parameters and <strong>e</strong> a vector of size n with the residuals or errors. The matrix <strong>X </strong>now also contains the constant or intercept, by setting the first column of the matrix to all 1s. In this way, we can express the equation above as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fs2TUF2ojkB18Ht23r5dfDt&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fs2TUF2ojkB18Ht23r5dfDt&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/19adb7525c231f2a83e9e0ac83af9144/href">https://medium.com/media/19adb7525c231f2a83e9e0ac83af9144/href</a></iframe><p>This nice and short form of the regression formula is exactly the same as before, we have only used a matrix and vectors to represent it. We can also derive the formula for both the constant or intercept and the parameters in a similar way as before. We will use basic knowledge of matrix and vector differentiation, but if you are not familiar with that, you can still follow the derivation and confirm that our way of estimating the unknown vector <strong>β</strong> is correct. Is important to make a distinction between <strong>b</strong> and <strong>β</strong>: <strong>b</strong> is the estimation of the unknown vector <strong>β</strong>.</p><p>Let us start with defining the sum of squared errors, that is:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuBUNDvAGrnG4FA5qFvhUhA&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuBUNDvAGrnG4FA5qFvhUhA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="143" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c47d7c12e5d2e80e57108b548809d60/href">https://medium.com/media/5c47d7c12e5d2e80e57108b548809d60/href</a></iframe><p>Where <strong>e’</strong> corresponds to the transpose of vector <strong>e</strong>. Then</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FkDtAvQ7zHNnhLyHx7b77Pm&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FkDtAvQ7zHNnhLyHx7b77Pm&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="527" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/85e0ca047b90d0ae3a48458543a5c8bf/href">https://medium.com/media/85e0ca047b90d0ae3a48458543a5c8bf/href</a></iframe><p>In order to find the minimum squared error with respect to the unknown vector <strong>b</strong> we again differentiate this last equation:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F66N6FjNnURtPEvYpuHquU9&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2F66N6FjNnURtPEvYpuHquU9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="434" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc3744cfcdd67cff842f45e5f0dd9250/href">https://medium.com/media/bc3744cfcdd67cff842f45e5f0dd9250/href</a></iframe><p>Equating this to 0 yields:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuW5qcycQVDr9sxo2zfZA2a&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuW5qcycQVDr9sxo2zfZA2a&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0192ca2dcf5332bf1ab7b56f181ad24/href">https://medium.com/media/d0192ca2dcf5332bf1ab7b56f181ad24/href</a></iframe><p>And this gives us the final result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FdFPH2JMH84vwsHG5rPKZUM&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FdFPH2JMH84vwsHG5rPKZUM&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/c174b7c4afae489e318e3853afa32dfe/href">https://medium.com/media/c174b7c4afae489e318e3853afa32dfe/href</a></iframe><p>Where the power minus 1 corresponds to the inverse of the matrix. Multiplying matrix <strong>X</strong> and its inverse results in the so-called Identity matrix <strong>I</strong>. This can be seen as a matrix version of 1, that is: <strong>X*I = X</strong>.</p><p>A technical but important point here is that the inverse of that matrix <strong>X </strong>only exists if <strong>X </strong>has at least rank k. This means that we need that the number of parameters is smaller than or equal to the number of observations. In practice however, it only makes sense to have substantially more observations than parameters for a good parameter estimation.</p><p><strong>Bias and Variance</strong></p><p>Now that we have an estimate for our parameter vector <strong>β</strong>, it is important to assess the quality of this estimation. In particular, we need to know if our estimate is biased or unbiased, that is on average correct or wrong, and we need to know what the variance of our estimator is. An estimator with a low variance is preferred over one with a high variance. A low variance indicates that our estimation <strong>b</strong> is close to the underlying value of <strong>β</strong> with a high probability. The higher the variance, the lower that probability becomes.</p><p>Let’s first calculate the bias of our estimator. This is done by finding the expected value of <strong>b</strong>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FjzTyVDbipiRuqY3E7dngYn&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FjzTyVDbipiRuqY3E7dngYn&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="768" height="112" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc3733d2079d1a7160f47ef4bda0571b/href">https://medium.com/media/bc3733d2079d1a7160f47ef4bda0571b/href</a></iframe><p>Note again that there is a difference between <strong>b</strong> and <strong>β</strong>, the latter representing the true value of the parameters, and <strong>b</strong> being our estimation of it. The same difference applies to <strong>e </strong>and <strong>ε</strong>. The Greek letter represents the true underlying value, and <strong>e </strong>the observed residuals.</p><p>We can already see that the expected value of <strong>b</strong> is equal to the expected value of <strong>β</strong>, apart from the second part of the above formula. However, because one our assumptions is that the disturbance is on average 0, the second part equates to 0. Therefore, we can see that our estimation of <strong>β</strong> is unbiased.<strong> </strong>The second <a href="https://medium.com/@jonathanbogerd/linear-regression-7-assumptions-a3fba42828bc">article</a> of this series is all about the underlying assumptions of Linear Regression if you want to find out more.</p><p>For calculating the variance of our estimator, we will use the standard formula for the variance:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8cJUxvWcuTR9SDZWehBDTe&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8cJUxvWcuTR9SDZWehBDTe&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="243" height="138" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b43d7d6177a4d4c1422e8a8c5ab9ea5/href">https://medium.com/media/6b43d7d6177a4d4c1422e8a8c5ab9ea5/href</a></iframe><p>In finding the bias of our estimator, we already found the following:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FetFwETTRk7XPFP25b5yQsp&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FetFwETTRk7XPFP25b5yQsp&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="235" height="138" frameborder="0" scrolling="no"><a href="https://medium.com/media/430ef7a2c750432a827d50621a325fc2/href">https://medium.com/media/430ef7a2c750432a827d50621a325fc2/href</a></iframe><p>Therefore:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FaomK5WiBEr9wDkFNt7Upg3&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FaomK5WiBEr9wDkFNt7Upg3&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="774" height="138" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a19e87cd37743263a2509afa850a56e/href">https://medium.com/media/4a19e87cd37743263a2509afa850a56e/href</a></iframe><p>as the transpose operator reverses the order of multiplication. We again use one of the assumptions, namely that the covariance of the disturbances is 0, in other words, there is no correlation between disturbances. This gives us our final result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FiLYFsdrWEsg7s27Gxwmc1i&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FiLYFsdrWEsg7s27Gxwmc1i&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="660" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/be679e28e84e0edd999caf997e032b33/href">https://medium.com/media/be679e28e84e0edd999caf997e032b33/href</a></iframe><p>Although we will not prove it here, is can be shown that out of all linear and unbiased estimators, our estimate of <strong>β </strong>is the estimate with the lowest variance possible.</p><p><strong>Extra Assumptions</strong></p><p>In the second <a href="https://medium.com/@jonathanbogerd/linear-regression-7-assumptions-a3fba42828bc">article</a> in this series we discussed the 7 assumptions underlying linear regression with one explanatory variable. Adding more explanatory variables requires one more assumption: Explanatory variables should be uncorrelated. To be more precise:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoNXke96LoEb1DLmRajgPaX&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoNXke96LoEb1DLmRajgPaX&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2d89c0612e1b8317664cdc98962849/href">https://medium.com/media/5d2d89c0612e1b8317664cdc98962849/href</a></iframe><p>If this assumption is violated, the parameter estimations will be wrong for our parameters <strong>β</strong>. Next to that, the estimation for the variance and any resulting p values and confidence intervals are not correct. Note that this covariance issue can be fixed by using ‘cleaned’ variables, a result of the Frisch-Waugh theorem. In this article we will not go into the specifics, but the main idea is that you remove the effects of a variable on another variable by auxiliary regression, before using the variable in the main regression.</p><p><strong>Code Example</strong></p><p>Now that we have derived all the formulas, let’s test them using Python!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f903b5d4cf5720d6aebfb3b60a1c1db/href">https://medium.com/media/7f903b5d4cf5720d6aebfb3b60a1c1db/href</a></iframe><p>If you run this code section, you will see that our estimation <strong>b </strong>is close to the true underlying value <strong>β</strong>.</p><p><strong>Conclusion</strong></p><p>In this article we derived the formula for Linear Regression, using the matrix representation. In addition we determined the bias and the variance of our estimator. This article concludes the three part series on Linear Regression. If you want to start from the beginning, <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430">this</a> article starts this series.</p><p>If you want to read more articles on data science, machine learning and AI, be sure to follow me on Medium!</p><p><strong>Sources</strong></p><p>1. Heij, C., de Boer, P., Franses, P. H., Kloek, T., &amp; van Dijk, H. K. (2004). <em>Econometric methods with applications in business and economics</em>. Oxford University Press.</p><p>2. Gujarati, D. N. (2021). <em>Essentials of econometrics</em>. SAGE Publications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d078bdaf582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression: 7 Assumptions]]></title>
            <link>https://medium.com/@jonathanbogerd/linear-regression-7-assumptions-a3fba42828bc?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3fba42828bc</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[ordinary-least-square]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 10:12:44 GMT</pubDate>
            <atom:updated>2022-09-18T10:12:44.106Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In this article we will go over the 7 assumptions of Ordinary Least Squares (OLS). In the previous <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430">article </a>we derived the formulas for OLS. This article covers the 7 assumptions that are required for OLS. In Part 3 we will investigate Linear Regression with multiple input variables. This three part series will teach all the basics you need to know on Linear Regression.</p><h3>Data generating process</h3><p>In this article we will use the same data generating process as in the first article on Linear Regression. The code and means to plot the results can be found in the code box below. We estimate parameters a and b with the formulas we have derived in the previous article. If you want to see how we derived those, please check out my previous <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430">article</a><strong>. </strong>Note that this time, the calculations for the variances of a and b are also included. We will show the impact of the assumptions of Linear Regression by changing the code to violate one of the assumptions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2a61d4b1f640d4a93d070985ff4aac/href">https://medium.com/media/9c2a61d4b1f640d4a93d070985ff4aac/href</a></iframe><p><strong>Assumptions</strong></p><h3>1. Random disturbance with mean zero</h3><p>The first assumption we have for Linear Regression is that the random errors should have a zero mean. If this would not be the case, it is easy to see that the parameter estimate for a is incorrect and will include the mean of the error term. This can be seen in the following example in which the mean of the error is changed to be 3. The resulting estimated parameter value for a is about 3 of the correct value, making the parameter estimate for a biased.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec7fd0144a73ea7e3932ead06fe3862/href">https://medium.com/media/4ec7fd0144a73ea7e3932ead06fe3862/href</a></iframe><h3>2. Homoskedasticity</h3><p>The next assumption, also on the error terms, is that the variance for all error terms is the same. If this is violated, the parameter estimates will still be unbiased, however, the calculation for the variance of a and b will be incorrect. In the code sample you can check that the parameters are still unbiased, however the variance has changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5de3bf292edb538e6aaa9a79c4978f7a/href">https://medium.com/media/5de3bf292edb538e6aaa9a79c4978f7a/href</a></iframe><h3>3. No correlation</h3><p>The next assumption in OLS is that the error terms are not correlated. If this is the case, it is usually called serial correlation or autocorrelation. The problem with violating this assumption, is that it shows that some information is uncaptured in the model. You can partially forecast the next error by knowing the current error, which therefore should be part of your model. This can be tackled in mainly two ways: Use a time series model or add a independent variable that captures this information.</p><h3>4. Jointly normally distributed error terms</h3><p>This assumption is technically not required for OLS. Even if the error terms would not be normally distributed, our formulas are correct and the parameter estimates unbiased. However, this property has some advantages. Firstly, our parameter estimates have the lowest possible variance of any unbiased estimator. Secondly, because this assumptions ensures that the OLS estimate is also the Maximum Likelihood Estimator (MLE), it makes our parameter estimation the best possible estimator.</p><h3>5. Constant parameters</h3><p>Constant parameters in the data generating process (DGP) are required to get accurate estimates for both a and b. If the parameters would change during the DGP, there is no way to estimate them properly and the estimates would be biased. If you encounter a real world situation in which parameters might have changed during the collection of the data, it might be worthwhile to estimate a parameter for each window with constant parameters. Note that changing parameters is closely related to the concept of non-stationarity. An example of changing parameters can be found in the code sample below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71af72055c4e1d593f2ab8265c47732a/href">https://medium.com/media/71af72055c4e1d593f2ab8265c47732a/href</a></iframe><h3>6. Fixed Regressors</h3><p>Fixed regressors can be seen as a fixed set of numbers instead of variables themselves. We needed this in the derivation of the formulas for our parameters. If you missed this, please read my previous <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430">article </a>on this topic. In practice however, it is more reasonable to think of our regressors X as outcomes of an underlying process. It can be shown that our formulas will still holdup in this case, provided that our regressors are independent of all error terms.</p><h3>7. Linear Model</h3><p>Last but not least, in order for Linear Regression to provide good results, the underlying model or data generating process should of course be linear as well. Although this is usually unknown, it is important to evaluate the performance of the linear regression model, for instance by comparing R2 or by visual inspection. In the graph below, you can see the performance of a linear regression model for a non linear data generating process. Clearly, linear regression is not the correct choice in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*n8hy-G6raw2RKp-5eky44Q.png" /><figcaption>Linear Model vs Quadratic DGP</figcaption></figure><h3>Conclusion</h3><p>In this article we discussed the 7 assumptions required for OLS and investigated the consequences of breaking these assumptions. In the next article, we will have a look into Linear Regression with multiple input variables. If you want to read the first article in this series, please find the link <a href="https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430"><strong>here</strong></a>.</p><p>If you want to read more articles on data science, machine learning and ai, be sure to follow me on Medium!</p><h3>Sources</h3><ol><li>Heij, C., de Boer, P., Franses, P. H., Kloek, T., &amp; van Dijk, H. K. (2004). <em>Econometric methods with applications in business and economics</em>. Oxford University Press.</li><li>Gujarati, D. N. (2021). <em>Essentials of econometrics</em>. SAGE Publications.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3fba42828bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression: Deriving the Formulas]]></title>
            <link>https://medium.com/@jonathanbogerd/linear-regression-deriving-the-formulas-67f61c78430?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/67f61c78430</guid>
            <category><![CDATA[ordinary-least-square]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 15:50:26 GMT</pubDate>
            <atom:updated>2022-08-31T15:50:26.659Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In this article we will cover the basics of Linear Regression. In part 1 we will derive the formulas and test their accuracy. Part 2 will discuss the assumptions underlying Linear Regression and in particular Ordinary Least Squares (OLS). In it we will test what happens if any of these assumptions is violated. In Part 3 we will investigate Linear Regression with multiple input variables. This 3 part series will teach all the basics you need to know on Linear Regression.</p><p><strong>Deriving the Formulas</strong></p><p>The idea of linear regression is to find the linear relation between an outcome variable, usually called ‘y’ and a set of input variables, denoted by ‘x’. This linear relation can be mathematically expressed as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FnMWhbMFuQHipfc9efzEvbf&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FnMWhbMFuQHipfc9efzEvbf&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/27b07cddb31ab1c957bac8a6fb651143/href">https://medium.com/media/27b07cddb31ab1c957bac8a6fb651143/href</a></iframe><p>In this equation, the input variable(s) x are related to the output y by a factor ‘b’ and a constant ‘a’. Graphically, a is the intercept of the given line, and b is the slope. Similar to the provided example, we will only discuss the case with one explanatory variable, that is one variable x, instead of a set of input variables. This is usually called simple regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*VbXb_KC8txXnudZF7HoPFA.png" /></figure><p>Linear Regression deals with the question: what are the best estimates for a and b to approximate the linear relation between x and y. In other words, we want to find the line that gives the best fit through the data points. In order to do this, we first have to determine what best really means.</p><p><strong>Determine the Error</strong></p><p>Probably the most intuitive measure would be to minimize the error for each observation, that is the vertical distance between each point and the given line. This error for observation i is denoted by</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F2XLmBbFybezG3MF2kLfudk&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F2XLmBbFybezG3MF2kLfudk&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/879fb7709330b72760cf28d7d953b7a6/href">https://medium.com/media/879fb7709330b72760cf28d7d953b7a6/href</a></iframe><p>The vertical distance is then the absolute value of e. We want to minimize the sum of all errors, hence:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FsAM2nhSYvvKzkG52ttgytE&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FsAM2nhSYvvKzkG52ttgytE&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="143" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b8aefd1842d7a3b4b422dc167b74582/href">https://medium.com/media/0b8aefd1842d7a3b4b422dc167b74582/href</a></iframe><p>Here we sum over all observations and for the rest of this article we will use the symbol n to denote the number of observations.</p><p>A standard approach for minimizing a function, is to calculate the derivative and equate it to zero. The solution to this equation then is the minimum. Of course, you would also have to check if a minimum exists for instance calculating the second order derivative, but for simplicity, we will ignore this part. If you are familiar with calculus you know that the derivative of an absolute value function is a piecewise defined function and that it is not defined at the point zero. If you look at the graph below, you can see that the slope is not continuous, indicating a piecewise derivative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*zW4335n2cmiO65GQ4zNRIw.png" /></figure><p>Therefore, although it is of course possible to use this error function, the most common approach is to minimize the sum of all squared errors:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fsv7t99TcBAaTNFdyhU4pwz&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fsv7t99TcBAaTNFdyhU4pwz&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/a749ca963eaa6c8df78391853e01f3de/href">https://medium.com/media/a749ca963eaa6c8df78391853e01f3de/href</a></iframe><p>Finding parameters a and b by minimizing this function is called Ordinary Least Squares. Lets start by finding the value of a that minimizes the error function.</p><p><strong>Calculating the Intercept a</strong></p><p>As explained, we want to find the minimum of squared errors, by calculating the derivative and equating it to 0. However, as we have two parameters that can be tuned, we will need partial derivatives with respect to both a and b. Lets start with finding the expression for a:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F6qW4A1XJDtVYJxWyQEPqdA&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F6qW4A1XJDtVYJxWyQEPqdA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="276" height="183" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e3d1404bee07b0c9ca05919c9c41d39/href">https://medium.com/media/7e3d1404bee07b0c9ca05919c9c41d39/href</a></iframe><p>Note that b and x are not variables in this partial derivative, but fixed constants. Therefore, the chain rule shows that we only need to multiply the derivative by -1, resulting in the shown derivative. Both y and x are dependent on i, however a is not. Rewriting to clarify this expression yields:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FictpHgZWX3yWp5w1aAGSXN&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FictpHgZWX3yWp5w1aAGSXN&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="319" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c1a51c52ca2c91ce1041b862b5e058/href">https://medium.com/media/e2c1a51c52ca2c91ce1041b862b5e058/href</a></iframe><p>Dividing both sides by 2n results in a expression for a. Note that summing y over all observations and then dividing by n is equivalent to the average of y, denoted by y bar. The same applies for x. Therefore, we found the value of a that minimizes the squared error:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FmjFqRU6CthNabmbmjEHFEr&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FmjFqRU6CthNabmbmjEHFEr&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/e695515d07923dacc2b92a6efe6e0a30/href">https://medium.com/media/e695515d07923dacc2b92a6efe6e0a30/href</a></iframe><p><strong>Calculating the Slope b</strong></p><p>Finding the value for b is a little bit more involved. First note that the average of x, x-bar, is independent of i. Then, the expression for the derivative of a can also be written as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F35kWXTHCDx5YJ3Js4zn2JY&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F35kWXTHCDx5YJ3Js4zn2JY&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="320" height="192" frameborder="0" scrolling="no"><a href="https://medium.com/media/72698001e9765769e135ed6c3b86ae6e/href">https://medium.com/media/72698001e9765769e135ed6c3b86ae6e/href</a></iframe><p>where we multiplied both sides by the average value of x and divided by -1. Now we move the average of x inside of the summation, which is allowed due to the mentioned independence. This yields:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fd863JJgEPxZ6jNjxXDTsxf&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fd863JJgEPxZ6jNjxXDTsxf&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="220" height="143" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4248bc32a0b159cef107ed17fe095d3/href">https://medium.com/media/e4248bc32a0b159cef107ed17fe095d3/href</a></iframe><p>But, why would we do this? We want to obtain a value for b, not for a! However, it turns out that we can use this expression, which we know equals 0, to our advantage.</p><p>The partial derivative with respect to b is:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F4b7LFK49tSmDDtviHp27Ep&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F4b7LFK49tSmDDtviHp27Ep&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="620" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/116b8323207fe9e322cd6c91e0787bf7/href">https://medium.com/media/116b8323207fe9e322cd6c91e0787bf7/href</a></iframe><p>Subtracting the new equation based on the derivate of a on both sides of the equation and reworking terms yields :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fh3MqvjykmqGUKG8NvmsNGV&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fh3MqvjykmqGUKG8NvmsNGV&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="522" height="174" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9adedf2fb9d62c959cc005d2a1c89fe/href">https://medium.com/media/d9adedf2fb9d62c959cc005d2a1c89fe/href</a></iframe><p>Now we can use the equation we found for a to solve for b:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F86yTdn4PSWQjPLWKqYBDhq&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F86yTdn4PSWQjPLWKqYBDhq&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="463" height="220" frameborder="0" scrolling="no"><a href="https://medium.com/media/138a465ba86b8f07ec908c62a08eb017/href">https://medium.com/media/138a465ba86b8f07ec908c62a08eb017/href</a></iframe><p>Here we have our formulas for both a and b! Note that the formula for b is very close to the formula of the covariance of x and y. This is not surprising as both measure the relation or the effect of a change to x on y.</p><p><strong>Data Generation and Test</strong></p><p>Now, lets put our formulas to the test using some Python code. We will generate a random sample of 1000 x values between 0 and 10 and a random sample of 1000 error values, with a standard normal distribution with mean zero. In the next article, on underlying assumptions for OLS, we will go into the reasons for the normal distribution.</p><p>Then we calculate y using the linear relation formula, now including the error term:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FahEadywhYADY58zhsvsn3z&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FahEadywhYADY58zhsvsn3z&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6bc62c2bc9238544887737792178b28/href">https://medium.com/media/c6bc62c2bc9238544887737792178b28/href</a></iframe><p>We will set a to 3 and b to 2 in this example. Now let’s calculate our best estimate for a and b using our formulas. All this is implemented in the section of code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e134f2271c0fa3364b4733adc03429a/href">https://medium.com/media/7e134f2271c0fa3364b4733adc03429a/href</a></iframe><p>In this case, we find a = 3.09 and b = 1.99, very close to the true underlying values of and b, despite the random errors that are present. In the graph below, you can find a plot with the data and the plotted line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*D9DCAHlL77M3Hsr0MEV-ng.png" /></figure><p><strong>Conclusion</strong></p><p>In this article we derived the formulas used in Ordinary Least Squares and tested the accuracy of the found estimates. However, Ordinary Least Squares is based on 7 assumptions that we did not explicitly discuss in this article. That will be the topic of the next article!</p><p>If you want to read more articles on data science, machine learning and AI, be sure to follow me on Medium!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67f61c78430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signs of overfitting and how to avoid it]]></title>
            <link>https://medium.com/@jonathanbogerd/signs-of-overfitting-and-how-to-avoid-it-7aa24c01f46f?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aa24c01f46f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 08:12:26 GMT</pubDate>
            <atom:updated>2022-06-08T08:12:26.986Z</atom:updated>
            <content:encoded><![CDATA[<p>A main issue while developing a machine learning model is the problem of overfitting. Overfitting occurs when the model you have developed learned not only some of the genuine interactions in the dataset but also fits the noise in the dataset. Typically, overfitted models perform very well on the training set that is used, but perform poorly on the test set. However, there are several ways to avoid overfitting and in this article I will go over some methods to do this. To illustrate the effect of each of these measures, we will test their effect while training a machine learning model on a dataset. Tests will be performed in Python, using pyspark in Azure Synapse Analytics. For more information on how to use Azure Synapse Analytics, see one of my previous <a href="https://medium.com/@jonathanbogerd/data-preparation-with-azure-synapse-analytics-2c54ef926460">articles</a><strong>.</strong> Before we test some methods to help avoid overfitting, we will first discuss some signs of and reasons for overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*c4s7ja2PxPetwxAvtszkGA.png" /><figcaption>By Chabacano — Own work, CC BY-SA 4.0, <a href="https://commons.wikimedia.org/w/index.php?curid=3610704">https://commons.wikimedia.org/w/index.php?curid=3610704</a></figcaption></figure><p><strong>Signs of Overfitting</strong></p><p>In order to avoid overfitting, it is very helpful to know some signs of overfitting. I will describe 3 different signs, but not all of them are applicable to all different types of models.</p><ol><li>Low error rates for training set compared to test set</li><li>High standard errors</li><li>Entirely different parameters for subsets of the data</li></ol><p>The first sign is applicable to all types of models. If you see a big discrepancy in train and test errors, this could be due to overfitting. It is typical that your machine learning model performs slightly better on your train set than on your test set. However, if the difference is very large, consider a method to prevent overfitting.</p><p>The second and third sign are applicable to models for which it is possible to view individual estimated parameters and corresponding standard errors. This is for instance possible for Linear Regression models. High standard errors can indicate high variance in your model. Models with high variance typically overfit and this is therefore a sign to be careful. The third sign of overfitting is as much a sign as a test for overfitting. If you create two subsets of your entire training set, select for instance 80% of your training set at random, and estimate your machine learning model. If the two resulting models are vastly different, this can be a clear indication that your model is not necessarily focusing on the patterns in the data, but more focusing on the noise. In the next section we will go over the reasons for overfitting and also verify this with examples. We will determine if a model overfits by using the signs mentioned.</p><p><strong>Reasons for Overfitting</strong></p><p>In this section we will go over the two main reasons for overfitting: too many variables or too complex models. For both reasons we will look at an example of overfitting and use the beforementioned signs of overfitting.</p><p><strong>Too many variables for the number of observations</strong></p><p>As mentioned in the introduction, in order to test the effects and signs of overfittings, we will use two Covid datasets provided in Azure Synapse Analytics. For more details on the feature engineering and Azure Synapse, see one of my other articles<a href="https://medium.com/@jonathanbogerd/data-preparation-with-azure-synapse-analytics-2c54ef926460"> here.</a> In order to show the effect of a high number of variables compared to the number of observations, lets take a small subsample of our training set and train a Linear Regression model on this dataset.</p><pre>dfTotal = dfTotal.drop(&#39;State&#39;,&#39;Date&#39;,&#39;Updated&#39;)</pre><pre>dfTrain, dfTest = dfTotal.randomSplit([0.7,0.3],1234)</pre><pre>dfTrain = dfTrain.sample(0.005,1234)</pre><pre>print(&quot;Train size&quot;,dfTrain.count())</pre><pre>print(&quot;Number of Variables&quot;, len(dfTrain.columns))</pre><pre>print(&quot;Test size&quot;,dfTest.count())</pre><p>All in all this gives us a dataset with 61 rows and 16 explanatory variables. We will create a Linear Regression model using statsmodels, because it provides easy options to determine the regression parameters and the corresponding standard errors. We will also include the test and train errors. This results in the following code:</p><pre>import statsmodels.api as sm</pre><pre>from sklearn.metrics import r2_score,mean_absolute_error, mean_squared_error</pre><pre>dfTrainPd = dfTrain.toPandas()</pre><pre>dfTestPd = dfTest.toPandas()</pre><pre>X_train, y_train = dfTrainPd.loc[:, dfTrainPd.columns != &#39;positive_increase&#39;],dfTrainPd[&#39;positive_increase&#39;]</pre><pre>X_test, y_test = dfTestPd.loc[:, dfTestPd.columns != &#39;positive_increase&#39;],dfTestPd[&#39;positive_increase&#39;]</pre><pre>ols = sm.OLS(y_train, X_train)</pre><pre>ols_result = ols.fit()</pre><pre>preds = ols_result.predict(X_test)</pre><pre>predsTrain = ols_result.predict(X_train)</pre><pre>MAETest = mean_absolute_error(y_test, preds)</pre><pre>print(&#39;Test MAE &#39;,MAETest)</pre><pre>MAETrain = mean_absolute_error(y_train, predsTrain)</pre><pre>print(&#39;Train MAE &#39;,MAETrain)</pre><p>The resulting test and train error are 832 and 520 respectively. This large difference in test and train error already points to overfitting in the model. Next to that, we get the standard errors of the estimated parameters by using the following code:</p><pre>ols_result.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*tXhnClWsi2JvfaG5-FsWuw.png" /></figure><p>From this table, you can see that the standard errors are relatively high. However, it could be that the explanatory variables are just not that informative for our label. Therefore, we will test for overfitting using a 80% sample of our dataset and compare it to the parameters provided in the table above. This can be done by the sample command in pyspark. The resulting table is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*LbUrZmKN0aN89BUHv3XsNA.png" /></figure><p>In the first figure, we can find a 95% confidence interval for a parameter estimate. We will count the number of estimators of the subset model that do <strong>not</strong> fall within the 95% confidence interval. We can see that the first 5, among which the most important explanatory variables, are without the provided confidence interval, a clear sign of overfitting.</p><p><strong>Too complex Model</strong></p><p>Now lets consider a different reason for overfitting: too complex models. To show an example of this in practice, we will look a decision tree regressor on the same dataset that we have used so far. Note that we now take the full training set and not a subset. One way to make a decision tree more or less complex is by varying the depth of the tree. For this example, we varied the depth from 1 to 23 and compared the R2 score and the Mean Absolute Error (MAE) for both the train and test set. The code for this can be found below:</p><pre>from sklearn.tree import DecisionTreeRegressor</pre><pre>regr = DecisionTreeRegressor(max_depth=23)</pre><pre>regr.fit(X_train,y_train)</pre><pre>preds = regr.predict(X_test)</pre><pre>predsTrain = regr.predict(X_train)</pre><p>For this decision tree, it is not possible to compare individual estimators and their standard errors. Therefore, we will compare the impact of overfitting based on the train and test error. The following figures show the train and test errors and R2s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NE4yjLHND9zPC2VO2Fkvlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ml1ajEvMamdcQ34ahqHIaQ.png" /></figure><p>Although the optimal depth is different for the MAE and R2, the pattern is very similar. If you use the MAE as an error measure, it is clear that a max depth of around 10 or 11 was the best and any deeper trees can be considered overfitting. For the R2 measurement, the optimal depth was around 6 or 7, afterwards the test score for the R2 goes down, whearas the R2 for the training set quickly goes to 1. These two figures clearly show, that the model you select should not be to complex and you should not only focus on the training score.</p><p><strong>Conclusion</strong></p><p>This article listed three signs of overfitting:</p><ol><li>Low error rates for training set compared to test set</li><li>High standard errors</li><li>Entirely different parameters for subsets of the data</li></ol><p>All of these points where illustrated using either a Linear Regression Model or a Decision Tree. Be careful when training a model not to focus to much on the score of the training set, this can have negative results for the overal performance of your model and test for signs of overfitting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aa24c01f46f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pros and Cons of Azure Synapse for a data scientist]]></title>
            <link>https://medium.com/@jonathanbogerd/pros-and-cons-of-azure-synapse-for-a-data-scientist-96e715396211?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e715396211</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[synapse]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 07:53:40 GMT</pubDate>
            <atom:updated>2022-02-25T07:53:40.218Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will explain the main features, advantages and disadvantages of Azure Synapse Analytics, an all-in-one platform created by Microsoft. It combines familiar Azure features such as Azure Data Factory, Azure Storage, Azure SQL Server and Azure Databricks into one platform. In the previous articles we have seen how to setup the Azure environment, how to extract, load and process data (ELT), how to develop a model and how to use this model to forecast. This article will be the last in this 5 part series on Azure Synapse Analytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L-Jxa52iUOc54LhJ" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Advantages</h3><p>In my opinion, there are three main advantages of Azure Synapse Analytics compared to the separate services of Azure it combines.</p><p>The first and most important advantages for a data scientist is that a lot of data engineering work is done automatically by Synapse. Training and scoring a model via for instance Databricks using Azure Machine Learning is often cumbersome and requires special attention to the correct versioning of Python, many packages and correct access policies in order to communicate between Databricks and Machine Learning. Currently, authentication between for instance Databricks and AML is rather complicated, especially if a virtual network is used for security reasons. By integrating all functionalities in one Azure service, authentication is made easier and eliminates the need for access outside Azure which would be required for Databricks. Synapse takes care of almost all of this in the background, so that you can focus on creating models and insights on data instead of on infrastructure and data engineering. Especially if data engineering is not your primary focus or expertise this is huge advantage and can save a lot of time and frustration.</p><p>The second advantage is that you do not longer have to access all services separately in order to develop an end-to-end solution in separate windows. This makes it easier and faster to develop in Azure Synapse Analytics as there now is one place that does it all. The third advantage is related to SQL. Synapse provides the options for serverless SQL. This makes it easier to use a SQL database, especially for smaller datasets, for which a dedicated SQL pool would be to costly. Having a SQL database can be beneficial if you want to connect other services, for instance bi software, to your prepared data sets. Synapse can therefore be used as a serving layer.</p><h3>Disadvantages</h3><p>However, Synapse does not only provide advantages of course. In my opinion, there are a number of disadvantages. The first disadvantage is related to the sometimes unfinished interface. Currently, it is not possible to scroll through a cell of a notebook for instance. Renaming a notebook is also more cumbersome than it should be. More difficult is the host of preview options which limit the current use of many important Synapse features in a production environment. Although this is likely to be resolved while Synapse is in development, for current users, relying on a stable, non-preview Synapse version, the options are limited. One can argue that currently the situation is similar to Azure Machine Learning, which is also undergoing permanent changes. Therefore, combining Synapse and Machine Learning, a powerful combination for a data scientist, can run into stability problems and code might require changes due to updates for either of these platforms.</p><p>Another (current) disadvantage of Azure Synapse Analytics is that the Spark clusters to run for instance the notebooks are not accessible outside of Synapse. For some setups (for instance in some cases of using Tableau) a Spark cluster is required to read or query files. For Databricks, the clusters are accessible outside of Databricks. Therefore, if you infrequently need a Spark cluster, you can use existing clusters within Databricks, eliminating the need to host your own Spark cluster. This option is not available within Synapse, the clusters cannot be accessed outside of Synapse. A next disadvantage is the limited Spark options that are available. If you run more complicated data transformations for which you have optimized your Spark cluster and settings, the same settings can often not be replicated within Synapse. Lastly, although the serverless SQL pool can be useful for many applications, the dedicated SQL pool currently offered within Synapse Analytics is very expensive. Using dedicated instead of serverless therefore is not worth it in most use cases, although it does provide a host more options than the serverless SQL pool.</p><h3>Conclusion</h3><p>All in all, Azure Synapse Analytics is well suited for any data scientist that wants to focus on creating models and insights in data, without having to worry about infrastructure. It is easy to setup, easy to use and can create good models that can immediately be used. Azure Synapse Analytics has the potential to become a center piece in a data driven environment. Using it is not without its issues, but once most of the important options are out of preview, Synapse is the tool for a data scientist to help the business towards the data driven future.</p><p><strong>Sources</strong></p><p><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-configure-databricks-automl-environment">Develop with AutoML &amp; Azure Databricks - Azure Machine Learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e715396211" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model deployment and scoring in Azure Synapse Analytics]]></title>
            <link>https://medium.com/@jonathanbogerd/model-deployment-and-scoring-in-azure-synapse-analytics-64df36ee7789?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/64df36ee7789</guid>
            <category><![CDATA[synapse]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[development-model]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 07:03:41 GMT</pubDate>
            <atom:updated>2022-02-24T07:03:41.249Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss model deployment and scoring with models. Two main options are available, the first being deployment via AML studio endpoints, the second loads the model in a notebook and uses it to score the dataset provided. The advantage of using an endpoint is that it is easily accessible and can be consumed from all kinds of software. On top of that, endpoints can be easily monitored from Azure Machine Learning Studio. However, it is more costly than the second option. This option can be especially useful if the model is consumed from Synapse or for instance Azure Databricks and will be consumed maybe once a day or less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W1Q2SKy23SnmdwKv" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj?utm_source=medium&amp;utm_medium=referral">Pietro Jeng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Synapse and AML</h3><p>For the deployment of a machine learning model that is registered in Azure Machine Learning Studio, there are currently three options in Azure Machine Learning, two of which are at the moment of writing in preview. Firstly, we will discuss the <em>Deploy to web service</em> option, the only non-preview option.</p><h3>Webservice</h3><p>If you deploy your model as a web service, you have two options for your compute type. The first is an Azure Kubernetes Service (AKS) and for all production settings, this is the recommended option by Microsoft. You will have to setup AKS yourself and you can do this within the Azure environment. The other option is the Azure Container Instance (ACI). This option is only recommended for testing purposes, but is easier to setup as it is automatically created if you select this option. If you select an ACI as compute, you will have to provide both the entry script and conda dependencies. You can find the conda dependencies by selecting your model, then go to the artifacts and download the conda.yaml file. You can upload this file during the deployment. Creating the entry script is more involved. Microsoft recommends to first create a dummy scoring script for this. Details on how to this are well documented on <a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-deploy-and-where?tabs=python#define-a-dummy-entry-script">this Microsoft page</a>. After the deployment is successful, you can change the scoring script, which is also discussed on this page. Under the advanced settings, you can set CPU and memory requirements if you want. Then click deploy and wait for the deployment to complete. In order to consume the web service, AML automatically creates a scoring script under consume. This is completely usable, however, there are two issues in my regard. The first one is the key provided in the code. It is very much advised to move this key to the Azure Keyvault (we already linked it in the first article) and get the key from there. The second issue is the format for the data. It would have been a lot easier if you could send a dataframe from Pandas or Spark instead of a Json list. However, currently this is the only AML deployment that is not in preview. Later in this article, we will discuss a way to consume a model that is not in preview and can deal with a Pandas dataframe. In my opinion, this is currently the easiest way to consume a model.</p><h3><strong>Real time endpoint</strong></h3><p>The second way to deploy a model is to deploy to a real time endpoint. Microsoft created an easier to use interface for this deployment. Just like with the web service, there are both ACI and AKS options. AML will create the environment and scoring files automatically, which makes it easier to deploy a model in this way. After selecting the compute and traffic settings, you can deploy the model. Note that deploying a model to a real time endpoint can take rather long.</p><h3>Batch endpoint</h3><p>For batching scoring, Microsoft created a different endpoint. The main advantage here is that is possible to upload a file and get the scored outcome. Therefore it becomes possible to upload for instance a parquet data file. This endpoint is particularly useful when you consume a model on a regular interval with a large dataset. Note that the last method that I will describe is also mainly focused on larger data sets on regular intervals. Currently batch scoring is still in preview and can therefore be subject to changes. The deployment is very similar to the real time endpoint deployment. This time however, you will need to provide the output type and location. Batch endpoints do not use a ACI or AKS but make use of a cluster provisioned in AML. You can select a cluster you already created or create a new one if this is preferred.</p><p>You can manually score a data set if the endpoint is deployed by selecting the endpoint and then clicking on <em>Create Job</em>. A window appears where you can select either a registered dataset in AML or select a file via a registered data store. At the moment of writing this article, it is only possible to use a filedataset according to the Microsoft documentation, but other options will hopefully be updated quickly. If you want to use the storage account of Synapse, you have to add this storage account as a linked service, then you can select it. After setting the output location, you can run the model and you will end up with a scored dataset. For up-to-date documentation for Batch endpoints, please see the <a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-use-batch-endpoint.">Microsoft documentation</a>.</p><h3>Model from registered location</h3><p>A final option for consuming a model is to load it from a registered location. The first step to do this is to register the model in AML. This helps with keeping tracking of the versions of models and creates an overview of all existing models in your environment. If you want to consume this model, you have to load it from AML to a storage, this could for instance be your Azure storage account, or the dbfs if you use Databricks. Note that storing your model in the dbfs can run into issues regarding the size of the model. Storing the model in the storage account therefore is preferred. An example on how to do this within Synapse if provided below.</p><pre>linkedService_name = &quot;LSAML1&quot;</pre><pre>from notebookutils.mssparkutils import azureML</pre><pre>ws = azureML.getWorkspace(linkedService_name)</pre><pre>model_name = &#39;yourModel-Best&#39;</pre><pre>local_model_path = &#39;abfss://data@dlweu01.dfs.core.windows.net/Models/&#39;</pre><pre>model = Model(ws, model_name)</pre><pre>LoadedModel = joblib.load(model.download(target_dir=local_model_path, exist_ok=True, exists_ok = None)+&#39;/model.pkl&#39;)</pre><pre>y_predict = LoadedModel.predict(dfToScorePandas)</pre><pre>#Add prediction to the Dataframe</pre><pre>dfToScorePandas[&#39;Prediction&#39;] = y_predict</pre><pre>dfScored = spark.createDataFrame(dfToScorePandas)</pre><p>The main advantage of this implementation is the use of a Pandas dataframe to score the data. This is a much more convenient format than the JSON lists for other endpoints. Another advantage of this implementation is that there is no endpoint, which makes it a cheaper option, especially if you plan to consume the model infrequently. For a model created with Spark MLlib, the same strategy is possible, saving and loading the model to avoid the use of AML.</p><h3>Consuming the model with Azure Databricks</h3><p>So far, we have used Synapse to create the model in Azure Machine Learning and to score the test data. However, it is also possible to for instance use Azure Databricks together with Azure Machine Learning. Although this is theoretically possible, in practice combining Databricks and Machine Learning is a lot more difficult than combining Machine Learning and Synapse. The disadvantage of Databricks is the manual step of adding the correct libraries and setting the correct versions for several Azure Machine Learning packages as well as setting the correct Python version. For AutoML to run via a Databricks cluster for instance, it is currently required to use Python version 3.6 or 3.7 instead of the default Python 3.8. You also have to specify the correct versions of the SKLearn library, which for Azure Machine Learning often is not the latest version. Although details on this can be found on the Microsoft website, this setup is lot harder and will take frequent changes to stay in tune with the current Azure Machine Learning version and its dependencies.</p><p>In this article we discussed the options to deploy and consume a model using Azure Synapse Analytics and Azure Machine Learning. In the next and last article, we will conclude this series by going over the advantages and disadvantages of Azure Synapse Analytics for a data scientist.</p><p><strong>Sources</strong></p><ul><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/concept-endpoints">What are endpoints (preview)? - Azure Machine Learning</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-consume-web-service?tabs=python">Create client for model deployed as web service - Azure Machine Learning</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-configure-databricks-automl-environment">Develop with AutoML &amp; Azure Databricks - Azure Machine Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64df36ee7789" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training a Machine Learning model with Azure Synapse Analytics]]></title>
            <link>https://medium.com/@jonathanbogerd/training-a-machine-learning-model-with-azure-synapse-analytics-8b489b780da5?source=rss-3863776b2716------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b489b780da5</guid>
            <category><![CDATA[synapse]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Jonathan Bogerd]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 07:11:35 GMT</pubDate>
            <atom:updated>2022-02-23T07:11:35.046Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will continue with the dataset that we created in the previous article to train a machine learning model on the covid data. Two options to do this will be discussed. The first option is to use the Azure Machine Learning Studio integration. This offers no-code or low-code options to train a machine learning model. The alternative is to use Spark MLlib. This requires coding but it gives more flexibility and does not require Azure Machine Learning. However, the MLlib package of Apache Spark does not contain a standard Time Series Package. Therefore, we will discuss a regression and classifier model built by using the MLlib package. The next article will discuss how to use the created models and score data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2F1OJYZX6BdrK-Kq" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">Charles Deluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>AutoML</h3><p>The first option we will use is the AutoML option in Azure Machine Learning. AutoML can be used within Azure Synapse Analytics. To do this for the training set we created, click on the <em>Data </em>tab and find the Spark tables (if you have not changed the location, they are under default). If you do not see them, please refresh the workspace by clicking the refresh button in the right corner of the workspace. Right click on the trainset, go to Machine Learning and then Train a new model. This will open a window which resembles the AutoML options in Azure Machine Learning Studio. For this example, we will use the Time series forecasting option, as this is often the most complicated to implement. Note that if you use the Azure Machine Learning Studio and create your own models without AutoML, it is not possible to use a time series model.</p><p>The first specifications we have to provide are the experiment name and best model name. In this case, I call them Covid and Covid-Best. The target column is the column we want to predict. This is in our case <em>positive_increase </em>and can be found in the drop-down menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*Q5q_I6t1BU3XGy2gfqH-GA.png" /></figure><p>The Spark pool will automatically be attached. Therefore, we do not need to generate a compute within Azure Machine Learning, as we can use the Spark pool of Synapse. After <em>continue</em> we get a new window for the time column and time series identifiers. The time column is in our case <em>date</em>. Note that this column should be in a standard datetime format for Machine Learning to understand the formatting. The time series identifier is an optional column that specifies subseries within the dataset. If you have multiple records for a specific date, you have to specify this column. In our case, the states are the identifiers such that the time series are unique. Therefore, this field is set to <em>state</em>. The maximum training time will be set to 1 hour. Note that it is not possible to set it lower than 1 hour. However, if we generate a notebook to run the pipeline, which we will do in the next step, we can manually change this to a minimum of 0.25 hours if so required. After these fields are filled in, you have two options. One is to create the run immediately in Azure Machine Learning. The other one is to open your specifications in a notebook. We will do this, as this provides us with the option of changing something if required and it will make it easier to fix any issues we encounter. We can see where the issue occurs and we can rerun the notebook to run it again.</p><p>Hopefully, it is not required to change anything and you can start with Run all. This is will send the run to Azure Machine Learning. It is possible to review the progress of the run by clicking the link that is generated in the notebook or by going to the run in Azure Machine Learning. When the run has finished, the model is automatically registered in Azure Machine Learning.</p><p>In the dataset, one potentially imported variable is missing on purpose: <em>the day of the week</em>. Including this might have a positive impact on the accuracy of the model. To add this, we only need to add this variable in the spark dataframe in the notebook: <em>Covid Data</em>. See the code fragment below:</p><pre>from pyspark.sql.functions import dayofweek</pre><pre>dfTotal = dfTotal.withColumn(&quot;dayofweek&quot;,dayofweek(dfTotal.date))</pre><p>Do not forget to import the dayofweek function from pyspark. Then, we only need to run this notebook and the machine learning notebook and we will get a registered model with the new variable included. This makes this setup really convenient, if variables will be added to the model.</p><h3>Spark MLlib</h3><p>For an implementation of machine learning models using Spark MLlib, we will use a different dataset, because our dataset is time series based. This dataset is the beforementioned data on large cities in the world. As mentioned before, currently Spark MLlib does not have time series models. Therefore, we will use both a classification model and a regression model. The dataset contains data on the largest cities in the world. Several variables are provided, such as country, latitude and longitude, population and if a city is a capital. The classification model will be trained to predict is a provided city is a capital. The regression model will focus on the number of inhabitants of a city. In order to run both models, we will need to create a new Spark pool with Spark version 3.1, in order to benefit from the newest models in MLlib. Note that the provided code does not function with Spark version 2.4.</p><h3>Classification</h3><p>After the dataset is uploaded to the storage account of Synapse Analytics, we can open it in a notebook by selecting <em>New notebook</em> and<em> Load to dataframe</em>. Note that this csv file contains a header, so this line needs to be uncommented. Next, we import the required packages and cast the columns to the correct data types. We also filter the smaller cities as they lack many variables. See the following code snippet for the exact code.</p><pre>%%pyspark</pre><pre>from pyspark.sql import SparkSession</pre><pre>from pyspark.sql.functions import *</pre><pre>from pyspark.sql.types import DoubleType</pre><pre>from pyspark.ml.stat import Correlation</pre><pre>from pyspark.ml import Pipeline</pre><pre>from pyspark.ml.classification import DecisionTreeClassifier</pre><pre>from pyspark.ml.feature import StringIndexer, VectorAssembler, OneHotEncoder,VectorIndexer</pre><pre>from pyspark.ml.evaluation import MulticlassClassificationEvaluator</pre><pre>sc = SparkSession.builder.getOrCreate()</pre><pre>df = spark.read.load(&#39;abfss://data@dlweu01.dfs.core.windows.net/worldcitiesdata.csv&#39;, format=&#39;csv&#39;</pre><pre>## If header exists uncomment line below</pre><pre>, header=True</pre><pre>)</pre><pre>df = df.withColumn(&#39;CapitalBoolean&#39;,when(df.capital == &#39;primary&#39;,lit(1)).otherwise(lit(0)))</pre><pre>df=df.na.fill(value=0)</pre><pre>df = df.withColumn(&#39;lat&#39;,df.lat.cast(DoubleType()))</pre><pre>df = df.withColumn(&#39;lng&#39;,df.lng.cast(DoubleType()))</pre><pre>df = df.withColumn(&#39;population&#39;,df.population.cast(DoubleType()))</pre><pre>df = df.filter(col(&#39;population&#39;)&gt;1000000)</pre><pre>display(df.limit(10))</pre><p>Now that the data is prepared and the required packages imported, it is time to setup the model. In this case, we will use a decision tree to classify the data. Firstly, we select the columns that we want to use for this prediction. Next, they should be split in numerical and categorical columns. In our case, only the variable <em>country </em>is categorical. For this column, we use an indexer and then an encoder to be able to use this variable. The stages list connects all the steps and makes it possible to create the pipeline of the model later on. The code for this fragment is provided below:</p><pre>df = df.select(&quot;lat&quot;,&quot;lng&quot;,&quot;population&quot;,&quot;CapitalBoolean&quot;,&quot;country&quot;)</pre><pre>cols = df.columns</pre><pre>categoricalColumns = [&#39;country&#39;]</pre><pre>stages = []</pre><pre>for categoricalCol in categoricalColumns:</pre><pre>stringIndexer = StringIndexer(inputCol = categoricalCol, outputCol = categoricalCol + &#39;Index&#39;)</pre><pre>encoder = OneHotEncoder(inputCols=[stringIndexer.getOutputCol()], outputCols=[categoricalCol + &quot;classVec&quot;])</pre><pre>stages += [stringIndexer, encoder]</pre><pre>label_stringIdx = StringIndexer(inputCol = &#39;CapitalBoolean&#39;, outputCol = &#39;label&#39;)</pre><pre>stages += [label_stringIdx]</pre><pre>numericCols = [&quot;lat&quot;,&quot;lng&quot;,&quot;population&quot;]</pre><pre>assemblerInputs = [c + &quot;classVec&quot; for c in categoricalColumns] + numericCols</pre><pre>assembler = VectorAssembler(inputCols=assemblerInputs, outputCol=&quot;features&quot;)</pre><pre>stages += [assembler]</pre><p>In the next section of code, we need to create the pipeline of the model that transforms the dataframe using the transform steps described above. This includes the encoding of categorical variables. We also need to split the data in a train and test set, in order to evaluate the results. This is done at random by using the randomSplit function of pyspark.</p><pre>pipeline = Pipeline(stages = stages)</pre><pre>pipelineModel = pipeline.fit(df)</pre><pre>df = pipelineModel.transform(df)</pre><pre>selectedCols = [&#39;label&#39;, &#39;features&#39;] + cols</pre><pre>df = df.select(selectedCols)</pre><pre>train, test = df.randomSplit([0.7, 0.3], seed = 1234)</pre><pre>print(&quot;Training Dataset Count: &quot; + str(train.count()))</pre><pre>print(&quot;Test Dataset Count: &quot; + str(test.count()))</pre><p>The last steps that we need to take is to create the actual model, save it, predict and evaluate the results. We will create a decision tree as a general classification model and we will save this model to the Synapse storage in order to use it later on. In this way, versioning of models is a bit more complicated then using Azure Machine Learning. In the last lines of code, an evaluation is performed in order to determine the accuracy of the model. Note that MLlib has many options for the decision tree, that can be found <a href="https://spark.apache.org/docs/3.1.2/api/python/reference/api/pyspark.ml.classification.DecisionTreeClassifier.html">here</a>.</p><pre>dt = DecisionTreeClassifier(featuresCol = &#39;features&#39;, labelCol = &#39;label&#39;)</pre><pre>dtModel = dt.fit(train)</pre><pre>dtModel.write().overwrite().save(&quot;abfss://data@dlweu01.dfs.core.windows.net/Models/CityDTC&quot;)</pre><pre>predictions = dtModel.transform(test)</pre><pre>predictions.select(&quot;prediction&quot;, &quot;label&quot;, &quot;features&quot;).show(5)</pre><pre>evaluator = MulticlassClassificationEvaluator(</pre><pre>labelCol=&quot;label&quot;, predictionCol=&quot;prediction&quot;, metricName=&quot;accuracy&quot;)</pre><pre>accuracy = evaluator.evaluate(predictions)</pre><pre>print(&quot;Test Error = %g &quot; % (1.0 - accuracy))</pre><h3>Regression</h3><p>Creation and training of a regression model is very similar to classification model. The data transformation part is exactly the same and will therefore not be repeated. A decision tree regression model is used for regression purposes as it is very similar to the decision tree classifier. The following code section provides the code to create the MLlib pipeline, model, test and training set and evaluation.</p><pre>df = df.select(&quot;lat&quot;,&quot;lng&quot;,&quot;population&quot;,&quot;CapitalBoolean&quot;,&quot;country&quot;)</pre><pre>cols = df.columns</pre><pre>categoricalColumns = [&#39;country&#39;]</pre><pre>stages = []</pre><pre>for categoricalCol in categoricalColumns:</pre><pre>stringIndexer = StringIndexer(inputCol = categoricalCol, outputCol = categoricalCol + &#39;Index&#39;)</pre><pre>encoder = OneHotEncoder(inputCols=[stringIndexer.getOutputCol()], outputCols=[categoricalCol + &quot;classVec&quot;])</pre><pre>stages += [stringIndexer, encoder]</pre><pre>numericCols = [&quot;lat&quot;,&quot;lng&quot;,&quot;CapitalBoolean&quot;]</pre><pre>assemblerInputs = [c + &quot;classVec&quot; for c in categoricalColumns] + numericCols</pre><pre>assembler = VectorAssembler(inputCols=assemblerInputs, outputCol=&quot;features&quot;)</pre><pre>stages += [assembler]</pre><pre>pipeline = Pipeline(stages = stages)</pre><pre>pipelineModel = pipeline.fit(df)</pre><pre>df = pipelineModel.transform(df)</pre><pre>train, test = df.randomSplit([0.7, 0.3], seed = 2018)</pre><pre>print(&quot;Training Dataset Count: &quot; + str(train.count()))</pre><pre>print(&quot;Test Dataset Count: &quot; + str(test.count()))</pre><pre>dt = DecisionTreeRegressor(featuresCol = &#39;features&#39;, labelCol = &#39;population&#39;)</pre><pre>dt.setMaxDepth(20)</pre><pre>dt.setMinInfoGain(30)</pre><pre>dtModel = dt.fit(train)</pre><pre>dtModel.write().overwrite().save(&quot;abfss://data@dlweu01.dfs.core.windows.net/Models/CityDTR&quot;)</pre><pre>predictions = dtModel.transform(test)</pre><pre>predictions.select(&quot;prediction&quot;, &quot;population&quot;, &quot;features&quot;).show(10)<br></pre><pre># Select (prediction, true label) and compute test error</pre><pre>evaluator = RegressionEvaluator(</pre><pre>labelCol=&quot;population&quot;, predictionCol=&quot;prediction&quot;, metricName=&quot;rmse&quot;)</pre><pre>rmse = evaluator.evaluate(predictions)</pre><pre>print(&quot;Root Mean Squared Error (RMSE) on test data = %g&quot; % rmse)</pre><pre>print(&quot;Depth &quot; , dtModel.depth)</pre><pre>print(&quot;MinInfoGain &quot; , dt.getMinInfoGain())</pre><p><strong>Conclusion</strong></p><p>In this article we created a model in two ways. The first way was by calling AutoML from Synapse Analytics and letting Azure Machine Learning figure out the best model for this training set. The second way was by using the MLlib library from Spark. In the next article, we will have a look on how to score data using the models we have developed.</p><p><strong>Sources</strong></p><ul><li><a href="https://docs.microsoft.com/en-us/azure/synapse-analytics/machine-learning/tutorial-automl">Tutorial: Train a model by using automated machine learning - Azure Synapse Analytics</a></li><li><a href="https://spark.apache.org/docs/latest/mllib-decision-tree.html">Decision Trees - RDD-based API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b489b780da5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>