<?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 Lina Haidar on Medium]]></title>
        <description><![CDATA[Stories by Lina Haidar on Medium]]></description>
        <link>https://medium.com/@haidarlina4?source=rss-30664d1617dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zTWceuij7zhQvbjBIYXmMA.jpeg</url>
            <title>Stories by Lina Haidar on Medium</title>
            <link>https://medium.com/@haidarlina4?source=rss-30664d1617dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:32:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@haidarlina4/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[Create Azure Compute Instance]]></title>
            <link>https://medium.com/@haidarlina4/create-azure-compute-instance-adcdefa023b6?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/adcdefa023b6</guid>
            <category><![CDATA[azure-compute-instance]]></category>
            <category><![CDATA[azure-notebooks]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Fri, 20 May 2022 16:21:26 GMT</pubDate>
            <atom:updated>2022-05-20T16:21:26.074Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is one section of the tutorial that provides a complete guide on how to bring your code to Azure cluster. This is suitable specially for advanced projects such as semantic segmentation and other deep learning projects.</p><p>Content of the tutorial:</p><ol><li><a href="https://medium.com/@haidarlina4/create-azure-machine-learning-workspace-5a28e8c60f4">Create Azure Machine Learning Workspace</a></li><li><strong>Create Azure</strong> <strong>Compute Instance (this post)</strong></li><li>Create Azure Compute Cluster</li><li>Create a Datastore</li><li>Create Datasets</li><li>Create a Virtual Environment</li><li>Initialize and Experiment</li><li>Submit and Run Experiment</li><li>Common Errors and how to handle them</li></ol><p><strong>What is Azure Compute Instance?</strong></p><p>Azure compute instance allows you to build and deploy models using integrated notebooks in Azure Machine Learning (AML) studio. The following applications can be used: <br>- Jupyter<br>- JupyterLab<br>- VS Code (preview)<br>- RStudio (preview)</p><p>This means that you can bring your training scripts to the AML studio instead of using your personal computer to train the model. However, there is a charge for using a compute instance depending on the type and the size of the virtual machine you choose, as we are going to see below.</p><p>Note that <em>Azure Compute Instance </em>is not the same as <em>Azure Compute Cluster</em>. The first is used as a replacement to your local environment. After closing the notebook, the training stops. Whereas the latter is used to submit the experiment to a remote GPU, which will train your model remotely and independently of your local machine or the compute instance.</p><p><strong>Create Azure Compute Instance:</strong></p><p>To create a compute instance, you should already have created <a href="https://medium.com/@haidarlina4/create-azure-machine-learning-workspace-5a28e8c60f4">a machine learning azure workspace</a>. After that, you can follow the steps as illustrated on the following screenshots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moS2HbtZvB9OQEUIuYyXdA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqgKF0MJHBH5il08nMfJmA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-zT1ownMVLztqTW0lcQAg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhubxNAcRvVNMu36AP4Qug.jpeg" /></figure><p>The virtual machine type and size can be chosen as desired depending on your specific needs. From financial perspective, it is better if you start with the cheapest if you are a total beginner, because you get charged per hour of <em>running</em> the compute cluster, not per <em>actually using</em> it.</p><p>The last step is to click on <em>Create</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DipuMInwbeKKfamI3DJ9pQ.jpeg" /></figure><p>Now the compute instance is created and you can move your scripts to the notebook by clicking on the tool as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fatcItIc0vnzcxw1zzBCRw.jpeg" /></figure><p><strong>Important Note:</strong></p><p>Note that, when the compute instance is running (i.e when it is <em>on</em>), it is charging as time passes, regardless of whether you are currently using it or not. Even if your computer is off, as long as the compute instance state says <em>running</em>, then you get charged. So, make sure you stop it when you no longer work on that day. You can start running it again when you come back next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adcdefa023b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Azure Machine Learning Workspace]]></title>
            <link>https://medium.com/@haidarlina4/create-azure-machine-learning-workspace-5a28e8c60f4?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a28e8c60f4</guid>
            <category><![CDATA[workspace]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Thu, 05 May 2022 14:59:29 GMT</pubDate>
            <atom:updated>2022-05-05T15:16:24.610Z</atom:updated>
            <content:encoded><![CDATA[<p>Azure Machine Learning (AML) Workspace is like your desk on which you have everything to start working on your project. AML workspace contains the tools that are needed to submit the experiment to the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*XXGMKVbSPKHIdGbx-MPD6Q.png" /><figcaption>Azure Workspace</figcaption></figure><p><strong>Create AML Workspace</strong></p><p>1. Using Azure <em>Workspace.create</em> method:</p><p>To be able to use the method, you need to<strong> </strong><a href="https://docs.microsoft.com/en-us/python/api/overview/azure/ml/install?view=azure-ml-py"><strong>install AML SDK for python</strong></a><strong>.</strong></p><pre>from azureml.core import Workspace<br>ws = Workspace.create(name=&#39;myworkspace&#39;,<br>               subscription_id=&#39;&lt;azure-subscription-id&gt;&#39;,<br>               resource_group=&#39;myresourcegroup&#39;,<br>               create_resource_group=True,<br>               location=&#39;eastus2&#39;<br>               )</pre><p>For beginners, it is relatively easier to use a user interface method, which is explained below.</p><p>2. Using Azure Portal</p><p>Sign in to the Azure Portal by using the credentials for your Azure Subscription. In the search box, type <em>Machine Learning</em> and select the matching item. Then click <em>create</em>. You should see the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*kOQ4WFWqHYhHey3rZTOaKA.jpeg" /><figcaption>create AML workspace</figcaption></figure><p>Provide the following information to configure your workspace:</p><p>. <strong><em>Subscription</em></strong>: Select Azure subscription that you want to use. If you have only one, it gets selected by default. <br>. <strong><em>Resource group</em></strong>: Use an existing one in your subscription. If it is the first time you create a workspace, enter a name to create a new resource group. <br>. <strong><em>Workspace name</em></strong>: Enter a unique name across the resource group. It is recommended to use a name which is easy to recall and to differentiate from workspaces created by others. The name is case-insensitive. <br>. <strong><em>Region</em></strong>: Select the matching location.</p><p>. Leave default values <strong><em>Storage account</em></strong><em>, </em><strong><em>Key vault</em></strong><em>, </em><strong><em>Applications insights</em></strong><em>, </em><strong><em>Container registry.</em></strong></p><p>. Then, click on <strong><em>Review + Create. </em></strong>In the <em>Validation page</em> click on <strong><em>Create</em> </strong>to start the deployment. When the deployment is terminated click on <strong><em>Go to resource.</em></strong></p><p><strong>. </strong>Finally,<strong> </strong>in the Azure Machine Learning resource page click on <strong><em>Launch studio</em>. </strong>Azure Machine Learning Studio home page will open in another tab of your browser and you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*HO3J10i1T8cinRj_izhhlg.jpeg" /><figcaption>AML Studio</figcaption></figure><p>To the left side are the tools that can be utilized in accordance with what your project needs.</p><p>This post is a section of the complete tutorial <a href="https://medium.com/p/303546e02da9/edit"><strong>Set up Azure Development Environment to Train Models</strong></a><strong>. </strong>Check it out to proceed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a28e8c60f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set up Azure Development Environment to Train Models]]></title>
            <link>https://medium.com/@haidarlina4/set-up-azure-development-environment-to-train-models-303546e02da9?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/303546e02da9</guid>
            <category><![CDATA[computer-engineering]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Thu, 05 May 2022 14:58:32 GMT</pubDate>
            <atom:updated>2022-05-20T16:22:34.160Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial provides a complete guide on how to bring your code to Azure cluster. This is suitable specially for advanced projects such as semantic segmentation and other deep learning projects.</p><p>On this page, you see the content of the complete tutorial. This helps giving an overall picture of what is needed for your project to run and it also helps you know at which stage you are. You can skip the section that you are already familiar with. The following sections are clickable and take you to their respective page.</p><ol><li><a href="https://medium.com/@haidarlina4/create-azure-machine-learning-workspace-5a28e8c60f4"><strong>Create Azure Machine Learning Workspace</strong></a></li><li><a href="https://medium.com/@haidarlina4/create-azure-compute-instance-adcdefa023b6"><strong>Create Compute Instance</strong></a><strong><br>….<br></strong><em>Note</em>: writing this tutorial is in progress<strong>. </strong>Following sections will be added:</li><li><strong>Create Compute Cluster</strong></li><li><strong>Create a Datastore</strong></li><li><strong>Create Datasets</strong></li><li><strong>Create a Virtual Environment</strong></li><li><strong>Initialize and Experiment</strong></li><li><strong>Submit and Run Experiment</strong></li><li><strong>Common Errors and how to handle them</strong></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=303546e02da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sobel vs. Canny Edge Detection Techniques: Step by Step Implementation]]></title>
            <link>https://medium.com/@haidarlina4/sobel-vs-canny-edge-detection-techniques-step-by-step-implementation-11ae6103a56a?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ae6103a56a</guid>
            <category><![CDATA[canny-edge-detection]]></category>
            <category><![CDATA[edge-detection]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Sat, 11 Sep 2021 15:46:19 GMT</pubDate>
            <atom:updated>2021-09-11T15:50:47.338Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post <a href="https://medium.com/@haidarlina4/image-gradient-concept-and-application-31c6faef45dd">Image Gradient Concept and Application</a>, we looked at the traditional edge detection algorithm with no enhancement. The main focus was to explain the concept of how the image gradient is used to detect edges in images.</p><p>Since edge detection is a fundamental step in computer vision and image processing, it is demanded to build algorithms that are accurate and robust. Several algorithms were developed for this purpose. Out of the available edge detection algorithms, Canny and Sobel techniques have the highest efficiency.</p><p>In this post, I’m going to give an overview of both algorithms and compare them with each other. The code can be found <a href="https://github.com/lina-haidar/Edge-Detection-Techniques-Sobel-vs.-Canny"><strong>here</strong></a>.</p><p>Regarding the code on <a href="https://github.com/lina-haidar/Edge-Detection-Techniques-Sobel-vs.-Canny"><strong>GitHub</strong></a>: The algorithms are implemented in two ways. At first, we will look at the step-wise approach using only <strong>Numpy</strong>. The code is long and it matches the steps mentioned in the post. In the end, we will implement the algorithms using the built-in functions in <strong>OpenCV</strong>.</p><h3>Sobel</h3><p>Sobel operator estimates the gradient magnitude and direction at each pixel in a grayscale image. Pixels that have high magnitude form an edge.</p><h4>Sobel Operator</h4><p>The Sobel operator is obtained by doing some manipulations to the x and y derivatives, that we looked at in the previous post. To obtain the Sobel derivative along the x-direction, we perform an outer product between a 1D Gaussian filter and the x derivative. The Sobel y filter is obtained by performing an outer product between the y derivative and a 1D Gaussian filter. The following figures illustrate the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a8h9CmAcIAYgq7hq.png" /><figcaption>Sobel-x</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CeIAzL1piphDHrzj.png" /><figcaption>Sobel-y</figcaption></figure><p>The Gaussian filter is used for reducing noise that results in blurred images. Thus, the Sobel operator computes the image gradient with less noise.</p><h4>Sobel Algorithm</h4><p>The Sobel algorithm can be summarized in four steps:</p><ol><li>Converting the image into grayscale</li><li>Convolving the gray image with Sobel-x filter</li><li>Convolving the gray image with Sobel-y filter</li><li>Calculating the gradient magnitude and direction</li></ol><h3>Canny</h3><p>The Canny algorithm was introduced to further enhance edge detection. Its implementation is relatively more complicated than Sobel’s, but it has its advantages that we will look at in the comparison section.</p><h4>Canny Algorithm</h4><p>The Canny algorithm can be summarized in five steps:</p><ol><li><strong>Blurring the grayscale image</strong><br>To blur the image, I implemented a Gaussian filter.</li><li><strong>Finding the gradient magnitude and direction</strong><br>To calculate the image gradient, the Sobel operator is implemented, basically, steps 2–4 of the Sobel algorithm discussed above.</li><li><strong>Non-maxima suppression</strong><br>This step is also known as edge thinning because it preserves the sharpest gradients and discards the others. The algorithm is implemented pixel-wise, given the gradient magnitude and direction. The gradient magnitude of the current pixel is compared with the magnitude of the neighboring pixels that point in the same direction. The direction is rounded to four angles: 0, 45, 90, and 135. For example, the angle is rounded to zero if it is in the range [0°,22.5°] or [157.5°, 180°]. The range of the direction (atan) is -π/2 to π/2, but the sign in this algorithm is irrelevant. For example -π/2 and π/2 are considered to have the same direction.<br><strong>The algorithm for a given pixel [i,j] is explained visually as follows:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eD6Yjmfsv904ma6_.png" /><figcaption>Case 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aymog_AtWZGoMwb5.png" /><figcaption>Case 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fHviE8aq4E2EjMWD.png" /><figcaption>Case 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q14vNW4AINqkDTkx.png" /><figcaption>Case 4</figcaption></figure><p>One important thing to keep in mind is that we use the direction of the gradient at the pixel that is being processed in the “if” statement to update the magnitude of the gradient at the same pixel. The edge is perpendicular to the direction of intensity change. Also, note that the x-coordinate axis of a digital image runs from left to right and the y-coordinate axis runs from top to bottom.</p><p><strong>4. Double Threshold <br></strong>While the previous step aims at suppressing or preserving the gradient of the pixel being processed relative to its neighboring pixels pointing in the same direction, this step considers the strength of the magnitude in the entire image. The algorithm classifies the magnitude in three categories strong, weak, and non-edge pixels. This is done by empirically choosing two thresholds:</p><ul><li>the pixels that have a gradient magnitude less than the low threshold are discarded, i.e their values are set to zero.</li><li>the pixels that have a gradient magnitude higher than the high threshold are chosen to be strong edges and they appear in the final result.</li><li>if the strength of the magnitude falls in between the two thresholds, it is considered to be a weak edge. Weak edges are either taken to the strong edges group or to the non-edge group. To decide on that, another algorithm is used, which is discussed in the final step.</li></ul><p><strong>5. Edge tracking by hysteresis</strong><br>This is the final step of the Canny edge detection algorithm and it is used to decide whether to consider a weak edge in the final result or not. Weak edges could be meaningful but they are just not as strong as strong edges. Or, they are just caused by noise and therefore they need to be removed. Normally, true edges are connected to the strong edges while the one that is caused by noise is not connected. Based on that, the algorithm goes as follows:</p><p>For each of the weak edges, compare the magnitude of the pixel being processed with its eight surrounding pixels. If at least one of these pixels belongs to the strong edges group, the value of the pixel being processed is preserved. Otherwise, it is discarded.</p><h3>Sobel vs. Canny</h3><p>The main advantages of the Sobel operator are that it is simple and more time-efficient. However, the edges are rough. On the other hand, the Canny technique produces smoother edges due to the implementation of Non-maxima suppression and thresholding. The downside of the Canny algorithm is that it is more complex and less time-efficient than Sobel. Knowing these differences is helpful in deciding which technique is better for a particular application.</p><p>The following images summarize the differences between Sobel and Canny edge detection applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*lekVAnbm8GrQcxEAHspMPA.jpeg" /><figcaption>Left: input image, middle: Sobel , right: Canny</figcaption></figure><p>To the left side is the original image already converted into grayscale. The middle image is the result of applying the Sobel operator on the grayscale image. The image on the right side is the result of the Canny algorithm.</p><p>The code that generated the above results can be found in my <a href="https://github.com/lina-haidar/Edge-Detection-Techniques-Sobel-vs.-Canny"><strong>GitHub</strong></a> account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ae6103a56a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Gradient Concept and Application]]></title>
            <link>https://medium.com/@haidarlina4/image-gradient-concept-and-application-31c6faef45dd?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/31c6faef45dd</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[edge-detection]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Sat, 11 Sep 2021 15:12:42 GMT</pubDate>
            <atom:updated>2021-09-11T15:50:55.996Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I am going to explain what it really means to find the derivative of an image, the method to calculate the image gradient, and how to use it for edge detection using <strong>python</strong>.</p><p>Note: the code of this article can be found on my <a href="https://github.com/lina-haidar/Image-Gradient-with-Python"><strong>GitHub</strong></a><strong> </strong>page<strong>.</strong></p><h3>Image Gradient</h3><p>The derivative of a function measures the rate of change of the function with respect to its independent variable. It is also referred to as the slop of the function. Functions can be continuous or discrete. A digital image is an example of 2D discrete functions.</p><h4>One Dimensional Functions</h4><p>A 1D image can be seen as a row of some pixels, such as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R8UrDdY024UtKDsY.png" /><figcaption>1D digital image</figcaption></figure><p>These discrete values represent the color intensity and the derivative of the entire row represents the intensity change as we move from one pixel to another.</p><p>Among the methods that are used to approximate the first derivative of a discrete function, the central finite difference gives the best results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*3D0_f7dWXDeMVDKb" /><figcaption>Central finite difference</figcaption></figure><p>This is also the same as applying a 1D filter on the image, which is known as convolution.</p><p>Applying the above method on our 1D digital image yields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ouuFLTNiu-bXQVr8.png" /><figcaption>Image gradient (1d)</figcaption></figure><h3>Two Dimensional Functions</h3><p>For multivariable functions, partial derivative measures the rate of change with respect to each of the independent variables. It is also referred to as the gradient of the function. The gradient of a 2D image <em>I(x,y)</em> is formed by combining the partial derivatives of the image in the <em>x </em>direction and <em>y </em>directions as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*mp6NnATicEgiR3zr" /><figcaption>Gradient of a 2D image</figcaption></figure><p>The first term measures the rate of change of pixel intensity in the <em>x</em> direction and it is approximated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*X4deOuh1CTrsGPy-" /><figcaption>Partial derivative in the <em>x</em> direction</figcaption></figure><p>The second term of the gradient measures the rate of change of pixel intensity in the <em>y</em> direction and it is approximated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*2mYkBEjWqvD_rAKe" /><figcaption>Partial derivative in the y direction</figcaption></figure><p>Similar to our example of the 1D image, the partial derivatives can be calculated by convolving the image with <em>x</em> and <em>y</em> filters individually. By using the central finite difference method, the <em>x</em> and <em>y </em>filters are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*aQCJHJGfg0IOpdYu.png" /><figcaption>2D x- and y-filters</figcaption></figure><h3>Properties of the Image Gradient</h3><p>When convolving a grayscale image with the <em>x</em> and <em>y </em>filters, we get two output feature images. One describes the rate of intensity change horizontally and the other describes the rate of change vertically.</p><p>For each corresponding pixel position of those feature images, we can calculate the gradient magnitude and its direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/0*vWRyoVhaxjeZaEr2" /><figcaption>Gradient magnitude</figcaption></figure><p>The magnitude is the amount of intensity change at a given pixel. The higher the value, the higher the change. As we shall see in the implementation section in this post, the magnitude is used to detect edges in the image.</p><p>The direction of the gradient tells us the direction of the intensity change at a given pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/0*H0lE3lI4jEZoERYB" /><figcaption>Direction of the gradient</figcaption></figure><h3>Implementation of Image Gradient for Edge Detection</h3><p>In this section, we are going to make use of image gradient in edge detection, which is one of the fundamental tools in image processing and computer vision.</p><p>Technically, an edge is a border or the frame of an object. In terms of colors, an edge is a region (line or point) where the color changes. Mathematically, an edge is the change of numbers when moving from one pixel to another; in other words, it is the gradient of the image.</p><p>The result of convolving the image with the <em>x</em> and <em>y</em> filters is two feature images with only black and white colors. The white color indicates the edges. The rest is just black.</p><p>The partial derivative of the image with respect to the <em>x </em>axis (or the rows) detects the vertical edges. This is also the same as convolving the image with the <em>x</em> filter. The horizontal edges are detected by convolving the image with the <em>y </em>filter.</p><p>In order to combine both feature images (the vertical and the horizontal edges), the magnitude is used. Higher magnitudes indicate the presence of edges. For images with simple shapes such as only a square, it suffices to use the magnitude with no further editing to find the edges. However, in more complex images, the wide range of pixel intensity results in a wide range of magnitude. As a result, the output looks messy. In this case, we pick up values of the magnitude above a certain threshold.</p><p>In summary, the pseudo algorithm to find the edges is:</p><ul><li>Convert the image into grayscale</li><li>Convolve the image with the <em>x</em> filter</li><li>Convolve the image with the <em>y </em>filter</li><li>Compute the magnitude</li><li>Apply a threshold on the magnitude</li></ul><p>That was all about the theory of using calculus to find edges on images. The implementation can be found on my <a href="https://github.com/lina-haidar/Image-Gradient-with-Python"><strong>GitHub</strong></a> account.</p><p>Please note that the above algorithm and the code are fundamental. The purpose of them is mainly to explain the concept of the image gradient. This algorithm was further developed. The famous edge detection techniques out there are Sobel and Canny edge detection. Each has its pros and cons. We will look at them in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31c6faef45dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Convert an Image into a Sketch (step by step)]]></title>
            <link>https://medium.com/@haidarlina4/tutorial-convert-an-image-into-a-sketch-step-by-step-e00e2f312521?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e00e2f312521</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 20:59:49 GMT</pubDate>
            <atom:updated>2021-09-09T10:50:29.818Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’m going to walk you through how to convert an image into a sketch, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*42moae8pUvMDxJAk8Q4sDA.jpeg" /><figcaption>Input and output images</figcaption></figure><p>I sectioned this article into two parts. In the first section, I explain the steps in details and I provide the code for these steps using only <strong>numpy</strong>. In the second section, I use the advanced method, which using the python library <strong>OpenCV</strong>.</p><h3><strong>Step by Step Photo Sketching Using Numpy</strong></h3><h4>Step 1: convert the image into grayscale</h4><p>A digital color image has three channels Red Green and Blue. Each channel has a density that goes from zero to one. The color that we see is a combination of the three channels. To convert the color image into grayscale, a mathematical operation is done on these channels. Depending on the approach, two methods are covered here.</p><ul><li>Average method: <br> In this method, the average of the three channels of the colored images is taken. <br> gray_image = (R+G+B)/3<br>The way it is done using numpy is shown below:</li></ul><pre>for i in range(image.shape[0]):<br>    for j in range(image.shape[1]):<br>      gray_image[i,j] =  np.clip( (image[i,j,0] + image[i,j,1] <br>                        + image[i,j,2] )/3, 0, 255)</pre><ul><li>Luminosity method:<br>In this method, a weighted average is taken. 0.07 for the red channel, 0.72 for the green channel, and 0.21 for the blue channel. <br> gray_image = 0.07R + 0.72G + 0.21B.<br>Below is the code for this method:</li></ul><pre>for i in range(image.shape[0]):<br>    for j in range(image.shape[1]):<br>      gray_image[i,j] = np.clip(0.07 * image[i,j,0]  <br>                + 0.72 * image[i,j,1] + 0.21 * image[i,j,2], 0, 255)</pre><p>You can experiment with both methods to see the difference. The average method treats the three channels equally but the human eyeballs react differently to each of them. Furthermore, the wavelength of the colors differs. For the red color, it is 650-700 nm. For the green, it is 550 nm, and for the blue, it is 450 nm. As you will notice, the output image of the average method is relatively darker because the contribution of the colors is not equal due to the difference in the wavelengths. The luminosity method takes care of the problem.</p><h4>Step 2: Blur the gray image:</h4><p>A popular filter to blur images is the <strong>Gaussian filter</strong>. Let’s look at how to initialize a 3x3 filter in theory and in code. First, construct the mesh as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BdettKWpCEknDEqvFjsgMQ.png" /><figcaption>3x3 mesh</figcaption></figure><p>Then apply the Gaussian function (ex.: with sigma=10) as explained below visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*OfWd4xicxPP0xvLZJ6EPXQ.png" /><figcaption>Creating Gaussian filter</figcaption></figure><p>After you complete the calculation for all the values of x and y, you get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BypKKOnoo2k5KLXgl8L06A.png" /><figcaption>Gaussian filter</figcaption></figure><p>The final step is to normalize the above filter. To implement the steps using numpy, have a look at the following function:</p><pre>def initialize_kernel(size , sigma): <br>    &quot;&quot;&quot; This function initializes a Gaussian kernel with the desired<br>        size and sigma.<br>    &quot;&quot;&quot;                                                                                         <br>    w, h = size                                                  <br>    x = np.linspace(-1,1,w)                         <br>    y = np.linspace(-1,1, h)                         <br>    x_cor, y_cor  = np.meshgrid(x, y) <br>    kernel = 1/(2*np.pi*np.power(sigma,2) )*<br>             np.exp((- (x_cor ** 2 + y_cor ** 2) )/ <br>             (2*np.power(sigma,2)))</pre><pre>&quot;&quot;&quot; Gaussion function: 1/(2 *pi*sigma^2) e^(-(x^2+y^2)/2sigma^2) &quot;&quot;&quot;</pre><pre>    kernel = kernel/np.sum(kernel) # normalization</pre><pre>    print(kernel)<br>   # ax.plot_surface(x_cor, y_cor, kernel)<br>   # plt.show()<br>   # print(kernel)</pre><pre>    return kernel</pre><p><strong>To get the blurred image, we convolve the gray image with the constructed Gaussian filter</strong>. The algorithm of convolving an image is:</p><ul><li>Add a frame of zeros to the original image (this is called <strong>padding</strong>).</li><li>Place the filter on the very top left edge of the image. Perform a dot product between the filter and the corresponding values of the image (on which the filter is placed). The resulted value is the new value at the index (0,0) of the resulted (blurred) image.</li><li>Move the filter one pixel to the right and perform a dot product again. The resulted value is placed at the index (0,1) of the output image.</li><li>Keep moving the filter from the left to the right and from the top to the bottom of the image, and then store the result of the dot product at the same index on the output image. This movement is called <strong>stride</strong>. When we move by only one pixel at a time, then stride is equal to one.</li></ul><p>Below is an example of how to implement convolution using numpy:</p><pre>def padding(image):<br>    padded_image = np.pad(image , ((1,1),(1,1)) , &#39;constant&#39;,<br>                   constant_values=(0,0) ) <br>    return padded_image  <br>                                              </pre><pre>def conv2d(image, ftr):                           <br>    s = ftr.shape + tuple(np.subtract(image.shape, ftr.shape) + 1)<br>    sub_image = np.lib.stride_tricks.as_strided(image, shape = s,<br>                strides = image.strides * 2)<br>    return np.einsum(&#39;ij,ijkl-&gt;kl&#39;, ftr, sub_image)</pre><p>Putting it all together, here is how to blur the image by calling the functions explained above:</p><pre>def blurring_image(gray_image):<br>    # blur the gray_image by a Gaussian function<br>    blured_image = conv2d( padding(gray_image),<br>                           initialize_kernel((3,3) , 10) <br>    # display the result<br>    cv2.imshow(&#39;image&#39;,blured_image/255)<br>    cv2.waitKey(0) <br>                                                <br>    return blured_image</pre><h4>Step 3: Divide the gray image by the blurred image</h4><p>This is the final step. It combines the output of step 1 and step 2 of this article. Here is one line of code to perform the division.</p><pre>np.divide(gray_image, blurred_image)</pre><p>This is the end of the first section. We looked at how to make a sketch of an image using only numpy. The code is long but relatively easier to understand. We are not treating anything here as a black box.</p><h3>Photo Sketching Using OpenCV</h3><p>This is the advanced section. We are going to follow the same steps in the previous section (steps 1–3), but in a shorter way. The following three lines of code describe the implementation:</p><pre># step 1: convert to grayscale                       <br>gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) <br>                                                                                           # step 2: blur the image                                               blurred_image = cv2.GaussianBlur( gray_image , (3,3), 10 )                                                <br>                                                                     # step 3: divide the gray image by the blurred image                                               sketched_image = np.divide(gray_image , blurred_image)                                               </pre><p>Now, you can convert your photos into a sketch. When I first learned this method, I felt accomplished, given that I can already sketch using a pencil.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e00e2f312521" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means Clustering with Scikit-learn]]></title>
            <link>https://medium.com/@haidarlina4/k-means-clustering-with-scikit-learn-70c805230646?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/70c805230646</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 19:56:31 GMT</pubDate>
            <atom:updated>2021-09-01T01:24:07.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ruqF282SiWPzA6RX" /><figcaption>Photo by <a href="https://unsplash.com/@nathananderson?utm_source=medium&amp;utm_medium=referral">Nathan Anderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Objective</strong>: This article shows how to cluster songs using the K-Means clustering step by step using <em>pandas</em> and <em>scikit-learn</em>.</p><p><strong>Clustering</strong> is the task of grouping similar objects together. Each cluster contains similar objects but the label is unknown and hence clustering is an unsupervised machine learning task. One of the most popular algorithms of clustering is the K-Means algorithm.</p><p>The<strong> K-Means</strong> algorithm is based on picking <em>k </em>number of random data points and assigning them as the initial centroids of the <em>k </em>clusters. Then, the algorithm takes the other data points and it calculates their distances to each of the centroids. A data point gets assigned to the cluster whose centroid is the closest to this data point. In the second iteration, the algorithm updates the centriods and re-assigns the other data points to clusters based on their distance to the updated centriods, and so on.</p><p>Implementing a machine learning project consists of sequential steps. In this project, I followed this <strong>outline</strong>:</p><ul><li><strong>Load the Data</strong></li><li><strong>Pre-process the Data</strong></li><li><strong>Choosing the Right Number of Clusters</strong></li><li><strong>Apply KMeans Clustering Method</strong></li></ul><p>Each of these steps are explained in details below.</p><h3><strong>Load the data</strong></h3><p>You can download the data from my <a href="https://github.com/lina-haidar/clustering_songs_kmeans"><strong>GitHub link</strong></a>. The data includes 5000 songs taken from <strong>Spotify</strong>. We can read and view the data using the python library <em>pandas</em>:</p><pre>import pandas as pd<br>songs = pd.read_csv(&#39;data/df_audio_features_5000.csv&#39;)</pre><h3><strong>Pre-process the Data</strong></h3><p>Before passing the data into any model, it is necessary to check that it is clean. When the input to the model is garbage, the output is also garbage. There is no surprise here.</p><p>Let’s print the head of the data-frame and do some explorations.</p><pre>songs.head()</pre><p>The output is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS_qC_DrPlC3bXVgB0KIIg.jpeg" /><figcaption>head of our data-frame</figcaption></figure><ul><li><strong>drop the unnecessary columns</strong></li></ul><p>The columns are the features of each of the songs whose names and artists are provided. What is important to know from this data-frame is to check the possible values that each feature has. That is because they affect the convergence of the model. It is better to exclude the columns that do not make sense in terms of using them as features to cluster the songs. For example, the duration of the song does not tell its genre.</p><p>By looking at the features, I’ve dropped these features [‘key’,’mode’, ‘duration_ms’ , ‘time_signature’] by using the <strong><em>drop</em></strong> method of <em>pandas</em>.</p><pre>songs.drop([&#39;key&#39;,&#39;mode&#39;, &#39;duration_ms&#39; , &#39;time_signature&#39;], axis=1, inplace = True)</pre><ul><li><strong>Set the columns <em>name</em> and <em>artist</em> as index</strong></li></ul><p>Since K-Means clustering works on numbers, the first two columns must be dealt with. We do not want to drop them otherwise we can not identify the songs anymore. Therefore, we will set them as the index of the data-frame:</p><pre>songs.set_index( [&#39;name&#39;, &#39;artist&#39;], inplace = True)</pre><ul><li><strong>Check for missing values</strong></li></ul><p>Next, check if the observations do not contain missing values. The K-Means algorithm will raise a value error when performing math calculations on NaN values. Let’s verify that our data-frame does not have missing values:</p><pre>songs.isnull().sum()</pre><p>The output is 0 for all of the columns, which means we are fine! There is no further work to be done here.</p><ul><li><strong>Apply transformation</strong></li></ul><p>The differences in the ranges of the features create a bias in that a feature that takes large values has a higher weight, and hence a higher influence on the algorithm. What we want is to let the model treat all the features equally without preferences. To do that, we need to normalize the data.</p><h3><strong>Choosing the Right Number of Clusters</strong></h3><p>One of the inputs to the k-means cluster algorithm is the number of the desired clusters we would like to have as the output. When the data is huge and is multidimensional, it is not trivial to decide on the number of the clusters.</p><p>One of the methods that helps in choosing the number of clusters is the <strong>Inertia Method</strong>. The inertia is the mean squared distance of the each instance from their nearest centroid. Since each cluster contains points that are close to each other, it makes sense to choose the right number of clusters when the inertia is small. However, the inertia keeps exponentially decreasing with respect to number of clusters (i.e. inertia = 0 when the number of clusters is equal to the number of data points). Therefore, the candidate for the number of clusters is chosen to be at the <strong>elbow</strong> of the curve of the inertia.</p><p>The other approach that is used to find the number of clusters is the <strong>Silhouette Coefficient Method</strong>. It is more precise than the inertia approach because its curve with respect to different number of clusters gives the highest score at the best number of clusters.</p><p>Below is a the code to visualize the curves of the two methods with respect to the number of clusters <em>k </em>using the same data.</p><pre># NOTE: input to this code is: &quot;k&quot;, &quot;sil_score&quot;, and &quot;inertia_list&quot;</pre><pre>fig, axs = plt.subplots(2)<br>fig.suptitle(&#39;Optimal number of clusters&#39;)<br>axs[0].plot(k , sil_score)<br>axs[0].scatter(k , sil_score, marker=&#39;x&#39;, color = &#39;red&#39;)<br>axs[0].set_ylabel(&#39;sil_score&#39;)<br>axs[0].set_xticks(k)<br>axs[1].plot(k , inertia_list)<br>axs[1].scatter(k , inertia_list, marker=&#39;x&#39;, color = &#39;red&#39;)<br>axs[1].set_ylabel(&#39;inertia&#39;)<br>axs[1].set_xticks(k)<br>axs[1].set_xlabel(&#39;k&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*D_N_OCe6tDhktFEQTSu8nA.png" /></figure><p>By looking at the inertia and the silhouette coefficient plot, it does not seem trivial to choose the best number of clusters. While number 5 seems at the elbow, 7–10 are also not too bad.</p><p>Let’s see what the <strong>silhouette diagram</strong> tells us. Below is the code that generates the diagram given the <em>data</em>:</p><pre>from yellowbrick.cluster import SilhouetteVisualizer</pre><pre>fig, ax = plt.subplots(2, 2, figsize=(25,20))<br>axli = ax.flatten()<br>j = 0<br>for i in [ 7, 8, 9, 10]:</pre><pre>  &#39;&#39;&#39;<br>    Create KMeans instance for different number of clusters<br>  &#39;&#39;&#39;</pre><pre>  km = KMeans(n_clusters=i, init=&#39;k-means++&#39;, <br>        n_init=10,   max_iter=100, random_state=42)</pre><pre>  &#39;&#39;&#39;<br>  Create SilhouetteVisualizer instance with KMeans instance<br>  Fit the visualizer<br>  &#39;&#39;&#39;<br>  visualizer = SilhouetteVisualizer(km, colors=&#39;yellowbrick&#39;, <br>               ax=   axli[j] )<br>  visualizer.fit(data)<br>  visualizer.finalize()<br>  j+=1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-eIzy9wiWj_HZL15rskFw.png" /></figure><p>The silhouette diagram provides nice results for using 9 clusters. Furthermore, I choose to use 9 clusters because the songs are 5000 and it makes sense that they include many genres.</p><p><strong>Apply KMeans Clustering Method</strong></p><p>After choosing the desired number of clusters, we are ready to call the KMeans function using our data:</p><pre>clusters, centroids = KMeans_cluster(transformed_data, 9)</pre><p>Here is the function:</p><pre>def KMeans_cluster(data, k):</pre><pre>    # 2. initialize the model</pre><pre>    my_kmeans = KMeans(n_clusters= k)</pre><pre>    # 3. fit the model to the data</pre><pre>    my_kmeans.fit(data) # pass your scaled data here</pre><pre>    # 4. obtain the cluster output</pre><pre>    clusters = my_kmeans.predict(data) # pass your scaled data here</pre><pre>    centroids = my_kmeans.cluster_centers_</pre><pre>    return clusters,  pd.DataFrame(centroids)</pre><p>We can directly add the clusters to the data-frame for easier analysis of the results.</p><pre>transformed_data[&quot;cluster&quot;] = clusters</pre><p>Now the data-frame has the cluster number for each of the songs. To be precise, you can replace the number of each cluster by the actual name of the genre. This requires listening to some songs from each cluster.</p><p>You can download the code and the data at my <a href="https://github.com/lina-haidar/clustering_songs_kmeans"><strong>GitHub link</strong></a>.</p><p>I hope you find this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70c805230646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate the data pipeline using Lambda]]></title>
            <link>https://medium.com/@haidarlina4/automate-the-data-pipeline-using-lambda-c1627b76b72d?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1627b76b72d</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Tue, 10 Aug 2021 19:14:30 GMT</pubDate>
            <atom:updated>2021-08-11T01:46:07.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0MaA5ja9I_uEVH2" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the last section of the project<a href="https://medium.com/codex/automating-an-end-to-end-data-pipeline-on-aws-cloud-7b5489e2925d"> <strong>Automating an end-to-end data pipeline</strong></a>. In the previous posts, we looked at how to use python scripts to collect data using web scraping and APIs and how to create a MySQL database and fill it with the data we collected. In this post, we are going to look at how to automate this project, i.e. setting a time schedule to automatically run the python scripts that include getting the data and inserting it into MySQL database.</p><p>The goal of this post is:</p><ol><li>setting up a database on AWS RDS,</li><li>running the Python scripts for data collection on AWS Lambda, and</li><li>schedule the scripts to run automatically with AWS Cloudwatch.</li></ol><p>These goals seem too much to cover on one post. However, my intention is to give an overview of the big picture so that we won’t get lost in the little details and deviate from the ultimate goal. This is not to say that we will skip the required steps as we go on. If those steps are covered somewhere else, a link will be provided. I hope this helps in producing a cleaner and easy-to-follow structure.</p><p>To be able to follow along, you need to have an <a href="https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Fportal.aws.amazon.com%2Fbilling%2Fsignup%2Fresume&amp;client_id=signup&amp;code_challenge_method=SHA-256&amp;code_challenge=GVS2Wj9_iTUGjPQYP_jg-hOtvEmxgVq1kg3c9CSW710#/start"><strong>AWS account</strong></a>.</p><p><strong>Set up a Database on AWS RDS</strong></p><p>The database we created in the post: <a href="https://medium.com/codex/create-a-database-on-mysql-workbench-24f44ba0a902"><strong>Create a Database on MySQL Workbench</strong></a><strong> </strong>was done locally on our computer. In this section we will set up a database on AWS RDS (Relational Database Service). From the AWS services, click on RDS to create a database and fill in the required fields.</p><p>Once the RDS MySQL instance is set up, we need to establish the connection to it. From MySQL workbench, create a new connection by clicking on the <em>plus</em> sign beside <em>MySQL Connections </em>and provide the required information:</p><ul><li><em>Connection name</em>: it can be any .</li><li><em>Hostname</em>: this is the instance endpoint from the AWS Console</li><li><em>Port</em>: it’s always 3306</li><li><em>Username</em>: the default when creating the database is “admin”, unless you changed it!</li><li><em>Password</em>: the password you set when creating the AWS instance</li></ul><p>Now, you can connect to your cloud instance you just created. By now, the connection is set up but there is no database. You can either create a new database of your choice or make a copy of databases that already exist in another connection. In our case, we can move the database that we created in this post <a href="https://medium.com/codex/create-a-database-on-mysql-workbench-24f44ba0a902"><strong>Create a Database on MySQL Workbench</strong></a><strong> </strong>to the new connection.<br>The only difference is that this database is now on the AWS cloud and not on the local host.</p><h4><strong>Run Python Scripts on AWS Lambda</strong></h4><p>In our project, we created five tables. Three of them are static. This means that the data does not need to get updated over time. These tables include information about the names of cities, countries they belong to, names of their airports and so on. The other two tables of our project are the flights and the weather forecasts tables. Those tables need to be updated over time. For that reason, we use Lambda functions such that these tables get updated automatically without further interference.</p><p>In the first two sections of this project, we already wrote python scripts to collect the flights data and the weather forecasts and insert the values on the local database. In this section we do two additional steps.</p><p>We first need to edit the Python connector to include our database on the cloud rather than the local one. To do so, use:</p><pre># import the library<br>import mysql.connector</pre><pre># create a connection to the MySQL server through connect()<br>cnx = mysql.connector.connect(</pre><pre>user=&#39;admin&#39;, # it is &quot;admin&quot; if you did not change the default name while creating the RDS instance</pre><pre>password=&#39;your_root_pwd&#39;, # the password you set while creating the RDS instance</pre><pre>host=&#39; &#39;, #  this is the instance endpoint from the AWS Console </pre><pre>database=&#39;db_name&#39; # the name of the database you want to connect to</pre><pre>)</pre><pre># cnx is a MySQLConnection object</pre><pre># connect to database<br>cursor = cnx.cursor()</pre><p>Then, create Lambda functions. These functions are going to be our python scripts that are used to collect the flights and weather forecasts information. Creating a lambda function involves several technical steps need to be followed. Here, I’ve provided the links that serve the purpose.</p><p><strong>Steps to create a lambda function:</strong></p><ol><li><strong>Create a role</strong>: To create a role, follow this link: <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html#roles-creatingrole-user-console">Creating a role to<br>delegate permissions to an IAM user</a>.</li><li><strong>Create a Lambda function</strong>: Follow the steps in this link <a href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html#gettingstarted-zip-function">Create<br>a Lambda function with the console</a>. Since we have python scripts,<br>choose <em>python</em> for Runtime.</li><li><strong>Upload a Layer to your Lambda function</strong>: This is like creating a virtual environment for the modules that the lambda function will be using. To upload a layer, from your local machine, create a zip<br>file of the <em>sitepackages</em> of your virtual environment. On the lambda function console, click on <em>Add a layer</em> &gt;<em> create a new layer</em>. Fill in the boxes and upload the zip file and hit create.</li></ol><p>Now we are done setting up our lambda function and it is ready to be executed. As I mentioned before, the lambda function is nothing but our python script that we created in the previous post. So, with the new modifications, the script to get the flights information looks like the following:</p><pre>import mysql.connector<br>import requests<br>from datetime import datetime , timedelta</pre><pre>def lambda_handler(event, context):</pre><pre>    tomorrow  = (  datetime.today() <br>                 + timedelta(days=1)).strftime(&quot;%Y-%m-%d&quot;)<br>    from_time =  (  tomorrow) + &quot;T09:00&quot;<br>    to_time   =  (tomorrow ) + &quot;T20:00&quot;</pre><pre>    url =&quot;https://aerodatabox.p.rapidapi.com/flights/airports   /icao/EDDB/&quot; + from_time+ &quot;/&quot; + to_time</pre><pre>    querystring =  {&quot;withLeg&quot;:&quot;true&quot;,&quot;direction&quot;:&quot;arrival&quot;,<br>                    &quot;withCancelled&quot;:&quot;false&quot;,<br>                    &quot;withCodeshared&quot;:&quot;false&quot;,<br>                    &quot;withCargo&quot;:&quot;false&quot;,<br>                    &quot;withPrivate&quot;:&quot;false&quot;}</pre><pre>    headers     = {&#39;x-rapidapi-key&#39;: &quot;your key&quot;,<br>                   &#39;x-rapidapi-host&#39;: &quot;aerodatabox.p.rapidapi.com&quot;}</pre><pre>    response = requests.request(&quot;GET&quot;, url,<br>                   headers=headers, params=querystring)</pre><pre>    arrivals   = response.json()[&#39;arrivals&#39;]</pre><pre>    flight_num = [arrival[&#39;number&#39;] for arrival in arrivals]</pre><pre>    arrival_time = [arrival[&#39;arrival&#39;]<br>                   [&#39;scheduledTimeUtc&#39;].replace(&#39;Z&#39;,&#39;&#39;)   <br>                    for arrival in arrivals]</pre><pre>    arrival_icao = (&#39;EGLL,&#39; * len(flight_num)).split(&#39;,&#39;) <br>               </pre><pre>    departure_icao = []</pre><pre>    for arrival in arrivals:</pre><pre>        try:</pre><pre>            departure_icao.append(arrival[&#39;departure&#39;]<br>                           [&#39;airport&#39;][&#39;icao&#39;])</pre><pre>        except:</pre><pre>            departure_icao.append(&quot;nan&quot;)</pre><pre>    # inserting values of flights into mysql<br>    # connect to database<br>    # define connection details</pre><pre>    cnx = mysql.connector.connect(</pre><pre>    user=&#39;admin&#39;,</pre><pre>    password=&#39;your password&#39;</pre><pre>    host=&#39;your host&#39;, # to connect to your local instance</pre><pre>    database=&#39;gans&#39; # the database you want to connect to</pre><pre>   )</pre><pre>    cursor = cnx.cursor()</pre><pre>    for i in range(len(flight_num)):</pre><pre>        value = (flight_num[i], departure_icao[i], <br>                arrival_icao[i], arrival_time[i] )</pre><pre>    query = &#39;INSERT INTO flights (flight_num, departure_icao,<br>            arrival_icao, arrival_time) VALUES (%s, %s, %s, %s);&#39;</pre><pre>    for i in range(len(flight_num)):</pre><pre>        value = (flight_num[i], departure_icao[i], <br>                 arrival_icao[i], arrival_time[i]  )</pre><pre>        cursor.execute(query, value)</pre><pre>    cnx.commit()<br>    cursor.close()<br>    cnx.close()</pre><p>You still need to click on <em>Test</em> to execute the function. This means, we are not done yet! We need to perform one last step to let this function run at a time we specify. Let’s move to the next section.</p><p><strong>Set up AWS Cloudwatch</strong></p><p>The last step of this project is to schedule the lambda functions to run periodically. To set up AWS Couldwatch, follow the steps on this tutorial: <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html">Schedule AWS Lambda Functions Using CloudWatch Events</a>.</p><p>Now, your functions will get executed on a regular basis and at the time you<br>have specified.</p><p>Congrats! You’ve just automated an end-to-end data pipeline on AWS cloud.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1627b76b72d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect Python with MySQL]]></title>
            <link>https://medium.com/@haidarlina4/connect-python-with-mysql-2f6bca38a1d1?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f6bca38a1d1</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 18:42:41 GMT</pubDate>
            <atom:updated>2021-09-01T19:38:04.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iGoDxNiXfRhrE22r" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the third out of four posts of the entire project <a href="https://medium.com/@haidarlina4/automating-an-end-to-end-data-pipeline-on-aws-cloud-7b5489e2925d"><strong>Automating an end-to-end Data Pipeline on AWS Cloud</strong></a><strong>.</strong></p><p>In the first post <a href="https://medium.com/@haidarlina4/automating-an-end-to-end-data-pipeline-on-aws-cloud-7b5489e2925d"><strong>Collect Data Using Web-scraping and APIs</strong></a>, we collected data and stored it in lists. In the second post <a href="https://medium.com/@haidarlina4/create-a-database-on-mysql-workbench-24f44ba0a902"><strong>Create a Database on MySQL Workbench</strong></a>, we set up a database on MySQL workbench with a structure that matches the data. In this post, we are going to fill this database with the data we collected using <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html"><strong>Connector/Python</strong></a><strong>.</strong></p><p>Normally, inserting values directly in the database using MySQL can be done by running the following query:</p><pre>-- to manually fill in a table<br>insert into table_name ( parameter1 , parameter2 ) values ( value1 ,<br>value2 ) ;<br>-- Example : insert into cities ( city_id , city_name , country ) values<br>( 2950159 , ’ Berlin ’ , ’ Germany ’) ;</pre><p>However, if the data is big, it would take months to fill the database this way.</p><p>Fortunately, there are alternative and more efficient ways to fill databases. One of them is by using <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html"><strong>Connector/Python</strong></a>, which can be summarized in two steps:</p><p><strong>Step 1: connect python with MySQL server</strong></p><p>To create a connection to the MySQL server, run the following lines of code:</p><pre># import the library<br>import mysql.connector</pre><pre>cnx = mysql.connector.connect(</pre><pre>user=&#39;root&#39;,</pre><pre>password=&#39;your_root_pwd&#39;, # your password of MySQL server</pre><pre>host=&#39;127.0.0.1&#39;, #  Server name or IP address on which MySQL is running. 127.0.0.1 for local host</pre><pre>database=&#39;db_name&#39; # the name of the database you want to connect to</pre><pre>)</pre><pre># cnx is a MySQLConnection object</pre><pre># connect to database</pre><pre>cursor = cnx.cursor()</pre><p>Once the connection to the MySQL server is established, we are ready to insert our values into the database.</p><p><strong>Step 2: run SQL queries from Python to fill in the database</strong></p><p>Basically, inserting values one by one is also possible and it is done using a similar way to what we did using a SQL query on MySQL workbench in the <a href="https://medium.com/@haidarlina4/create-a-database-on-mysql-workbench-24f44ba0a902">previous post</a>. Below is an example of inserting only one row of values into a table:</p><pre>query = &quot;&quot;&quot;</pre><pre>INSERT INTO table_name (parameter1 , parameter2 ) values( value1 , value2 );</pre><pre>&quot;&quot;&quot;</pre><pre># after the query is defined, you are ready to execute it</pre><pre>cursor.execute(query)<br>cnx.commit()</pre><pre># close the connection after the insertion is complete</pre><pre>cursor.close()<br>cnx.close()</pre><p>Notice that when inserting values, you need to specify the table name of the database: <em>table_name</em>. Also, the names of parameters must match with those of the table. And of course the datatype of the values must match with what you already defined when creating the table. For example, if one of the variables (or column name) of the table is set to be an integer:</p><pre>city_id INT, </pre><p>then the inserted value must be an integer.</p><p>Now we are ready to do the real work which is inserting the values we collected in the <a href="https://medium.com/@haidarlina4/automating-an-end-to-end-data-pipeline-on-aws-cloud-7b5489e2925d">first post</a> into our database that we set up in the <a href="https://medium.com/@haidarlina4/create-a-database-on-mysql-workbench-24f44ba0a902">second post</a>. We are going to take the above code and do a little modification such that instead of inserting one value, the entire list gets passed into the table. In the first post of this project, we stored the values of the flights in four lists: <em>flight_num</em>, <em>departure_icao</em>, <em>arrival_icao</em>, <em>arrival_time</em>. The following code inserts those lists in the database we created in the second post:</p><pre># inserting values of flights into MySQL database<br># connect to database<br># define connection details</pre><pre>cnx = mysql.connector.connect(<br>user=&#39;host&#39;,<br>password=&#39;your password&#39;,<br>host=&#39;127.0.0.1&#39;, # to connect to your local instance<br>database=&#39;gans&#39; #type the name of the database you want to use here</pre><pre>)</pre><pre># connect to database<br>cursor = cnx.cursor()</pre><pre># you should have flight_num, departure_icao, arrival_icao and arrival_time as lists</pre><pre>query = &#39;INSERT INTO flights (flight_num, departure_icao, arrival_icao, arrival_time) VALUES (%s, %s, %s, %s);&#39;</pre><pre>for i in range(len(flight_num)):<br>    value = (flight_num[i], departure_icao[i], <br>            arrival_icao[i], arrival_time[i]  )</pre><pre>cursor.execute(query, value)<br>cnx.commit()<br>cursor.close()<br>cnx.close()</pre><p>The additional step that we added here is creating a tuple of lists, and the for loop executes the same query for each of the values of the lists inside the tuple. If the codes runs without any error, you can check the <em>flights</em> table on my MySQL workbench by running:</p><pre>SELECT * FROM flights ;</pre><p>To fill in the other tables, the same approach can be followed. You need to only change the name of the table and its parameters.</p><p>If you followed the project from the start, by now, the tables on MySQL<br>should be filled.</p><p>It would seem that this is the end of the project. Well, in some cases, depending on the type of the project, filling the tables on our local host should be the last step. However, in our project we are collecting data of weather forecasts and flights of cities. The values change over time. This means that we have to run our scripts every day to first collect the daily weather forecasts and flights, and then to insert these values on our database.</p><p>Luckily, there is an alternative way. We can automate the data pipeline using AWS lambda functions. This means, we can set a trigger to let the lambda function run periodically according to our needs. This way, we do not have to worry about updating our databases frequently without our further intervention. More on this topic on the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f6bca38a1d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Database on MySQL Workbench]]></title>
            <link>https://medium.com/@haidarlina4/create-a-database-on-mysql-workbench-24f44ba0a902?source=rss-30664d1617dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f44ba0a902</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Lina Haidar]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 13:25:39 GMT</pubDate>
            <atom:updated>2021-08-10T08:08:04.967Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second section of the project <a href="https://medium.com/@haidarlina4/automating-an-end-to-end-data-pipeline-on-aws-cloud-7b5489e2925d"><strong>Automating an end-to-end Data Pipeline on AWS Cloud</strong></a><strong>.</strong></p><p>In the previous post: <a href="https://medium.com/@haidarlina4/automating-an-end-to-end-data-pipeline-on-aws-cloud-7b5489e2925d"><strong>Collect Data Using Web-scraping and APIs</strong></a> , we used web scraping and APIs to collect the following data:</p><p>1. names of European cities<br>2. airports flights information of each city<br>3. the weather forecasts in each city</p><p>In this post, we are going to set up a local database on MySQL workbench<br>that will be used to store the data we collected. <br><br>Before creating the database right away, it is important to first think of a<br>schema such that the data gets stored in an efficient way. Each table should<br>have an id that uniquely identifies the identity of a row, which is known as the<br>primary key. Also, there shouldn’t be redundant columns in the database.<br>The second step is to decide which table to create first. Creation of tables must be done sequentially because the tables are connected to each other<br>through keys. The primary key of one table is a foreign key in the table that is<br>connected to. So, a table that contains a foreign key can not be created if the<br>table that has this foreign key as a primary key is not created.</p><p>Regarding the names of the tables and their columns, by convention the<br>name of the tables is plural and the names of the columns are singular.<br>Once you have the EER diagram in mind or drawn on paper, you are ready to go.<br>Considering our data that we collected in the previous post, we should have the following tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*dIiga1HJW_kxmb214rbu1g.jpeg" /><figcaption>EER Diagram</figcaption></figure><p>The database is created by using the following query:</p><pre>CREATE DATABASE database_name ;</pre><p>To let the SQL server know that we want to work on this database, we need to write:</p><pre>USE database_name ;</pre><p>Let’s begin with creating our tables. The first table to create is <em>cities</em> because it does not have a foreign key.</p><pre>CREATE TABLE cities(</pre><pre>city_id INT ,<br>city_name VARCHAR(200),<br>country VARCHAR (200),<br>PRIMARY KEY (city_id)</pre><pre>);</pre><p>The query to create a table is executed only once. If you try to execute the above command again, there will be an error: <em>Query Interrupted</em> with the Message: <em>Error Code: 1050. Table ’cities’ already exists.</em></p><p>To avoid such an error in case by mistake you run the query, include the<br>words <em>IF NOT EXISTS</em> as follows:</p><pre>CREATE TABLE IF NOT EXISTS  cities(</pre><pre>city_id INT ,<br>city_name VARCHAR(200),<br>country VARCHAR (200),<br>PRIMARY KEY (city_id)</pre><pre>);</pre><p>Next, we create the <em>weathers</em> table with the following variables:</p><pre>CREATE TABLE IF NOT EXISTS weathers(</pre><pre>weather_id INT AUTO_INCREMENT,<br>city_id INT,<br>rain_prob DECIMAL (3,2),<br>forecast_time DATETIME,<br>PRIMARY KEY (weather_id),<br>FOREIGN KEY (city_id) REFERENCES cities (city_id)</pre><pre>);</pre><p>Following the same logic as which table comes next by looking at its keys,<br>create the table <em>airports</em>:</p><pre>CREATE TABLE IF NOT EXISTS airports(</pre><pre>airport_icao VARCHAR(4),<br>airport_name VARCHAR (200),<br>PRIMARY KEY (airport_icao)</pre><pre>);</pre><p>After that comes either <em>cities_airports</em> or <em>flights</em>:</p><pre>CREATE TABLE IF NOT EXISTS cities_airports (</pre><pre>city_id INT,<br>airport_icao VARCHAR(25),<br>PRIMARY KEY (city_id, airport_icao),<br>FOREIGN KEY (city_id) REFERENCES cities(city_id),<br>FOREIGN KEY (airport_icao) REFERENCES airports(airport_icao)</pre><pre>);</pre><pre>create table if not exists flights (</pre><pre>flight_id int auto_increment,<br>flight_num varchar(200),<br>departure_icao varchar(4),<br>arrival_icao varchar(4),<br>arrival_time datetime,<br>primary key(flight_id),<br>foreign key(arrival_icao) references airports(airport_icao)</pre><pre>);</pre><p>In the table <em>cities_airports</em> the line <em>PRIMARY KEY (city_id, airport_icao)</em>,<br>is a restriction that makes sure the entities in this table are unique. We are<br>adding this condition because this table is a many to many relationship and<br>hence it does not have a primary key that uniquely identifies its rows.</p><p>Below are some commands that might be needed during the process. In<br>case something goes wrong and you want to start over, you can drop a table,<br>drop/add a column.</p><pre>-- to retrieve all columns of a table<br>select * from table_name;</pre><pre>-- to drop a table<br>drop table table_name;</pre><pre>-- to add a column to a table :<br>ALTER TABLE table_name<br>DROP column_name INT;</pre><pre>-- to drop a column from a table:<br>ALTER TABLE table_name<br>DROP COLUMN column_name;</pre><p>So far, this database is set up but it is empty! Inserting values can be done manually by using:</p><pre>-- to manually fill in a table</pre><pre>insert into table_name (parameter1 , parameter2 ) values( value1 , value2 );</pre><pre>-- Example: insert into cities(city_id , city_name, country) values( 2950159 , &#39;Berlin&#39;, &#39;Germany&#39;);</pre><p>However, our data is big and it would be super tedious to fill the tables this way. In the next post we are going to learn how to insert the data in the SQL database using the python library <em>mysql.connector.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f44ba0a902" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>