<?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 Tanveer Khan on Medium]]></title>
        <description><![CDATA[Stories by Tanveer Khan on Medium]]></description>
        <link>https://medium.com/@khantanveerak?source=rss-284044362ce1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*f7_9heADDvAKBkON.</url>
            <title>Stories by Tanveer Khan on Medium</title>
            <link>https://medium.com/@khantanveerak?source=rss-284044362ce1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:31:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khantanveerak/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[Straight Forward Way To Update CUDA, cuDNN and Nvidia Driver.]]></title>
            <link>https://medium.com/ibm-data-ai/straight-forward-way-to-update-cuda-cudnn-and-nvidia-driver-and-cudnn-80118add9e53?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/80118add9e53</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cudnn]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 08:58:22 GMT</pubDate>
            <atom:updated>2023-09-29T08:12:32.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Updating Nvidia Driver" src="https://cdn-images-1.medium.com/max/595/1*rRkiOCstTDyqDvVaxSB6ZA.png" /><figcaption>Upgrading nvidia driver</figcaption></figure><p>While working on GPU the most painful thing is updating CUDA, Nvidia Driver and cuDNN. Doing the updates and getting all versions in sync can make anyone crazy. But there is a simple and easy process to update them.</p><p>In this blog post we will discuss the process to update Nvidia Driver, Cuda and cuDNN and keep all the version in sync.</p><p>Edit — Encountered an error on my well setup GPU’s all of sudden</p><blockquote>nvidia-smi &gt;&gt; Failed to initialize NVML: Driver/library version mismatch</blockquote><p>To address that I need to got rid of my nvidia driver and have to do step 1.</p><blockquote>sudo apt purge nvidia* libnvidia*</blockquote><blockquote>sudo apt install nvidia-driver-530</blockquote><blockquote>sudo reboot</blockquote><p>The order of update would be:</p><ol><li>Update Nvidia Driver</li><li>Update CUDA</li><li>Update cuDNN</li></ol><p>To briefly touch:</p><p>Cuda is a parallel computing platform and programming model developed by NVIDIA for general computing on graphical processing units (GPUs). With CUDA, developers are able to dramatically speed up computing applications by harnessing the power of GPUs. And cuDNN is a Cuda Deep neural network library which is accelerated on GPU’s. It’s built on underlying Cuda framework. nvcc output you get is for CUDA and nvidia-smi fetches nvidia display driver version and cuda associated with it.</p><p><strong>First check available nvidia driver as:</strong></p><pre>sudo apt search nvidia-driver</pre><figure><img alt="How to search the available nvidia driver from command prompt." src="https://cdn-images-1.medium.com/max/843/1*tUSXy3NuWeRoG7irSJ1Jpw.png" /></figure><p>Select the driver version you want to pick.</p><pre>sudo apt install nvidia-driver-510</pre><p>Once this is complete execute:</p><pre>sudo reboot</pre><p>After rebooting confirm the driver version using</p><pre>nvidia-smi</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*nJIPezDELhP561puQrnWyQ.png" /><figcaption>nvidia-smi output to check updated driver version</figcaption></figure><p><strong>Updating CUDA Version</strong></p><p>Go to nvidia download to select the appropriate cuda version. I wanted to download cuda-11–6 update 1 for installing deep stream.</p><p><a href="https://developer.nvidia.com/cuda-11-6-1-download-archive">CUDA Toolkit 11.6 Update 1 Downloads</a></p><p>Selecting your os, cpu architecture, distribution, version and installer type as <strong>‘runlocal’</strong></p><p>Run below command to download the run file:</p><pre>wget https://developer.download.nvidia.com/compute/cuda/11.6.1/local_installers/cuda_11.6.1_510.47.03_linux.run</pre><p>And once download is complete execute the below command to start cuda updation:</p><pre><br>sudo sh cuda_11.6.1_510.47.03_linux.run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*XWs1ULH4p1TJ7a28OyH0Tg.png" /></figure><p>Select continue:</p><figure><img alt="installing cuda" src="https://cdn-images-1.medium.com/max/738/1*J-h8XN2qS5RT5gQI22Kaqg.png" /></figure><p>Type Accept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*NscpASjAsMEghZnUylQGfA.png" /></figure><p>Unselect driver as it has been updated in step #1 and select install</p><figure><img alt="installing cuda toolkit without driver." src="https://cdn-images-1.medium.com/max/819/1*t6bMua3QEj0BDdzqJynqRw.png" /></figure><p>Install cuDNN:</p><p>go to nvidia developer download page:<br><a href="https://developer.nvidia.com/cudnn">https://developer.nvidia.com/cudnn</a></p><p>Select download cuDNN:</p><figure><img alt="Downloading cuDNN from website." src="https://cdn-images-1.medium.com/max/1024/1*7bKlqFQbk3Vm-DjKGUJvxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpOu2pojZv8-THOOXUj07Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpOu2pojZv8-THOOXUj07Q.png" /></figure><p>You have to login to developer program, it’s free incase you haven’t joined it yet.</p><p>After logging select T&amp;C and Download appropriate version which you want to download:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBOjmBl4dkep6VGSVOvzEA.png" /></figure><p>Go to the download location of the file and untar the downloaded file:</p><pre>tar -xvf cudnn-linux-x86_64–8.4.1.50_cuda11.6-archive.tar.xztar.xz</pre><p>After untar run the following command:</p><pre>$ sudo cp cudnn-*-archive/include/cudnn*.h /usr/local/cuda/include <br>$ sudo cp -P cudnn-*-archive/lib/libcudnn* /usr/local/cuda/lib64 <br>$ sudo chmod a+r /usr/local/cuda/include/cudnn*.h /usr/local/cuda/lib64/libcudnn*</pre><p>So, In this blog we have seen a simple and straight forward way of updating all three drivers which we are required to keep your Deep Learning setup in sync and you can seamlessly use your GPU’s.</p><p>I hope this will be useful for you for sometime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80118add9e53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ibm-data-ai/straight-forward-way-to-update-cuda-cudnn-and-nvidia-driver-and-cudnn-80118add9e53">Straight Forward Way To Update CUDA, cuDNN and Nvidia Driver.</a> was originally published in <a href="https://medium.com/ibm-data-ai">IBM Data Science in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to find correct docker base image while creating containers that need GPU ?]]></title>
            <link>https://medium.com/ibm-data-ai/how-to-find-correct-docker-base-image-while-creating-containers-that-need-gpu-c2bbf897a237?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bbf897a237</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 16:51:17 GMT</pubDate>
            <atom:updated>2022-07-22T11:30:03.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic Hygiene For Creating Containers That needs GPU ?</h3><figure><img alt="Installing nvidia driver on linux system is a pain." src="https://cdn-images-1.medium.com/max/646/1*QWPyOMQwJxsL4xP11RK57Q.png" /></figure><p>We are living in the era of “Containers”. For many benefits containers and dockers are most preferred method of deployments. Same benefits applies to Deep Learning as well which has special nuance that your container should be able to access the underlying GPU Hardware. Nvidia has created NGC (Nvidia Container Environment) as an abstraction over docker, So we can execute such containers easily !! But creating such docker images and container is tricky and often leads to errors and failed execution of container.</p><p>In this blog, We will discuss one such situation and a basic hygiene for creating docker containers that needs GPU’s.</p><p>Nvidia container environment has hard dependencies on the version of Cuda and cudNN on the host machine which is running the docker container. In this post we will not discuss what cuda and cudnn is but briefly:</p><p>Cuda is a parallel computing platform and programming model developed by NVIDIA for general computing on graphical processing units (GPUs). With CUDA, developers are able to dramatically speed up computing applications by harnessing the power of GPUs.</p><p>And cuDNN is a Cuda Deep neural network library which is accelerated on GPU’s. It’s built on underlying Cuda framework.</p><p>If there is a version mismatch your container will be created but you won’t be able to run any application that uses cudnn because of the error:</p><figure><img alt="Error message while running containers with gpu" src="https://cdn-images-1.medium.com/max/1024/1*W_b59--FyIFWDr5KmeqYBw.png" /><figcaption>error from docker container requesting cuda</figcaption></figure><p>Reason for this error is version mismatch between cuda and cuDNN between Host Computer that is running container and container’s own cuda and cuDNN environment.</p><p>One thing to note here is the base image you selected in the docker file will determine the cuda and cudnn version that will be installed inside the container.</p><p>First of all we need to find the version of cuDNN and cuda version on host Computer so that we can select the correct image to build the docker container to avoid version conflicts.</p><p><strong>Steps to find CuDNN version on the Host Computer</strong>:</p><blockquote>whereis cudnn_version.h</blockquote><figure><img alt="Command to show how to find version of cudnn" src="https://cdn-images-1.medium.com/max/792/1*6LNvAREZU_YjRsaw3W2auQ.png" /><figcaption>output of CuDNN</figcaption></figure><p>We can see the CuDNN version is located at /usr/include/cudnn_version.h</p><p>Copy the location and do a more on file and scroll to find exact version of cudDNN.</p><blockquote>more /usr/include/cudnn_version.h</blockquote><figure><img alt="cudnn version file content showing cudnn version" src="https://cdn-images-1.medium.com/max/772/1*sV_s_qXM5IQOGwDyubjWeA.png" /><figcaption>cuDNN version</figcaption></figure><p><strong>So for my machine exact version of CuDNN is 8.1.1</strong></p><p>Now we need to find the exact version of the Cuda, Which can be done easily by nvida-smi or nvcc or issuing command whereis cuda_version.h</p><figure><img alt="command showing nvidia-smi. This command shows nvidia driver and cuda version, gpu memory utilization, gpu usage utilization, power consumption and other vitals related to GPU." src="https://cdn-images-1.medium.com/max/803/1*gxy9AGmQAYhiNs4lGg0T9Q.png" /><figcaption>Output of nvidia-smi</figcaption></figure><p><strong>So version of Cuda on my machine is 11.4.0.</strong></p><p>Now to build a docker container with nvidia run time to access GPU inside the container, We need to find the base image that has matching Cuda and CuDNN versions on our host machine.</p><p>cuda = 11.4</p><p>cuDNN = 8</p><p>(replace these numbers with versions on your computer).</p><p>Base images can be searched over below link:</p><p><a href="https://gitlab.com/nvidia/container-images/cuda/blob/master/doc/supported-tags.md">doc/supported-tags.md · master · nvidia / container-images / cuda · GitLab</a></p><p>Now, We need to go back and update Dockerfile to include the correct base image and we are good to go.</p><p>In below example I am using base image as cuda:11.4.0-cudnn8-devel-ubuntu20.04</p><figure><img alt="sample docker file for creating a container that needs GPU." src="https://cdn-images-1.medium.com/max/858/1*qRnsHyKdg4toKAAuRfv-ZQ.png" /><figcaption>DockerFile</figcaption></figure><p>Then build the image and create a docker container and successfully run it !!</p><p>So, While creating the docker images for your containers that needs GPU’s please ensure:<br>1. Check the Cuda and cuDNN version on your Target Machine on which your container will execute.</p><p>2. In NGC find the base image that uses exactly same versions of cuda and cuDNN and use that as a base image.</p><p>3. Create the base image and run the containers !!</p><p>Good Luck !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bbf897a237" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ibm-data-ai/how-to-find-correct-docker-base-image-while-creating-containers-that-need-gpu-c2bbf897a237">How to find correct docker base image while creating containers that need GPU ?</a> was originally published in <a href="https://medium.com/ibm-data-ai">IBM Data Science in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Hygiene With Tensorflow During Model Training and Deployment for Inference]]></title>
            <link>https://medium.com/ibm-data-ai/memory-hygiene-with-tensorflow-during-model-training-and-deployment-for-inference-45cf49a15688?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/45cf49a15688</guid>
            <category><![CDATA[data-science-tutorial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 12:48:37 GMT</pubDate>
            <atom:updated>2021-09-29T18:39:16.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Memory Hygiene With TensorFlow During Model Training and Deployment for Inference</h3><h3>Introduction</h3><p>If you work on TensorFlow and want to share GPU with multiple processes then you must have encountered into either of one of the below situations. This post discusses how to address these situations and use the GPU resources optimally to take maximum advantage of it.</p><figure><img alt="Image with stick figures. In situation one, the stick figure on the left says “hey- are you training some model on GPU. Seems entire memory is occupied. I need to train my model.” The stick figure on the right replies “oh yes, you would need to wait for a few hours.” In situation two, the stick figure says “I have only one GPU and need to deploy couple of models for inference simultaneously”" src="https://cdn-images-1.medium.com/max/758/1*KHptmSM4R9TXHuOA6EXMtQ.png" /></figure><p><strong>Technical Details:</strong></p><ul><li>GPU — Nvidia RTX 3080</li><li>CPU &amp; Memory — Intel i7, 32 GB RAM</li><li>TensorFlow Version — 2.4</li><li>CUDA Version — 11.2</li><li>Application — TensorFlow application that I will be discussing is Automated Number Plate Recognition which is built on Darknet as backbone network</li></ul><p>Let’s see Memory Allocation For a TensorFlow-Based Model on a GPU:</p><p>These are the GPU memory details before loading any TensorFlow Based Workload.</p><p>It can be clearly observed that GPU has 10 GB of memory and of which only 489 MB is occupied.</p><figure><img alt="This image is an output of command nvidia-smi which is used to print stats about Nvidia GPU. This image shows 490 MB of memory is allocated to the GPU before running any Tensorflow based workload." src="https://cdn-images-1.medium.com/max/760/1*JjnEw4gA_OQoiHySh21l_A.png" /><figcaption>Initial GPU Memory Allocation Before Executing Any TF Based Process</figcaption></figure><p>Now let’s load a TensorFlow-based process.</p><p>We will load an object detection model deployed as REST-API via Flask [1] running over Twisted [2].</p><p>You can see how quickly the complete GPU memory is filled up as soon as TensorFlow model is loaded:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMYwBRnRAKW0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMYwBRnRAKW0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMYwBRnRAKW0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/018e2a2148b4b9e62deaddaa274e620e/href">https://medium.com/media/018e2a2148b4b9e62deaddaa274e620e/href</a></iframe><p>So if we try to start another process it will give you an Out of Memory Error.</p><p>Our inference module is exposed as a REST API which listens for inference requests on a specified Port. Since we are already running a process, that Port is in use. If we run one more instance of the process, it will fail as that port is in use. To avoid this error, we will just change the Port Number where our REST service will listen and run the same process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLKzuZOOhcsM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLKzuZOOhcsM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLKzuZOOhcsM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c16a1b06ad7da874831d4f53e3b4f69/href">https://medium.com/media/5c16a1b06ad7da874831d4f53e3b4f69/href</a></iframe><p><em>The above video clearly shows the out of memory error. TensorFlow aggressively occupies the full GPU memory even though it actually doesn’t need to do so.</em></p><p><em>This is a greedy strategy adopted by TensorFlow to avoid memory fragmentation, but this causes a bottleneck of GPU memory. Only one process exclusively has all the memory.</em></p><p><a href="https://www.tensorflow.org/guide/gpu">Use a GPU | TensorFlow Core</a></p><p>By default, TensorFlow maps nearly all of the GPU memory of all GPUs (subject to <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars">CUDA_VISIBLE_DEVICES</a>) visible to the process. This is done to more efficiently use the relatively precious GPU memory resources on the devices by reducing memory fragmentation. To limit TensorFlow to a specific set of GPUs we use the <a href="https://www.tensorflow.org/api_docs/python/tf/config/set_visible_devices">tf.config.experimental.set_visible_devices</a> method.</p><p>Due to the default setting of TensorFlow, even if a model can be executed on far less memory, many times a model will occupy far more memory than needed. This results in non-optimal and often wastage of computation power of a GPU.</p><p>If the optimal memory is allocated to a TensorFlow process, it will occupy less GPU memory and the remaining memory can be shared by other process.</p><p>So either you can train multiple models at one go or you can execute multiple model for inference at the same time.</p><h3>TensorFlow has provided Two options to address this situation:</h3><h4><strong>First Option — Specifically Set The Memory</strong></h4><p>We need to add the line below to list the GPU(s) you have.</p><pre><strong>gpus = tf.config.list_physical_devices(&#39;GPU&#39;)</strong></pre><p>In this option, we can limit or restrict TensorFlow to use only specified memory from the GPU. In this way, you can limit memory and have a fair share on the GPU between the different processes. Using this option you can define the optimal memory for your process and it will use only that memory.</p><p>Setting this optimal memory can be tricky. You can use tools like Weight and Biases [3] and Tensorboard [4] to look at the System Graphs to come-up with an optimal memory size for your process. These tools generate very useful graphs with details about your GPU computation, utilization, memory usage and memory transfer.</p><p>We will add below code to our process and will execute</p><pre><strong>if gpus:<br>    for gpu in gpus:<br>        tf.config.experimental.set_virtual_device_configuration(gpu,[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)])</strong></pre><p>In the above code, we are setting an upper bound of 4 GB on GPU memory limit. So when we trigger the process, it will occupy only 4 GB of memory instead of occupying the full memory.</p><p>Let’s look at the screenshot of nvidia-smi command to know the memory usage of GPU after executing our process which is bounded to use only 4 GB of memory. It can be observed that only 4 GB of memory is used instead of 8 GB as shown in the first video.</p><figure><img alt="This image shows GPU memory allocated via nvidia-smi command. This is a standard command to display GPU stats including utilization, memory usage and temperature of Nvidia GPU. This image shows memory usage has increased by 4GB as we had allocated 4GB memory to our process." src="https://cdn-images-1.medium.com/max/802/1*HCrvlyixgdiKgvIZXzdafQ.png" /><figcaption>GPU Memory Allocated After Starting One Process with 4 GB Memory Allocation</figcaption></figure><p>Now let’s execute the other process which has previously faced Out Of Memory Error.</p><figure><img alt="This image has three screen shots. Left and right panel of the image is a log from a inference from Tensorflow based process that is exposed as REST using Flask and ran via Twisted. The middle panel of the image shows GPU memory allocated via nvidia-smi command. This image shows memory usage has increased by 8 GB we had allocated 4GB memory to each process. This image shows both the process are able to ran using their equal share of GPU memory." src="https://cdn-images-1.medium.com/max/1024/1*VCDtaDyPu47jvyMS1jSdxA.png" /><figcaption>Two process running simultaneously with-in their allocated memory</figcaption></figure><p>Attached is the screen grab for whole process:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD7MZT7Wwu5Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD7MZT7Wwu5Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD7MZT7Wwu5Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/481bdd369cbf1cb15026cbb74162cf2f/href">https://medium.com/media/481bdd369cbf1cb15026cbb74162cf2f/href</a></iframe><p>We have clearly seen that using this option, we can allocate/override GPU memory allocation for the TensorFlow process and can use GPU resources optimally between the team or process.</p><h4><strong>Second option</strong> — Set memory growth as per the need</h4><p>This option will initially allocate just a little memory and will keep on allocating more. <em>However, there is one caveat with this option. Once the memory is allocated, it will not be released to avoid memory fragmentation. So even if your process starts on low memory, it will acquire more memory gradually but it will not release when it don’t need it. I would recommend to use the first option whenever possible.</em></p><p>The code snippet below sets the second option discussed in the blog post which will initially allocate the minimum required memory and later on increase the memory allocation as needed for the TensorFlow-based workflow. The first line finds out if and how many GPU’s are available and for each GPU, it says to use the set_memory_growth_option</p><pre><strong>gpus = tf.config.list_physical_devices(&#39;GPU&#39;)</strong></pre><pre><strong>if gpus:<br>    for gpu in gpus:<br>       tf.config.experimental.set_memory_growth(gpu,True)</strong></pre><p>Let’s execute my process one more time and see the memory allocation.</p><figure><img alt="This image is an output of command nvidia-smi which is used to print stats about Nvidia GPU. This image shows 352 MB of memory is allocated to the GPU before running any Tensorflow based workload." src="https://cdn-images-1.medium.com/max/827/1*Y6bk_3mWx_aKEelRPs8aiA.png" /><figcaption>GPU Memory Allocation Before Executing A Process With Set Process</figcaption></figure><p><strong>The process is executed. We can see, the full memory is NOT allocated: only few MB’s are allocated.</strong></p><figure><img alt="Left Panel of the image shows the log of Tensorflow based process that was executed. It shows process is up and running. Right Panel of the image is an output of command nvidia-smi which is used to print stats about Nvidia GPU. This image shows few MB memory is allocated to the GPU after running Tensorflow based workload. Image shows using this option Tensorflow is taking only what is required." src="https://cdn-images-1.medium.com/max/1024/1*V2PhJh0AutF7_XLA4Iru7Q.png" /><figcaption>Memory Allocated After Executing Process</figcaption></figure><p>Now, we will put some load on the GPU. To add more load, we will make 100 REST calls simultaneously to do the object detection which will do the Automatic Number Plate Recognition. This request will go to the REST server and will put load on the GPU and that will cause an increase in GPU memory.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmkZlinnBdyA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmkZlinnBdyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmkZlinnBdyA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/16d255d43cd06fd8306532b1330918ef/href">https://medium.com/media/16d255d43cd06fd8306532b1330918ef/href</a></iframe><p>In the above screen grab, we can see the memory gradually increases but it doesn’t occupy the full memory. However, it doesn’t release the memory even after the load on the GPU is gone. (The REST service is still running but inference load is complete).</p><figure><img alt="This image is an output of command nvidia-smi which is used to print stats about Nvidia GPU. This image shows 8GB memory is allocated to the GPU before running any Tensorflow based workload. This image shows memory usage has increased significantly based upon load but it has not still occupied full memory." src="https://cdn-images-1.medium.com/max/743/1*l-CX_d1PJ8yQaHlOFpV6Xg.png" /><figcaption>Memory Is Occupied Even Load On GPU Is Finished</figcaption></figure><h3>Conclusion:-</h3><ol><li>TensorFlow processes by default will acquire the full memory of the GPU, even if it does not need it. If you build a small neural network, it will acquire the complete GPU memory. This might lead to inefficient GPU utilization if your work load is not heavy.</li><li>There are two settings which you can use to control memory acquired by a TensorFlow process.</li><li>Specify the exact memory you want to allocate to your process. This will need tuning and experimentation to arrive at the correct number. One can refer to the System Graphs of a GPU. These graphs are available with Weight &amp; Biases. Below are the sample graphs which can be used to evaluate how much memory your process would need to execute.</li></ol><figure><img alt="Graphs showing Process GPU temperature in Celsius, Process GPU Time Spent Accessing Memory by percent, Process GPU Memory Allocated by percent and Process GPU Power Usage by percent" src="https://cdn-images-1.medium.com/max/1024/1*xXw9kA3PV3jZTeUZNwnNIQ.png" /><figcaption>Weight &amp; Biases Graph For Process GPU Utilization and Memory Allocation</figcaption></figure><figure><img alt="Graphs showing GPU utilization by percent, GPU temp in Celsius, GPU time spent accessing memory by percent, and GPU memory allocated by percent" src="https://cdn-images-1.medium.com/max/1024/1*fmtxb1HCA4Co4Qc4501Rwg.png" /><figcaption>Weight &amp; Biases Graph For Overall GPU Utilization and Memory Allocation</figcaption></figure><p>4. You can specify a memory growth option. This option will allocate small memory to the process. And it will increase the allocation as needed with increase in load. But it will not release the acquired memory even when the load is complete.</p><p>I hope you’ve found this post informative and this helps alleviate any headaches with GPU usage in your next TensorFlow project.</p><h3>References</h3><p>[1] <a href="https://flask.palletsprojects.com/en/1.1.x/">https://flask.palletsprojects.com/en/1.1.x/</a></p><p>[2] <a href="https://twistedmatrix.com/trac/">https://twistedmatrix.com/trac/</a></p><p>[3] <a href="https://wandb.ai/site">https://wandb.ai/site</a></p><p>[4] <a href="https://www.tensorflow.org/tensorboard">https://www.tensorflow.org/tensorboard</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45cf49a15688" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ibm-data-ai/memory-hygiene-with-tensorflow-during-model-training-and-deployment-for-inference-45cf49a15688">Memory Hygiene With Tensorflow During Model Training and Deployment for Inference</a> was originally published in <a href="https://medium.com/ibm-data-ai">IBM Data Science in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Hygiene With Tensorflow During Model Training and Deployment for Inference]]></title>
            <link>https://medium.com/ai-for-real/memory-hygiene-with-tensorflow-during-model-training-and-deployment-for-inference-f3e30e3eea49?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e30e3eea49</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 18:20:39 GMT</pubDate>
            <atom:updated>2021-03-08T14:40:48.262Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>If you work on Tensorflow and want to share GPU with multiple processes then you must have encountered into either of one situation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*KHptmSM4R9TXHuOA6EXMtQ.png" /></figure><p>Let’s see Memory Allocation For Tensorflow Based Model on A GPU:</p><p>This is the GPU memory details before loading any Tensorflow Based Workload.</p><p>It can be clearly observed that GPU has 10 GB of memory and of which only 489 MB is occupied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*JjnEw4gA_OQoiHySh21l_A.png" /><figcaption>Initial GPU Memory Allocation Before Executing Any TF Based Process</figcaption></figure><p>Now let’s load a Tensorflow based process.</p><p>We will load object detection model deployed as REST-API via flask running over Twisted.</p><p>You can see how quickly the complete GPU memory is filled up as soon as Tensorflow model is loaded:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMYwBRnRAKW0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMYwBRnRAKW0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMYwBRnRAKW0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/018e2a2148b4b9e62deaddaa274e620e/href">https://medium.com/media/018e2a2148b4b9e62deaddaa274e620e/href</a></iframe><p>So if we try to start another process it will give you Out of Memory Error. We will just run the same process on another port.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLKzuZOOhcsM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLKzuZOOhcsM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLKzuZOOhcsM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c16a1b06ad7da874831d4f53e3b4f69/href">https://medium.com/media/5c16a1b06ad7da874831d4f53e3b4f69/href</a></iframe><p><em>Above video clearly shows the out of memory error. As</em> <em>Tensorflow aggressively occupy the full GPU memory even though it actually don’t need.</em></p><p><em>This is a greedy strategy adopted by Tensorflow to avoid memory fragmentation. But this causes Bottleneck of GPU memory. Only one process exclusively has all the memory.</em></p><p><a href="https://www.tensorflow.org/guide/gpu">Use a GPU | TensorFlow Core</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*CIlRqX-l9jy1VgLRC8KDaA.png" /></figure><p>Even though a model can be executed on a far more lesser memory but due to default setting of Tensorflow, Many a times it occupies far more than needed. This results into non-optimal and often wastage of computation power of GPU.</p><p>If optimal memory is allocated to Tensorflow process it will occupy less GPU memory and the remaining memory can be shared by other process.</p><p>So either you can train multiple models at one go or can execute multiple model for inference at the same time.</p><p>Tensorflow has provided few options to address this situation:</p><p>First we need to add below line to list the GPU(s) you have.</p><pre><strong>gpus = tf.config.list_physical_devices(&#39;GPU&#39;)</strong></pre><p>In this option we can limit or restrict Tensorflow to use only specified memory from the GPU. In this way you can limit memory and have a fair share the GPU between the different process. Using this option you can define the optimal memory for your process and it will use that memory only.</p><p>Setting this optimal memory can be tricky. And you can use tools like Weight and Biases and Tensorboard to look a the System Graphs to come-up with a number for your process. These tools generate very useful graphs with details about your GPU computation, utilization, memory usage and memory transfer.</p><p>We will add below code to our process and will execute</p><pre><strong>if gpus:<br>    for gpu in gpus:<br>        tf.config.experimental.set_virtual_device_configuration(gpu,[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)])</strong></pre><p>In the above code we are setting upper bound of 4 GB on GPU memory limit. So when we trigger the process it will occupy only 4 GB memory instead of occupying the full memory.</p><p>Let’s look at the screenshot of nvidia-smi about the memory usage after executing our process which is bounded to use only 4 GB of memory. It can be observed that only 4 GB of memory is used instead of 8 GB as shown in the first video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*HCrvlyixgdiKgvIZXzdafQ.png" /><figcaption>GPU Memory Allocated After Starting One Process with 4 GB Memory Allocation</figcaption></figure><p>Now let’s execute the another process which has previously faced Out Of Memory Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCDtaDyPu47jvyMS1jSdxA.png" /><figcaption>Two process running simultaneously with-in their allocated memory</figcaption></figure><p>Attached is the screen grab for whole process:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD7MZT7Wwu5Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD7MZT7Wwu5Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD7MZT7Wwu5Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/481bdd369cbf1cb15026cbb74162cf2f/href">https://medium.com/media/481bdd369cbf1cb15026cbb74162cf2f/href</a></iframe><p>We have clearly seen that using this option we can allocate/override GPU memory allocation for the Tensorflow process and can use GPU resources optimally between the team or process.</p><p>There is one more option of setting memory growth. This option will initially allocate the little memory and will keep on allocating more. <em>But caveat with this option is once the memory is allocated it will not be released to avoid memory fragmentation. So even if your process starts on low memory it will acquire more memory gradually but it will not release when it don’t need it. To me where ever possible we should use the first option.</em></p><pre><strong>gpus = tf.config.list_physical_devices(&#39;GPU&#39;)</strong></pre><pre><strong>if gpus:<br>    for gpu in gpus:<br>       tf.config.experimental.set_memory_growth(gpu,True)</strong>      </pre><p>Let’s execute my process one more time and see the memory allocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*Y6bk_3mWx_aKEelRPs8aiA.png" /><figcaption>GPU Memory Allocation Before Executing A Process With Set Process</figcaption></figure><p><strong>Process is executed, And we can see, NOT full memory is allocated only few MB’s are allocated:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2PhJh0AutF7_XLA4Iru7Q.png" /><figcaption>Memory Allocated After Executing Process</figcaption></figure><p>Now, We will put some load on GPU. To add load we will make 100 REST call simultaneous to do the object detection. This request will go to the REST server and will put load on GPU and that will cause increase in GPU memory.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmkZlinnBdyA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmkZlinnBdyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmkZlinnBdyA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/16d255d43cd06fd8306532b1330918ef/href">https://medium.com/media/16d255d43cd06fd8306532b1330918ef/href</a></iframe><p>In the above screen grab we can see the memory gradually increases but it didn’t occupied the full memory. But it didn’t release the memory even after the load on the GPU is gone. (REST service is still running but inference load is complete) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*l-CX_d1PJ8yQaHlOFpV6Xg.png" /><figcaption>Memory Is Occupied Even Load On GPU Is Finished</figcaption></figure><h3><strong>Conclusion:-</strong></h3><ol><li>Tensorflow process by default will acquire full memory of GPU. Even though it does not need it. Even if you build a small neural network it will acquire complete GPU memory. This might lead to inefficient GPU utilization if your work load is not heavy.</li><li>There are two settings which you can control memory acquired by a Tensorflow process.</li><li>Specify the exact memory you want to allocate to your process. This will need tuning and experimenting to arrive at correct number. One can refer to System Graphs of GPU. These graphs are available with Weight &amp; Biases.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXw9kA3PV3jZTeUZNwnNIQ.png" /><figcaption>Weight &amp; Biases Graph For Process GPU Utilisation and Memory Allocation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmtxb1HCA4Co4Qc4501Rwg.png" /><figcaption>Weight &amp; Biases Graph For Overall GPU Utilisation and Memory Allocation</figcaption></figure><p>4. You can specify a memory growth option. This option will allocate small memory to the process. And it will increase the allocation as needed with increase in load. But it will not release the acquired memory even when load is complete.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e30e3eea49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-for-real/memory-hygiene-with-tensorflow-during-model-training-and-deployment-for-inference-f3e30e3eea49">Memory Hygiene With Tensorflow During Model Training and Deployment for Inference</a> was originally published in <a href="https://medium.com/ai-for-real">AI For Real</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[einsum — An Easy/Intuitive way to write Tensor Operation]]></title>
            <link>https://medium.com/ibm-data-ai/einsum-an-easy-intuitive-way-to-write-tensor-operation-9e12b8a80570?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e12b8a80570</guid>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Sat, 20 Feb 2021 14:56:26 GMT</pubDate>
            <atom:updated>2022-09-16T21:47:25.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>einsum — An Easy/Intuitive way to write Tensor Operation</h3><h3>Einstein Summation Convention on Operands</h3><h4>What is Einstein Summation Convention ?</h4><p>Einstein summation is a convention for simplifying expression that includes summation of vectors, matrices or in general tensor. <em>Remember scalar is zero rank tensor, vector is a rank one tensor and matrices are rank two tensors. Basically scalar, vectors and matrices are different forms of tensor based upon their rank.</em></p><p>There are three rules which need to be followed to represent an expression as Einstein Summation and they are:</p><ol><li>Values along the repeated indices (axis) are multiplied and then implicitly sum over. (if an index (axis) in expression is repeated it will be implicitly summed over i.e. we need not to write summation explicitly)</li><li>Each index can appear not more than two times in a term.</li><li>Each term must contain identical non-repeated indices.</li></ol><p><strong>Let’s see some of the examples for representing some operations with a valid einsum notation. Below equation denotes dot product of two vectors u and v in with ’n’ dimensions in a valid Einsum notation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*N7uwOmSyXVGxq-qQ40d1wg.png" /><figcaption>vector vector dot product</figcaption></figure><p>To understand the einsum notation we can see ‘i’ is the repeated index so values along the axis represented represented by ‘i’ for vector u and v are multiplied with each other and then a sum will be computed for final result.</p><p><strong>Let’s see another example of vector and matrix multiplication. In this case “j” is the repeated index. So values of matrix A along the “J” axis and values of vector “u” along the j axis will be multiplied and then sum over.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*IeYcjugEJF1SL1NOWXKkWw.png" /><figcaption><strong>matrix vector multiplication</strong></figcaption></figure><p><strong>We will take one last example for matrix to matrix multiplication.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVspf3xYWCwNRS2l8HA_HQ.png" /><figcaption>matrix-matrix multiplication</figcaption></figure><p><strong>In the above two notion we can see how item #2 and #3 of Einstien Summation Convention has been followed.</strong></p><p><strong>Below are the general matrix operations we do:</strong></p><ol><li>Matrix — Vector Multiplication</li><li>Matrix — Matrix Multiplication</li><li>Dot Product</li><li>Outer Product</li><li>Transpose of the Matrix</li></ol><h3>CASE FOR EINSUM</h3><p>As Frameworks like Numpy, PyTorch and Tensorflow has their own set of instructions with their own syntax for above operations. But there are certain challenges:</p><ol><li>Need to correct the shapes using reshape or resize or transposing the matrix.</li><li>Need to use some intermediate matrices/tensors to hold results.</li><li>Need to remember different different syntax for these operations.</li></ol><p><strong>Using Einsum:</strong></p><ol><li>Single command/interface for all such operations across the framework. And don’t need to remember separate syntax for each of the operations.</li><li>Operations can be expressed in more intuitive manner.</li><li>Multiple Operations can be combined into one single operation.</li><li>Code looks more concise, clear and efficient. And we don’t have to remember a separate syntax for all those operations.</li><li><strong>Relatively Faster and Memory efficient when a single einsum expression is used to replace multiple tensor operations.</strong></li></ol><h3><strong>Understanding Syntax For Einsum</strong></h3><p>Einsum is available in all three frameworks:</p><ul><li>numpy : numpy.einsum</li><li>pytorch : torch.einsum</li><li>tensorflow : tf.einsum</li></ul><p>And this method shares the same signature in all of the above frameworks.</p><p>einsum(expression,operands)<br>where - <br>expression - this is a equation that represents the Einstein Summation. The equation is given in terms of lower case letters (indices) to be associated with each dimension of the operands and result. This expression has two parts separated by symbol &#39;-&gt;&#39;.</p><p>Left part defines input and operations and Right part defines the output.</p><p>operands - tensors on which einsum needs to be evaluated on. This could be one more tensors on which want to apply operation expressed by einsum notation.</p><p>For example for multiplying two matrices u and v, einsum can be written as:</p><p>w = einsum(&#39;ij,jk-&gt;ik&#39;,u,v)</p><p>where &#39;u&#39; has dimension (i,j) and &#39;v&#39; has dimension(j,k) and (i,k) is the dimension of resultant matrix &#39;w&#39;</p><h3>Axis Labeling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*y9f4bMh9R-O2YNFV9i4OBA.png" /><figcaption>mapping of indices in notation to array axis</figcaption></figure><h3><strong>For writing equations:</strong></h3><p>1. Choose the correct labeling for the axes of input and output tensors.</p><p>2. Remember below rules</p><p>A. If an indices is repeated in the left side of expression (-&gt;) then we need to multiply value (element wise) along that axis.</p><p>B. If an indices is missing in right side of expression (-&gt;) than we need to sum along the axis and explicitly reduce the dimensions.</p><p>So in the equation - <br>einsum(&#39;ij,jk-&gt;ik&#39;,u,v)</p><p>We need to multiply values element wise along the axis represented by &quot;j&quot; for u and v. Which is rows for u (i,j) and column for v (j,k) and as &quot;j&quot; is omitted we need to sum it.</p><p>3. We can return the unsummed axes in any order we want.</p><p>4. If we don&#39;t provide explicit &#39;-&gt;&#39; to separate input and output indices, Numpy will take those indices which appeared once in the expression and will arrange in the alphabetic order.</p><p>so expression :<br>einsum(&#39;ij,jk-&gt;ik&#39;,u,v) is equal to einsum(&#39;ij,ik&#39;,u,v)</p><p>Since &#39;j&#39; is common index, So numpy will pick up &quot;i&quot; and &quot;k&quot; as indices that appear just once and create an output tensor of shape &quot;ik&quot; (arrange “i” and “k” in alphabetic order).</p><h3><strong>How To Write Expression:</strong></h3><p><strong>We will try to understand this using code</strong></p><p>Let’s say we have a two dimensional array ‘u’ of shape 2,3 with value 2 across the cells. And, We want to compute:</p><ul><li>Sum along columns</li><li>Sum along rows</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*Xg24AZg4cYweDYNz8gtMLw.png" /></figure><pre><strong>import numpy as np<br>u = np.full((2,3),2)<br>print (u)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/1*AoGlbX4KVLAQMCKJPUN9Rw.png" /></figure><p><strong>How to write einsum equation:</strong></p><ul><li><strong>Sum along the columns — where we have 2 rows and 3 columns. In this case output will be a 3 dimensional vector.</strong></li></ul><p>For this problem our operand is a matrix ‘u’ with dimensions (2,3) and we want to sum along columns so we need to remember rule #2 i.e. we need to omit the i axis from the output</p><p>So our expression will look like:<br>‘ij -&gt; j’</p><p>In this example our output will be 3 dimensional vector as j = 3</p><p><strong>So python code will look like</strong></p><pre><strong>print (np.einsum(&#39;ij-&gt;j&#39;,u))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*A-3AWU0k21lcr2OKpTLg3w.png" /></figure><ul><li><strong>Sum along the Rows — where we have 2 rows and 3 columns. In this case output will be a 2 dimensional vector.</strong></li></ul><p>For this problem our operand is a matrix ‘u’ with dimensions (2,3) and we want to sum along rows so we need to remember rule #2 i.e. we need to omit the j axis from the output<br>So our expression will look like:<br>‘ij -&gt; i’<br>In this example our output will be a 2 dimensional vector.</p><p><strong>So python code will look like</strong></p><pre><strong>print (np.einsum(&#39;ij-&gt;i&#39;,u))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*1jAm05_JS046v7FZ1fUjfQ.png" /></figure><p><strong>I hope, We are clear with the rule #2. Now we will take a look at the rule #1 to understand it.</strong></p><p>Let’s say we have two matrices ‘x’ and ‘y’ of dimensions (2,3) and (3,4) and we want to do a matrix and matrix multiplication. So output matrix will be of shape (2,4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*HrHJJZRKwZ4tDn5nFLtkJQ.png" /></figure><pre><strong>x = np.full((2,3),2)<br>y = np.ones((3,4))</strong></pre><pre><strong>#Here there are two operands &#39;x&#39; and &#39;y&#39; and with dimension (2,3) and #(3,4)<br><br>#To write a einsum equation for this matrix - matrix multiplication </strong></pre><pre><strong>#what we need </strong></pre><pre><strong>print (np.einsum(&#39;ij,jk-&gt;ik&#39;,x,y)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*zBk1mHy1PuSxyzVVoYRYNA.png" /></figure><p>In the above einsum expression ‘j’ is repeated indices so element wise multiplication will happen along the “j” axis. And “j” is omitted in the output expression so a sum will be computed along that axis and that dimension will be drooped.</p><p><strong>We can see this matrix multiplication in two step process to visualize application of rule #1 and rule #2.</strong></p><p>As per the rule #1 repeated indices which is (“j”) are multiplied with each other. So elements along the ‘j’ axis (rows) in the ‘x’ and vertical (column) in the ‘y’ and will be multiplied each other.</p><pre><strong>u = np.full((2,3),2)<br>v = np.ones((3,4))</strong></pre><pre><strong>#let&#39;s apply the rule #1<br>w = np.einsum(&#39;ij,jk -&gt; ijk&#39;,u,v)<br>print (w.shape)<br>print (w)</strong></pre><p><strong>Here we can see the rule #1 is applied and a new dimension is added</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*vMgnAsDp-uDCRgFgoyBwsQ.png" /></figure><p><strong>Now we will apply rule #2 on this. There we will sum along ‘j’ axis and will reduce the dimension. And we can see the results are exactly same.</strong></p><pre><strong>print (np.einsum(&#39;ijk -&gt; ik&#39;,w))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*Fxs-H7frRYL-KiE8MdKCMQ.png" /></figure><p>I hope with the above example einsum notation is clear.</p><h3>Here we will list down some common matrix/vector operations in einsum notation. Link for colab notebook.</h3><p><a href="https://colab.research.google.com/drive/1utaGDbHpNtR_V6h7HBDdiOg6kuRrIxvU?usp=sharing">Google Colaboratory</a></p><p><strong>References:</strong></p><ul><li><a href="https://mathworld.wolfram.com/EinsteinSummation.html">Einstein Summation</a></li><li><a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html">numpy.einsum - NumPy v1.22 Manual</a></li><li><a href="https://ajcr.net/Basic-guide-to-einsum/">A basic introduction to NumPy&#39;s einsum</a></li><li><a href="http://numpy-discussion.10968.n7.nabble.com/einsum-td11810.html">einsum</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e12b8a80570" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ibm-data-ai/einsum-an-easy-intuitive-way-to-write-tensor-operation-9e12b8a80570">einsum — An Easy/Intuitive way to write Tensor Operation</a> was originally published in <a href="https://medium.com/ibm-data-ai">IBM Data Science in Practice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containers and Dockers For Data Scientist]]></title>
            <link>https://medium.com/ai-for-real/containers-and-dockers-for-data-scientist-c9000fb69478?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9000fb69478</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 07:33:00 GMT</pubDate>
            <atom:updated>2020-10-16T18:03:15.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fV62GTR22q1CEtXzl--QoA.png" /><figcaption><strong>Typical Situation</strong></figcaption></figure><h3><strong>Introduction</strong></h3><p>Containerization is buzz word. Everyone talks about docker and containerization. Everyone want their project’s to be containerized because of associated benefit. But challenge is there are very few who understands actually what containers are and how they can be used in Artificial Intelligence based projects.</p><p>I have attended many sessions about Docker but I couldn’t understand much and more importantly how it’s going to help in my role as Data Scientist.</p><p>Objective of this blog is to cover the information that is required to know about containers, what containers are, why they are useful and how to use them as a part of the AI based projects.</p><p>This post is doesn’t cover Dev-Ops information as I don’t know that. This post is about building a concept and understanding and doesn’t deal with syntax/commands of docker.</p><h3><strong>Application Deployment ???</strong></h3><p>Deployment involves all the activities that are required to make an Application run or use in an environment (Development, QA, Production etc).</p><p>This is one of the fundamental step during the SDLC. There are various ways of deploying an application and they evolved over the time.</p><p>To develop intuition and understanding about containers, we need to understand various ways of deployment from historical point of view.</p><p>I will try to explain based upon level of abstraction that each approach provides.</p><h3><strong>Legacy Way — Individual Server — NO ABSTRACTION</strong></h3><p>The legacy way of deploying an application is to request for an individual server to host your application. Dedicated hardware will be used to host your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*y19cUXbhaueKcjdBEi67Ng.png" /><figcaption><strong>Legacy Approach For Deployment</strong></figcaption></figure><p>In this approach you would need to request for machine (hardware), then you would need to setup an OS, then install software and dependencies and then put an application code on it. This is tedious and time consuming process, on a long run such servers becomes difficult to maintain, it doesn’t uses the hardware in an optimal manner, It causes issues in the Application code due to upgrade in OS and Dependencies etc.</p><p>This was not the good way of deploying an application and suffers from major drawbacks as mentioned in the figure.</p><p>Industry needed a solution for this and it gave birth to a concept called <strong>“Virtualization”.</strong></p><h3><strong>Virutalization — Hardware Abstraction</strong></h3><p>Virtualization introduced by VM Ware was a fantastic way of addressing some of the challenges/issues raised by individual server deployment.</p><p><strong>In this approach Hardware (Bare metal) is abstracted by the use of ‘Hypervisors’.</strong></p><p><strong>Hypervisors </strong>let you create and run multiple virtual (guest) machines on a piece of hardware/machine called host machine.</p><p>Hardware is shared between the multiple applications. So multiple applications can be deployed and executed on same machine.</p><p>This looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*6eWv7QCyVNPZr_vvI2m2Gw.png" /><figcaption><strong>Virtualization — 1</strong></figcaption></figure><p>This approach has many benefits like improved hardware utilization as multiple applications can share the hardware, deployment time was reduced to few days instead of moths, comparatively easy to maintain and it was a cost effective solution. But it do suffers from cons like it’s not a truly portable approach as applications are still tied to OS and Hyervisor. Different hypervisor exist for a different platform, since each VM contains OS so they are heavy and their starts time is high so it doesn’t scale so fast.</p><p>We can take look at the below figure to understand Pros and Cons of virtualization approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*SPG9C6DDwl8JE4WpWNjz8A.png" /></figure><p>I think main challenges are VM’s are not fully portable and another issue is they take time to start due to OS startup so it can’t scale instantaneous. In Modern application scalability is huge concern and requirement is to scale in really near time basis.</p><p>Almost all of these challenges has been solved by beautiful concept called <strong>“Containerization”</strong>.</p><h3><strong>CONTAINERS — OS ABSTRACTION — VIRTUALIZING OPERATING SYSTEM</strong></h3><p>Containers basically creates higher level of abstraction by virtualizing operating system. They breaks the coupling between application code and OS.</p><p>Due to this they are very light and contains exactly what is needed to run an application.</p><p><strong>Containers Contains Application Code and Dependencies.</strong></p><p>Since containers doesn’t contain OS so things like OS upgrade etc didn’t impact them. Containers are the snap shot of code and dependencies so dependency management can be implemented easily. Two different applications can use different versions of same dependencies without creating any conflict. We can also control dependency upgrades for each application.</p><p>Deployment time is few minutes for container. Another major advantage of container is they spin very fast as they don’t contain operating system. So they can be used for applications hat needs real time scaling of resources.</p><p>And they are extremely portable so same code can be ported easily without any change so a lot of rework and redundancy is avoided.</p><p>Few Benefits of containers are listed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*zj2C0sMtN2Yw9TGJwiWb7A.png" /><figcaption><strong>Container Benefits</strong></figcaption></figure><p>So we can see a lot of benefits associated with the containers and I hope you can understand what is container and how they help them. But how to do that.</p><h3><strong>How To Create Container ?</strong></h3><p>To create container we can use a popular open source framework called “Docker”.</p><p>The overall flow for creatisng the container looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATffoa_Sh-PiASvFgUcTUQ.png" /><figcaption><strong>Container Creation &amp; deployment Process</strong></figcaption></figure><h3><strong>Example of Containerization</strong></h3><p>Now let’s take an example of AI Application for text classification. This application has three parts:</p><p>a) Orchestration/Middleware written in Java which collect the data.</p><p>b) Data Pre-processing module in Python. Exposed as REST API. Built on libraries like numpy, spacy etc.</p><p>c) Python Classification Engine which runs a Deep learning model. Exposed as REST API. Built on Pytorch, uses word embedding etc.</p><p>To containerize this entire application, We need to ensure few things.</p><ol><li>Decide on number of containers. We can have one container for each module to have better handle on the application. In this case we have three modules so we can create 3 containers.</li><li>We need some way to store the data. Each container will have their own memory but we need a way so that containers can share the data. Things like our code, configuration file and data files should be stored in such a way that all three container can access them.</li></ol><p>This can be done by <strong>“VOLUME CONTAINER”</strong>. Volume containers are the special type of containers which can persist the data. Application Containers (code containers) can mount volume containers. All the application containers mounting same Volume Container can read/write to it. That’s how data can be shared between the container.</p><p>3. Need to bind container to the port. So Container can run it on that port.</p><p>4. Need some way so that containers can communicate with each other without any problem. We can specify a meaningful name while creating container so that they can be accessed by their names. Another thing we need to ensure is all the containers are visible to each other. For example from Orchestration, We should be able to access the pre-processing container and classification module.</p><p>This can be done using “<strong>NETWORK</strong>”. We would need to create a docker <strong>NETWORK</strong>. So all the containers under the same network can be communicate with each other. In this case they make REST calls to each other.</p><p>URI For REST Calls will look like</p><p>https://container_name:bind_port/api_endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*07OEZdXqzRIAP1JbcB64hQ.png" /><figcaption><strong>Containerized Architecture</strong></figcaption></figure><p>Overall there are two steps:</p><ol><li>Create a container image for each of the module by creating respective docker file. One docker file for each container.</li><li>Use the plumbing code to build these containers and stitch them together as an application. So finally it will one Shell script for an entire application.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*p1xehGl0ict951Fpg5X8QQ.png" /><figcaption><strong>Container Build Process full</strong></figcaption></figure><p><strong>Sample Docker File Looks Like:</strong></p><pre><strong>FROM ubuntu:18.04     ## Select a base image                                          </strong></pre><pre><strong>##install python<br>RUN apt-get update -y &amp;&amp; \               <br>apt-get install -y python3 python3-pip python3-dev</strong></pre><pre><strong>##copy python dependencies. they are specified in requirement.txt<br>COPY ./requirements.txt /app/requirements.txt</strong></pre><pre><strong>## change the working directory.<br>WORKDIR /app</strong></pre><pre><strong>##install python dependencies<br>RUN python3 -m pip install -r requirements.txt</strong></pre><pre><strong>COPY . /app                                              </strong></pre><pre><strong>## start the app<br>ENTRYPOINT [ &quot;python3&quot; ]</strong></pre><pre><strong>CMD [ &quot;main.py&quot; ]</strong></pre><p><strong>Sample Application File:</strong></p><pre><strong>#create network                       </strong></pre><pre><strong>docker network create my_network</strong></pre><pre><strong># Create volume container using volume image                      </strong></pre><pre><strong>docker run -idt --name my_volume --net=my_network my_volume:latest</strong></pre><pre><strong>docker attach IMAGE_ID</strong></pre><pre><strong>## Create data pre-processing container using pre-processor image</strong></pre><pre><strong>docker run -idt -p 9097:9097  --volumes-from my_volume --name preprocessor --net=create my_network preprocessor:latest</strong></pre><pre><strong>docker attach IMAGE_ID</strong></pre><p>I have seen confusion around Docker “run” vs “start”. Docker run is combination of build (creating a new container) and then starting it. Run needs to be executed when you want to create and run the container by one command.</p><p>If you just want to create a container then just do docker build. It will not start the container. And you can start the container with Docker “start”.</p><p><strong>After building basic concepts regarding containers, I will suggest you to go and explore the API and command syntax for option available with Docker.</strong></p><p><strong>I hope this blog clears your understanding about the containers and is useful to you.</strong></p><p><strong>Happy Learning !!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9000fb69478" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-for-real/containers-and-dockers-for-data-scientist-c9000fb69478">Containers and Dockers For Data Scientist</a> was originally published in <a href="https://medium.com/ai-for-real">AI For Real</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to take Your Trained Machine Learning Models to GPU for Predictions in 2 Minutes]]></title>
            <link>https://medium.com/ai-for-real/how-to-take-your-trained-machine-learning-models-to-gpu-for-predictions-in-2-minutes-3fca78e62204?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fca78e62204</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 18:56:24 GMT</pubDate>
            <atom:updated>2020-10-08T19:17:39.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*Oi2Y-bdDc0Bj4PGY3n6NRQ.png" /><figcaption>figure — 1</figcaption></figure><p><strong>Problem</strong></p><p>We all encounter above situation when inference or prediction time of our Machine Learning model is high. This specially happens for complicated ensembles models like Random Forest, Gradient Boosting etc. Further prediction time for the model increases with the number of features so larger models have high inference time.</p><p>This overall results in poor response time of API serving a model or long duration batch cycles. We strive for improving performance by using techniques like scaling-up server, use load balancer, run multiple models in parallel etc.</p><p>In the worst case scenario, We look for training a new model that can perform inference in the faster way or retrain the model on the GPU as some of the implementations like xgboost supports GPU based training.</p><p>Now a days most of people/projects have an access to the GPU but they cannot use those GPU’s for improving inference time of existing Trained Sklearn model.</p><p>We need some different approach to solve this.</p><p><strong>Solution:</strong></p><p>In this blog, We will discuss a library from Microsoft Research- Hummingbird, that converts trained scikit-learn models into tensor computations that can run on GPU yielding faster prediction/inference time.</p><p>Hummingbird also allows user to leverage latest neural network like Pytorch to accelerate traditional Machine Learning model.</p><p>Few benefits of using Hummingbird are:</p><ol><li>Latest Improvements — As they are using these latest and evolving framework their models can benefit from current and future improvements/optimization in these frameworks .</li><li>Traditional models can run on GPU’s which is a native Hardware Based Acceleration.</li><li>Performance Improvements (Time Required for Inference Reduction) during the model serving.</li><li>There is no difference in the prediction output of original model and converted model. Model performance stays exactly same.</li><li>As most of the companies are investing in the GPU’s so single infrastructure can be used for running both types of models. It will lead to better and efficient Machine learning operations.</li><li>Converting existing models to Tensor Computation avoid need of retraining these models with the GPU support. This will save a lot efforts and results in a lot of saving.</li><li>Faster Turn Around Time. Converting a model to tensor computation is a matter of one single line of code.</li><li>API of Hummingbird is consistent with SKlearn so model can be changed under the hood with NO change in your code. It’s totally abstracted.</li></ol><p>So overall conversion process looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAg2rkUGxe9HGk_Yo97-9g.png" /><figcaption>figure -2</figcaption></figure><h4>The only thing we need to do is just replace machine learning model in figure -1 with converted model in figure -2. No change in Code At All. Amazing !!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*cbNnfmhEiC7BREFfQV-DDg.png" /><figcaption>Figure — 3</figcaption></figure><p><strong><em>After just replacing the model file you are good to go and you can start using CUDA cores, bandwidth optimization, large number of registers which leads to Faster Computations in GPU.!!</em></strong></p><p>Now let’s look at the code part which is very simple. I am releasing the google colab notebook for the same.</p><p>First Train a scikit-learn model for a classification problem which classifies 3 classes. In the below code we will create fake data and create a classifier.</p><pre><strong>import numpy as np<br>from sklearn.ensemble import RandomForestClassifier</strong></pre><pre><strong>num_classes = 3<br>X = np.random.rand(100000, 50)<br>y = np.random.randint(num_classes, size=100000)<br>randomForestCPU = RandomForestClassifier(n_estimators=10, max_depth=10)<br>randomForestCPU.fit(X, y)</strong></pre><p>Let’s run the prediction using this model which uses CPU to make prediction and compu<strong>te the time for prediction as.</strong></p><p>%%timeit is ipython statement to capture time taken by an execution to complete.</p><pre><strong>%%timeit<br>randomForestCPU.predict_proba(X)</strong></pre><p>We can see the time taken by making predictions over CPU as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdf6aDR3VPeMqIG8T_IdfQ.png" /><figcaption>Inference Time Taken By Model On CPU</figcaption></figure><p><strong><em>Now, We will install hummingbird library and will convert our model in TWO LINE OF CODE. Magic isn’t it ??</em></strong></p><p>First line will convert the model to Pytorch equvivalent and then we need to set the target device of execution of model to GPU (to(‘cuda’))</p><pre><strong>from hummingbird.ml import convert<br># Use Hummingbird to convert the model to PyTorch<br>randomForestGPU = convert(randomForestCPU, &#39;pytorch&#39;)<br>randomForestGPU.to(&#39;cuda&#39;)</strong></pre><p>Let’s go and check the inference time of the GPU based Randomforest that we created in the above step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STL3WTTWAVYIk9f58lOdSg.png" /><figcaption>Inference Time Taken By Model On GPU</figcaption></figure><p><strong>Voila, We can time taken for inference of same number of records on GPU is 19.8 ms and on CPU is 99.1 ms. This 5X reduction in inference time which is a huge huge can.</strong></p><p>Another thing that we would need to ensure is to do sanity check that both the models are producing exact same results otherwise our comparison will not be valid. So we will use following code to compute the class prediction.</p><pre><strong>y_gpu = randomForestGPU.predict(X)<br>y_cpu = randomForestCPU.predict(X)</strong></pre><pre><strong>if False in np.equal(y_gpu,y_cpu).tolist():<br>    print (&quot;prediction mismatched&quot;)<br>else:<br>    print (&quot;prediction matched&quot;)</strong></pre><p>Results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDVAl8kyh1D4B4bF03SUCQ.png" /></figure><p><strong>We can despite reduction in inference time both the models produced exactly same results !!</strong></p><p><strong>Lo and Behold all this without any retraining, without any significant effort, without any accuracy loss and with ONLY two lines of Code. And no change in existing code etc.</strong></p><h3>Summary</h3><p>So we have seen very significant improvement in inference time after using hummingbird converted model. Time reductions are very high and that too without any effort or impacting any of the existing code. We have also noticed that accuracy of original model and converted model is exactly same. So basically there is no effort or cost associated with the process.</p><p>However, these time reductions will be very significant for large models if you attempt to use this approach for small simple models like Linear Regression or Logistic regression it will be a smaller improvement. We did an experiment and below finding shows their is a 3X reduction in run time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eUwnn3bLdWBHhiDbeEKnw.png" /></figure><p>We hope you find this post informative and useful. Please drop your suggestion in the comment box.</p><p><strong>Happy Learning !!</strong></p><p>Code shown in this notebook is present at the below github repo:</p><p><a href="https://github.com/tkhan3/airo/blob/master/hummingbird_cpu2gpu.ipynb">tkhan3/airo</a></p><p>Reference Link For Git Repo For Hummingbird</p><p><a href="https://github.com/microsoft/hummingbird">microsoft/hummingbird</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fca78e62204" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-for-real/how-to-take-your-trained-machine-learning-models-to-gpu-for-predictions-in-2-minutes-3fca78e62204">How to take Your Trained Machine Learning Models to GPU for Predictions in 2 Minutes</a> was originally published in <a href="https://medium.com/ai-for-real">AI For Real</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis (Python) Results in 2 Minutes with Pandas-Profiler.]]></title>
            <link>https://medium.com/ai-for-real/exploratory-data-analysis-python-results-in-2-minutes-with-pandas-profiler-c82386fe1962?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c82386fe1962</guid>
            <category><![CDATA[exploration]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Sat, 03 Oct 2020 09:28:27 GMT</pubDate>
            <atom:updated>2020-10-10T14:02:54.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploratory Data Analysis (Python) in 2 Minutes with Pandas-Profiler.</h3><h4>Problem Introduction</h4><p>Data Exploration is the very first and fundamental task that Data Scientist’s perform as soon as they receive the data.</p><p>Often Data Exploration even in a basic sense takes a lot of time. Though some of the metrices which Data Scientists want to take a look are common for various tasks but they usually don’t have a single code base to run such tasks. And if not every time but most of the time they need to re-write the code, fix the error etc. This results in lot of time.</p><p>There are various reasons for doing data exploration:</p><ol><li>Understanding distribution of various variables.</li><li>Finding percentage of missing values in variables so that data imputation strategies can be formed.</li><li>Discovering interactions between the variables.</li><li>Finding out correlated variables.</li><li>Measuring variability/spread of the variables.</li><li>Discovering the presence and nature of extreme (outliers) values.</li></ol><p>Above are few important reasons for performing data explorations. The above factors directly and prominently impact the quality of output predictions. If they are not accounted while building the model it will result in a very sub-standard quality model that will be of no-use.</p><p>As you can see there are lot of tasks that needs to be done for each and every project for machine learning. And it needs time. Further time needed to accomplish this task increases with increase in the number of variables and number of Data sources you have at your disposal.</p><h4>How do we do this ?</h4><ol><li>We take our data may be shared in an excel sheet or csv file or in a database as source.</li><li>Read the data from the source to Pandas in the Python.</li><li>Then use scipy or Pandas function or matplotlib or some other library to start writing code for this.</li></ol><p>Gosh !! Too much of work if say there are 5 data sources and 200 variables.</p><h4>Solution</h4><p>To do data exploration literally in two minutes, We will use this fantastic python library called “Pandas Profiler” which will do all the tasks for us <strong>in just one line of code.</strong></p><p><strong>You read it right - in just one line of code all the variables at the same time. Amazing isn’it !!</strong></p><p><strong>Let’s take a look at the library:</strong></p><p><a href="https://github.com/pandas-profiling/pandas-profiling">GitHub - pandas-profiling/pandas-profiling: Create HTML profiling reports from pandas DataFrame objects</a></p><p>This is a very simple and easy to use library. It can do a lot of analysis of Structured Data and can help you to do some analysis for unstructured data like images and text. For structured data it can product a lot of matrices and for unstructured data it will generate the report about the metadata of the files.</p><p>To install the library we can just simply run the command:</p><pre>!pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip</pre><p>Then read your dataset as Pandas data frame. In the example I have data inside the excel file so reading the data from excel sheet uploaded on a drive and reading it<strong> inside the pandas.</strong></p><pre><strong>input_data = pd.ExcelFile(&#39;./gdrive/My Drive/dataset/pandas profiler demo.xlsx&#39;)</strong></pre><pre><strong>input_data = input_data.parse(&quot;Sheet1&quot;)</strong></pre><p>We can see in my dataset there are 5 variables and 117580 observation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FqFq0y4gHq5G2peD8GALA.png" /></figure><p>Let’s check the column name and their types:</p><pre><strong>input_data.dtypes</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*0g9Jzqo0iEEj-by4CYmQnA.png" /></figure><p>Now we are ready to start with the exploratory data analysis. First thing that we will do is to select the variables we want to study. Let’s say in this case we want to study x1,x2 and x3. So we will trim our data frame to a have these columns (for simplicity).</p><pre><strong>input_data_trim = input_data[[&#39;x1&#39;,&#39;x2&#39;,&#39;x3&#39;]].copy()</strong></pre><p>Now we will use our ammo to do the data exploration. Let’s import the pandas profiler as:</p><pre><strong>from pandas_profiling import ProfileReport</strong></pre><p>It’s a time to invoke python profiler.</p><pre><strong>profile = ProfileReport(input_data_trim, title=&#39;Profiler Demo&#39;, explorative=True)</strong></pre><p>There are two arguments. “Title” is the name of the profile report and “Explorative” will control the information that we want to produce as output.</p><p>There are various way to see the report. We can see the report with-in the notebook using Ipython widgets or we can save it as html pages and share with larger audience.</p><p>Since we are using colab for the demo let’s generate the output with-in the notebook.</p><pre><strong>profile.to_widgets()</strong></pre><p>Output will look like:</p><p>You can click on any tab and see the results. Below screen shot is the overall summary of the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIqvADF5ySzvtw90X6ZYJQ.png" /></figure><p>We can click on the tab and check all the details. Let’s click on variable.</p><p>There is an analysis for all the variables. Let’s get analysis of “x1”.</p><p>We can see lot of descriptive analysis of the “x1” including missing values, unique, mean, media, IQR, min, max, range, skewness, variance etc.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPNqtrydfCUIbnDapjLhqQ.png" /></figure><p>We can also the histogram to understand the nature of distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QKR8ZJvA3S2WdhsWqGnYA.png" /></figure><p>We can also check the common values and outliers too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz-668QSmPf32LEQpvyYTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H50YOkU-P8HUuTAvi_Eoyg.png" /></figure><p>We can also get the correlation and interaction between the variables by clicking interaction and correlation tabs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYPZQ7Y_NfZ6hNdKsWo8hA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RYHoZAAknxkqRyFplIfbw.png" /></figure><p><strong>Summary</strong></p><p>In this blog post we looked at this amazing library Pandas-Profiler. We have also seen that it’s usage is very easy and simple. This library does a lot of work for us out of the box and without “ANY” effort. If we opt to do manually we might miss some statistics about the data and using this library clearly eliminates that risk.</p><p>We hope you find this post informative and useful. Please drop your suggestion in the comment box.</p><p>Code shown in this notebook is present at the below github repo.</p><p><a href="https://github.com/tkhan3/airo/blob/master/Pandas_Profiler_Demo.ipynb">tkhan3/airo</a></p><p>Happy Learning !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c82386fe1962" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-for-real/exploratory-data-analysis-python-results-in-2-minutes-with-pandas-profiler-c82386fe1962">Exploratory Data Analysis (Python) Results in 2 Minutes with Pandas-Profiler.</a> was originally published in <a href="https://medium.com/ai-for-real">AI For Real</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark With Google Colab:]]></title>
            <link>https://medium.com/ai-for-real/spark-with-google-colab-fd6881e6acd3?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd6881e6acd3</guid>
            <category><![CDATA[sparkwithcolab]]></category>
            <category><![CDATA[colabspark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[sparkoncolab]]></category>
            <category><![CDATA[colab]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 17:40:42 GMT</pubDate>
            <atom:updated>2020-09-05T17:40:42.415Z</atom:updated>
            <content:encoded><![CDATA[<p>We often want to experiment with Spark but gets stuck with the absence of Spark Environment. In this post we will discuss how to setup a Spark environment inside the google colab with the few line of codes and We can use spark right away there in few minutes.</p><p>Below are the steps for installing Spark inside the google colab:</p><ol><li>Pre-requisite for Spark is installing Java. We need to have Java installed before setting-up Spark in colab.</li></ol><p><em>!apt-get install openjdk-8-jdk-headless</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*_uiYboNPohYC2eHwcNrZ9g.png" /></figure><p>2. We will see a message once Java is installed. We can check Java version.</p><p>!java — version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdno2BYGjQgjSxvt200QDA.png" /></figure><p>3. Now we need to download Spark distribution. From Apache website. You can go and check the latest distribution at below link.</p><p><a href="https://archive.apache.org/dist/spark/">Index of /dist/spark</a></p><p><em>!wget </em><a href="https://archive.apache.org/dist/spark/spark-2.4.5/spark-2.4.5-bin-hadoop2.7.tgz"><em>https://archive.apache.org/dist/spark/spark-2.4.5/spark-2.4.5-bin-hadoop2.7.tgz</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdGRaSWdEuKfYl6RCsDbhg.png" /></figure><p>4. We need to extract the Spark distribution downloaded.</p><p><em>!tar xvf spark-2.4.5-bin-hadoop2.7.tgz</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LT5qmCwKVbTeIvbr0PVm-w.png" /></figure><p>5. We can check extracted spark as.</p><p><em>!ls</em></p><p><em>!ls spark-2.4.5-bin-hadoop2.7</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKwOGQoTtD4BRXSZta7TwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TA2o-Xbj1HXFyUCT_UYpw.png" /></figure><p>6. Since spark is Not on system path we would need some way to detect where spark is present. We will use a python library findspark which will add Spark to sys.path and we can use PySpark.</p><p><em>!pip install -q findspark</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFOylFo4qXs7qLtlEp2fKw.png" /></figure><p>7. We need to set environment variables for the JDK and Spark path.</p><blockquote>import os</blockquote><blockquote>os.environ[“JAVA_HOME”] = “/usr/lib/jvm/java-8-openjdk-amd64”</blockquote><blockquote>os.environ[“SPARK_HOME”] = “/content/spark-2.4.5-bin-hadoop2.7”</blockquote><p>8. We need to initialize the findspark to detect the PySpark location as:</p><pre>import findspark<br>findspark.init()</pre><p>9. We can check the PySpark installation as:</p><p><em>findspark.find()</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D35VWOILJdABdAHqff1aiA.png" /></figure><p>10. Now we can initialize and Spark is ready to use in colab:</p><p><em>import pyspark</em></p><p><em>sc = pyspark.SparkContext(appName=”myAppName”)</em></p><p><em>data = [1, 2, 3, 4, 5]</em></p><p><em>rdd = sc.parallelize(data)</em></p><p><em>rdd.collect()</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Neu3PxWYJ386pa3-lSl3hA.png" /></figure><p><strong>Congratulations You Have Setup Spark in Your Colab Environment and it’s ready to use. Code explained in this story can be accessed in my github page as:</strong></p><p><a href="https://github.com/tkhan3/airo/blob/master/Spark_Setup_in_Colab.ipynb">https://github.com/tkhan3/airo/blob/master/Spark_Setup_in_Colab.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd6881e6acd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-for-real/spark-with-google-colab-fd6881e6acd3">Spark With Google Colab:</a> was originally published in <a href="https://medium.com/ai-for-real">AI For Real</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relationship between Cosine Similarity and Euclidean Distance.]]></title>
            <link>https://medium.com/ai-for-real/relationship-between-cosine-similarity-and-euclidean-distance-7e283a277dff?source=rss-284044362ce1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e283a277dff</guid>
            <category><![CDATA[euclidean-distance]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[distance-metric]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <dc:creator><![CDATA[Tanveer Khan]]></dc:creator>
            <pubDate>Tue, 10 Mar 2020 14:24:16 GMT</pubDate>
            <atom:updated>2020-03-10T14:43:52.513Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of us are unaware of a relationship between Cosine Similarity and Euclidean Distance. Knowing this relationship is extremely helpful if we need to use them interchangeably in an indirect manner. One application of this concept is converting your Kmean Clustering Algorithm to Spherical KMeans Clustering algorithm where we can use cosine similarity as a measure to cluster data.</p><h3>Use Case:-</h3><p>We often want to cluster text documents to discover certain patterns. K-Means clustering is a natural first choice for clustering use case. K-Means implementation of scikit learn uses “Euclidean Distance” to cluster similar data points.</p><p>It is also well known that Cosine Similarity gives you a better measure of similarity than euclidean distance when we are dealing with the text data.</p><p>So We may want to run Kmeans using cosine distance which is not possible in the case of scikit learn implementation.</p><p>We can use hack — if some how convert euclidean distance as some proportionate measure of cosine distance then this can be achieved.</p><h3>Mathematics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aiif-BY_Z_l8RMbN4--rA.jpeg" /></figure><h3>Proof with Code</h3><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>logging</strong><br><strong>import</strong> <strong>scipy.spatial</strong><br><strong>from</strong> <strong>sklearn.metrics.pairwise</strong> <strong>import</strong> cosine_similarity<br><strong>from</strong> <strong>scipy</strong> <strong>import</strong> sparse<br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> metrics<br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> preprocessing<br><strong>from</strong> <strong>sklearn.metrics.pairwise</strong> <strong>import</strong> euclidean_distances</pre><pre>np.random.seed(42)</pre><pre>test_array = np.random.rand(3,100)</pre><pre><strong>for</strong> item <strong>in</strong> range(test_array.shape[0]):   <br>    element = test_array[item]   <br>    print (element.transpose().dot(element)</pre><p><strong>output</strong></p><pre>30.868488161326475<br>33.289148886695116<br>35.31491104309238</pre><p>Normalizing Vectors</p><pre>X_normalized = preprocessing.normalize(test_array, norm=&#39;l2&#39;)<br>euclidean_dist = euclidean_distances(X_normalized)<br>squared_euclidean = np.square(euclidean_dist)<br>print (squared_euclidean)</pre><p>output</p><pre>[[0.         0.55794124 0.54552104]<br> [0.55794124 0.         0.56962493]<br> [0.54552104 0.56962493 0.        ]]</pre><p>Computing cosine similarity</p><pre>adjusted_cosine_distance = 2 - 2*cosine_similarity(X_normalized)<br>print (adjusted_cosine_distance)</pre><p>output</p><pre>[[6.66133815e-16 5.57941240e-01 5.45521039e-01]<br> [5.57941240e-01 2.22044605e-16 5.69624926e-01]<br> [5.45521039e-01 5.69624926e-01 6.66133815e-16]]</pre><p><strong>We can see from above that when vectors u and v are normalised then there exist a relationship between cosine similarity and euclidean distance.</strong></p><p><strong>For Normalised Vectors:</strong></p><p><strong>Euclidean Distance (u,v) = 2 * (1- Cosine Similarity(u,v))</strong></p><p><strong>Euclidean Distance (u,v) = 2 * Cosine Distance(u,v)</strong></p><p><strong>Hack :- So in the algorithms which only accepts euclidean distance as a parameter and you want to use cosine distance as measure of distance, Then you can convert input vectors into normalised vector and you will get results as per the cosine distance.</strong></p><p><em>Hope above explanation has cleared your understanding about relationship between euclidean distance and cosine similarity.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e283a277dff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-for-real/relationship-between-cosine-similarity-and-euclidean-distance-7e283a277dff">Relationship between Cosine Similarity and Euclidean Distance.</a> was originally published in <a href="https://medium.com/ai-for-real">AI For Real</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>