<?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 Navarasu on Medium]]></title>
        <description><![CDATA[Stories by Navarasu on Medium]]></description>
        <link>https://medium.com/@navarasu?source=rss-8df2e9eedd42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dXpAGaff1NqVzzPd2LtC_g.png</url>
            <title>Stories by Navarasu on Medium</title>
            <link>https://medium.com/@navarasu?source=rss-8df2e9eedd42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:50:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@navarasu/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[Visually Debug, Log and Test an Image Processing Code Using OpenCV and Python]]></title>
            <link>https://blog.francium.tech/visually-debug-log-and-test-an-image-processing-code-using-opencv-and-python-36e2d944ebf2?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e2d944ebf2</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Fri, 06 Dec 2019 13:59:29 GMT</pubDate>
            <atom:updated>2021-01-08T16:45:07.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Visually Debug, Log and Test an Image Processing Code using OpenCV and Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjiWAGDJXHYkIx0wGVmjRA.jpeg" /><figcaption>Image by <a href="https://pixabay.com/photos/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1209823">Free-Photos</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1209823">Pixabay</a></figcaption></figure><p>As a Programmer, we are well familiar with logging, debugging and testing our regular program.</p><p>i.e.,</p><ul><li><strong>Log</strong> the data value to record the behavior of the program and see it offline.</li><li>Log them at various <strong>log</strong> <strong>levels</strong> to see the only preferred level of the log. E.g.<em>,</em><em>ERROR, DEBUG, TRACE, INFO, WARN, etc.</em></li><li><strong>Debug</strong> the program locally and view the data value at a debug point. We drive through code by navigating to the next step or next debug point by pressing some short keys.</li><li><strong>Test </strong>the code by comparing the expected data and report the failure as Pass or Fail. Record the failure data or error raised by the program for failure analysis.</li></ul><p>In the fast-growing computer vision projects and its related programming, I see there is a need for similar kind requirements.</p><p>While working in computer vision projects, I had lots of requirements to handle the logging, debugging and test reporting efficiently. Surprisingly I didn’t see any utility packages in python to satisfy the needs expect one package which is very preliminary and unmaintained.</p><p>So I had started implementing those requirements as utilities into projects and it makes my code clean, productive and maintainable. Later I have published a few of them as a python package called <a href="https://pypi.org/project/opencv-log/"><strong>opencv-log</strong></a></p><p><a href="https://pypi.org/project/opencv-log/">opencv-log</a></p><p>Through this blog, I like to discuss those requirements and its implementation for visually logging and testing using OpenCV and python.</p><h3>Image Processing Data Aspect</h3><p>In the regular program, data are mostly human-readable to log, debug and compare.</p><p>While here, we process a digital image represented as a number matrix. We apply various image processing techniques to transform the image or extract the required information. The data are mostly the number, binary or large matrices. Such data are not human-readable but it can be visualized for interpretation.</p><h4>Data Visualization</h4><p>In image processing, it is not just an image matrix to be visualized. We get a different type of data at the various stage as an output of image processing techniques.</p><blockquote>For e.g., We apply various techniques on the image like filtering, thresholding, feature extraction, feature matching, transformation, segmentation, edge and contours detection, hough lines detection, morphological operation, color analysis, and machine learning, etc.,</blockquote><p>The output of each technique has to be visualized differently, to analyze them. E.g.,</p><ul><li>For thresholding, smoothing, edge detection, and morphological operation, the output is a matrix just that can be visualized as image. i.e. convert the matrix to the image. ( cv2.imwrite , cv2.imshow)</li><li>For contour, hough lines and feature detection, the output are coordinates and we draw the output on the input image. ( cv2.drawContours, cv2.drawKeypoints, cv2.drawMatches, cv2.line, cv2.rectangle)</li><li>For color analysis, we draw the color to visualize it.</li><li>For histogram and other data analysis, we plot them using matplotlib.</li></ul><h3>Visual Debugging \ Logging</h3><p>Every computer vision developer is aware of all the above visualizations techniques. They are basics of image processing and is not any new idea to discuss in detail.</p><p>In general, at the analysis stage, we all play with this visualization in finding the right algorithms to analyze and extract or transform the image as per the business requirements. Once the code is matured for the implementation stage, we mostly wind up all the debugging lines and move only the actual image processing code for production.</p><p>Again when we find an issue in testing or production, we put these debugging lines back into code wherever required to find the issue. We will be adding visualization for major steps and then we will be moving to minor steps to corner the issue.</p><h4>Requirements</h4><p><em>My requirements are quite simple, basic and most needed, they are,</em></p><ul><li>First thing, I want the visual debugging lines to reside in my production code as a sleeper cell. Whenever needed, I will activate them.</li><li>It should have two ways of activations, it should act as a debugger or it should act as a logger.</li></ul><p><strong><em>Logger Mode</em></strong></p><ul><li>In logger mode, it should behave like our regular logger. It should log the images in a readable format.</li><li>The data can be saved as an image file and load in HTML organized directly logging base64 image string to the HTML.</li><li>Like logger, we can log based on levels at least three levels like ERROR, INFO and TRACE</li><li>Log only in case of error or validation failure ( ERROR level)</li><li>Log only major steps along with error steps (INFO level) or include the minor steps as well (TRACE level).</li></ul><p><strong><em>Debugger Mode</em></strong></p><ul><li>In debugger mode, it should behave exactly behave like ide based debugger.</li><li>It should show the visualization as a popup window using something like cv2.imshow</li><li>If I press a short key, it should move to the next debug point and if the press ESC to should exit the program.</li><li>We can use the same logger level here, show the image for the data value only for error case or show me major steps alone or include minor steps as well.</li></ul><p><strong><em>Log utilities</em></strong></p><ul><li>Apart from logging the matrix as an image, we can also add utils logging other data.</li><li>E.g., if we need to see the hough lines, we take the previous output image or original image and we draw the line over it. The image used for drawing should be cloned. So that actual image not disturbed.</li><li>These steps can be made into util function like log_houghlines . Similarly, for all the possible outputs if we have util to log, it will save lots of time.</li></ul><p>You can see these implementations of these features in the opencv-log package,</p><pre>pip install opencv-log</pre><p><em>An Example from the </em><em>opencv-log package,</em></p><pre>import cvlog as log</pre><pre># Set default mode and level<br># If we dont set, then default mode is NONE<br># and the default level is ERROR</pre><pre>log.<strong>set_mode</strong>(log.<strong>Mode</strong>.LOG)<br>log.<strong>set_level</strong>(log.<strong>Level</strong>.TRACE)</pre><pre>img = cv2.imread(&quot;sample.png&quot;)</pre><pre><em># log or show the image or do nothing based on log mode and log level</em></pre><pre>log.<strong>image</strong>(log.<strong>Level</strong>.INFO, img)</pre><pre># If mode is None, it remain as sleeper cell<br># If mode is LOG, it logs image to html file.<br># If mode is DEBUG, it shows image in pop window and wait for the key.</pre><p>This is a sample HTML log created using the logger mode,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xU71AXcvCfbdjT8CEaztJw.png" /></figure><h3>Visual Testing</h3><p>Testing an image processing code requires human intelligence to confirm whether it is processed as expected. It cannot be automated completely. But it can be semi-automated with test reporting as a helper tool.</p><p>During the implementation stage, we have a set of image types and we tune the code to match all the criteria for the different image types.</p><p>Then to fine-tune and make production-ready, we test with a bunch of test images to find the failure cases. Ultimately, we need the report of failed images. Then after fine-tuning, we iterate the test. Also, we may need to cross-compare with the previous report.</p><h4>Requirements</h4><p><em>The requirements can be simplified as below,</em></p><ul><li>The test should iterate with a list of images as file paths and process it using the processing script to be tested.</li><li>It should show me the processed image or results in a popup window one by one.</li><li>Manually, we confirm it as pass or fail by pressing any key. It generates a report with the result.</li><li>In case of failure, it records the output image and in case of any error, it records the error.</li><li>The report can be saved as a CSV or HTML file</li><li>In the case of HTML, we can combine the above logging features to make the report more informative to debug the actual issue.</li></ul><p><em>An Example from the python package,</em></p><pre>import cvtest as test</pre><pre># Process Image from image path<br>def <strong>process_image</strong>(imagepath):<br>    img = cv2.<strong>imread</strong>(imagepath)<br>    # after processing...<br>    <strong>return</strong> img</pre><pre><strong>test_image_paths</strong>=[&quot;example1.png&quot;,&quot;example1.png&quot;,&quot;error.png&quot;]</pre><pre># This shows image using cv2.imshow,</pre><pre>test.<strong>report</strong>(test_image_paths, process_image)</pre><pre># On presssing &#39;y&#39; key, it report it as PASS<br># On pressing any other key, it report it as FAIL and save output image for verification<br># On any exception, it report it as ERROR with exception stack</pre><p>You find a few of the implementation in the below repo,</p><p><a href="https://github.com/navarasu/opencv-log">navarasu/opencv-log</a></p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="/service/mailto:contact@francium.tech"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e2d944ebf2" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/visually-debug-log-and-test-an-image-processing-code-using-opencv-and-python-36e2d944ebf2">Visually Debug, Log and Test an Image Processing Code Using OpenCV and Python</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Multiple Elastic Search in Rails]]></title>
            <link>https://blog.francium.tech/using-multiple-elastic-search-in-rails-c7263305731e?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7263305731e</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 09:25:38 GMT</pubDate>
            <atom:updated>2019-11-14T09:26:26.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akMVMnztqc0uPwYI1y9UFg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/Pexels-2286921/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1868894">Pexels</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1868894">Pixabay</a></figcaption></figure><p>For the Multi Database support i.e. managing model-specific database connection, we were waiting for Rails 6. It enhances our application to scale on the database level. You can check the below blog for some more details.</p><p><a href="https://blog.francium.tech/amazing-features-of-rails-6-0-ddb1a616b0af">Amazing features of Rails 6.0</a></p><p>Similarly, we had a requirement to have multiple elastic search application for an architectural reason. That is we need to configure the elastic search specific to model. It is not a bigger deal like maintaining a database connection. In elastic search, it is just an API level integration.</p><p>With <a href="https://github.com/elastic/elasticsearch-rails">elasticsearch-rails</a> gem, it can be simply configured by assigning the client directly to __elasticsearch__.client of the model.</p><p>For example, if you have a model Article,</p><pre>class Article &lt; ActiveRecord::Base<br>  include Elasticsearch::Model<br>end</pre><p>The elastic search client can be assigned directly to the model in the following way,</p><pre>Article.__elasticsearch__.client = Elasticsearch::Client.new url: “http://127.0.0.1:9200&quot;</pre><p>In our case, we have configured two elastic search clients, one specific to two models and another for remaining models.</p><p>The initializer configuration of the above is as,</p><pre><em>initializers/elastic_search.rb</em></pre><pre><strong>#Elastic Search for all Model Files</strong></pre><pre>Elasticsearch::Model.client = Elasticsearch::Client.new url: &quot;http://main_elastic_host/&quot;, log: false</pre><pre><strong>#Configure Separate elastic search for Specific Model Files</strong></pre><pre>secondary_client = Elasticsearch::Client.new url: &quot;http://second_elastic_host&quot;, log: false</pre><pre>[Model1, Model2].each do |model|<br>  model.__elasticsearch__.client = secondary_client<br>end</pre><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="/service/mailto:contact@francium.tech"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7263305731e" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/using-multiple-elastic-search-in-rails-c7263305731e">Using Multiple Elastic Search in Rails</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started with Machine Learning in Visual Studio Code and Jupyter]]></title>
            <link>https://blog.francium.tech/get-started-with-machine-learning-in-visual-studio-code-and-jupyter-158d17cdc55e?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/158d17cdc55e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Tue, 05 Nov 2019 09:23:33 GMT</pubDate>
            <atom:updated>2019-11-10T12:48:19.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q44ZZUV7w0_F0erjcCAJSQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nordwood?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NordWood Themes</a> on <a href="https://unsplash.com/s/photos/office-desk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In General, we will be often switching to the browser for executing the Jupyter notebook file (.ipynb) while we spent the most time with our favorite Visual Studio Code Editor for editing .py file.</p><p>Like bringing in all languages to the single editor, VS Code solved this problem as well by integrating the jupyter notebook with it. Especially, the option to execute a .py file like a .ipynb file using comment syntax makes me avoid maintaining a separate .ipynb for debugging purposes.</p><p>In the previous article, we were setting up the environment using Anaconda and we have seen explored the jupyter notebook.</p><p><a href="https://blog.francium.tech/get-started-with-machine-learning-handy-python-tools-a1ce97085837">Get Started with Machine Learning — Handy Python Tools</a></p><p>In this blog, We will see an alternative way of setting up the environment using the Visual Studio Code and explore the VS code Jupyter extension.</p><h3>Setting up the Tools</h3><p>There lots of ways to install python. If we use <strong>PyEnv</strong>, we can easily manage multiple python versions like RVM for ruby.</p><h4><strong>Install PyEnv</strong></h4><pre>curl https://pyenv.run | bash</pre><p><strong>Important: </strong>You need to add the .pyenv\bin path to your .bashrc\.zshrc . You will get the details at the end of the installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwgVSMapYS6snQzNJs1I6g.png" /></figure><p>Once added these three lines to .bashrc or .zshrc , restart the terminal.</p><h4><strong>Install Python</strong></h4><p>Install Python using pyenv and get it as a global python.</p><pre>pyenv install 3.7.5</pre><pre># you can get the global python</pre><pre>pyenv global 3.7.5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZn0XglG6y8Py3_Lge3nng.png" /></figure><h4>Install Visual Studio Code and Python Extention</h4><p>Download and Install Visual Studio Code using the installer from <a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a> and install python extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjFfCEvfT1aO2KnzvYepsg.gif" /></figure><h4>Install Jupyter</h4><p>Install jupyter using pip, pip install jupyter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_IGWikRZc6vSU_FEPerRWQ.gif" /></figure><h4>Install ML Basic Libraries</h4><pre>pip install scikit-learn</pre><pre>pip install pandas</pre><pre>pip install seaborn</pre><pre>pip install tensorflow</pre><pre>pip install Keras</pre><p>Here scikit will install numpy &amp; scipy and seaborn will install matplotlib as dependencies.</p><h3>Using Jupyter Notebook in VS Code</h3><p>Create a new file with .ipynb extension</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Th5uMWy6Z7-c6b9BbMXfvw.gif" /></figure><p>Select the python version where the jupyter and other ml libraries installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpkUHIkDw756-ZaVF-iyaQ.gif" /></figure><p>Let&#39;s run-first code by typing the code and hitting SHITF + RETURN</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNEFbDc0wkMrNG5Ccr_P0g.gif" /></figure><h3>Beyond Jupyter</h3><p>Visual studio code notebook extends the jupyter notebook really to the next level by bringing in the following benefits,</p><h4><strong>Single Environment</strong></h4><p>First most thing, we get a single environment for managing notebook files along with python files. Else I need to take care of using the same python kernels for both.</p><h4><strong>Code Completion</strong></h4><p>IntelliSense support for code completion and parameter hints which we badly miss in the browser jupyter version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfWKVtKdYKXcguKsbsBTLg.gif" /></figure><h4><strong>Data viewer</strong></h4><p>Data viewer provides an option to view our data like excel and we can sort and filter data for debugging. I love this feature as it saves much of my time. During data preprocessing, this helps to do manual cross verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stEikM1KkfyKyBImQPyDEg.gif" /></figure><h4><strong>Running Python file like Notebook</strong></h4><p>By typing this comment text # %%before and after the piece of code, VS code treats the single piece of like notebook cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7DXCxx7DewAFFjmIIwMwQ.gif" /></figure><p>Also, we can use the comments section as a markdown notebook cell.</p><pre># %% [markdown]<br># # This is example notebook title</pre><p>Finally, We can export this python file to .ipynb . I have started using this comment into my production code and helps me in debugging like a charm.</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="/service/mailto:contact@francium.tech"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=158d17cdc55e" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/get-started-with-machine-learning-in-visual-studio-code-and-jupyter-158d17cdc55e">Get Started with Machine Learning in Visual Studio Code and Jupyter</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started with Machine Learning — Handy Python Tools]]></title>
            <link>https://blog.francium.tech/get-started-with-machine-learning-handy-python-tools-a1ce97085837?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ce97085837</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 10:08:39 GMT</pubDate>
            <atom:updated>2019-10-21T10:08:39.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Get Started with Machine Learning — Handy Python Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNRGaFHQ6MXMUviSvgr_PQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@seanpatrickphotography?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Sean Patrick </a>from <a href="https://www.pexels.com/photo/person-with-tattoo-holds-python-2005922/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>As part of the machine learning series, this article covers the necessary environmental setup to get hands dirty with machine learning in python.</p><h4>Why Python?</h4><p>There are many programming languages providing machine learning ecosystems like <em>R, Python, Scala, Julia, and also Java.</em></p><p>Among them, Python is always the favorite choice mainly due to simplicity and extensive well-tested frameworks &amp; libraries. It has a great community of developers that we can understand from below <a href="https://insights.stackoverflow.com/survey/2019/#technology">Stack Overflow’s Developer Survey 2019</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLvg6TD05hpUYUVH0YJ-pQ.png" /><figcaption>% of developers who are developing with the language or technology and have expressed interest in continuing to develop with it</figcaption></figure><p>Below is the <a href="https://www.jetbrains.com/research/python-developers-survey-2018/">Survey of JetBrains 2018</a> for python usage, we can see data analysis and machine learning leading the chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v56fq8a18r0GE6Y9N9ZJ-Q.png" /></figure><p>|Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/e30fbcd9-f595-4a9f-803d-05ca5bf84612">here</a> for basic python data camp cheat sheet</p><h3>Anaconda</h3><p>Anaconda is a one-stop setup to get you started faster with machine learning. It brings all required tools and libraries for machine learning including python language gets installed to your system.</p><h4>Setup Anaconda</h4><p>You download the GUI\ CLI based installer from <a href="https://www.anaconda.com/distribution/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGiAbqR8VEJCJSRTY9UUrQ.png" /></figure><p>It installs python and dependent packages for machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jXX5ThRuIdgapJYelTLbg.png" /></figure><p>It brings the following major tools,</p><ul><li><strong><em>Conda</em></strong><em> — for dependency and environment management.</em></li><li><strong><em>Jupyter Notebook </em></strong><em>— The best IDE for machine learning.</em></li><li><strong><em>Data Analysis</em></strong><em> libraries — Numby, Pandas, Dask,etc.,</em></li><li><strong><em>Data Visualisation</em></strong><em> libraries — Matplotlib, Seaborn, etc.,</em></li><li><strong><em>Machine Learning and Deep Learning</em></strong><em> libraries — Scikit learn, Tensorflow, Keras, etc.,</em></li><li>And other 200 related libraries.</li></ul><p>Run conda list to see the list of packages installed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*47ZooY6a1rZ-2xg6SbR5Wg.png" /></figure><h3>Jupyter Notebook</h3><p>With Ananconda installation, we get this powerful IDE, <strong><em>Jupyter Notebook</em></strong> which saves lots of time when your working with machine learning.</p><p>You can start from the terminal by typing jupyter notebook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXRBra04UpczgneRGRkhTg.png" /></figure><p>It is a browser-based IDE that starts in the above port. By clicking New &gt; Python3, we can create our first notebook to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0deOq6NSrQBc11vQgGQv7w.png" /></figure><p>Let’s run the first script by typing and press SHIFT + ENTER</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfYPRTxaI8rG_zm8TKAiRw.png" /></figure><p>It is almost like python console, you can notice the last line code is printed automatically and a new line created for running the next command.</p><p>Beyond a python console, it can do lots like</p><ul><li>We can go back and re-run the previous command.</li><li>It displays machine learning data in tabular format.</li><li>It can display graphs and images inline below the command.</li><li>Easy to add documentation and share as a single file to explain your concept &amp; code.</li><li>and a lot more.</li></ul><p>It stores the notebook like as .ipynb and you can surf for lots of notebook files shared by other developers explaining the machine concepts &amp; code.</p><blockquote>Refer <a href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Jupyter_Notebook_Cheat_Sheet.pdf">here</a> for jupyter notebook data camp cheatsheet</blockquote><h3>Conda</h3><p>Conda is the package and environment manager bundled with Anaconda.</p><p>We can maintain multiple python environments and we can switch between them using conda . It is an alternative to virtualenv .</p><p>The command conda env list gives a list of environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*p0eePC06Xu_Ukq4Nv5IZwg.png" /></figure><h4>Install Conda Extention for Notebook</h4><p>To use the conda environment in jupyter, we need to install nb_conda</p><pre>conda install nb_conda</pre><p>This adds a new tab to jupyter for managing conda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBdeiHOgr0NFBSrdlDXFyw.png" /></figure><blockquote>Refer <a href="https://github.com/conda/conda-docs/files/1252315/conda-cheatsheet.pdf">here</a> for condas cheatsheet</blockquote><h3>Know Your ML Libraries</h3><h4>Numpy and Pandas</h4><p>In machine learning, we deal with matrices of data which is basic of all libraries.</p><p><strong><em>NumPy</em></strong> is the most popular library in python for managing large n-dimensional arrays with matrix manipulation operations.</p><blockquote>Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/e9f83f72-a81b-42c7-af44-4e35b48b20b7">here</a> for numpy data camp cheatsheet.</blockquote><p><strong>Pandas</strong> provide high-level data manipulation tools <em>built upon </em><strong><em>NumPy. </em></strong>Pandas provide an in-memory table object like a spreadsheet with column names and row labels called Dataframe. You can also load data from CSV or Database. Additionally, it has the option to create pivot tables, computation, and plotting graphs.</p><blockquote>Refer <a href="http://datacamp-community-prod.s3.amazonaws.com/dbed353d-2757-4617-8206-8767ab379ab3">here</a> for basic panadas data camp cheatsheet and look <a href="https://datacamp-community-prod.s3.amazonaws.com/9f0f2ae1-8bd8-4302-a67b-e17f3059d9e8">here</a> for advanced operations</blockquote><h4>Scipy and Scikit Learn</h4><p><strong>SciPy</strong> provides algorithms and functions core for scientific computation, like optimization, linear algebra, integration, interpolation, special functions, FFT, signal and image processing. It is<em> built upon </em><strong><em>Numpy.</em></strong></p><blockquote>Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/5710caa7-94d4-4248-be94-d23dea9e668f">here</a> for scipy data camp cheatsheet.</blockquote><p><strong>Scikit-learn</strong> is <em>built upon </em><strong><em>Numpy</em></strong><em> and </em><strong><em>SciPy</em>. </strong>It is a collection of classical and advanced machine-learning algorithms and techniques.</p><blockquote>Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/5433fa18-9f43-44cc-b228-74672efcd116">here</a> for scikit data camp cheatsheet.</blockquote><h4>Matplotlib and Seaborn</h4><p><strong>Matplotlib</strong> is a 2-dimensional plotting library like lots, histograms, power spectra, bar charts, error charts, scatterplots, etc., with just a few lines of code.</p><blockquote>Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/28b8210c-60cc-4f13-b0b4-5b4f2ad4790b">here</a> for matplotlib data camp cheatsheet.</blockquote><p><strong>Seaborn</strong> is a data visualization library<em> based on </em><strong><em>matplotlib</em></strong>. It provides a high-level interface for drawing attractive and informative statistical graphics.</p><blockquote>Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/f9f06e72-519a-4722-9912-b5de742dbac4">here</a> for seaborn data camp cheatsheet.</blockquote><h4>TensorFlow and Keras</h4><p><strong>Tensorflow</strong> is a backend platform for machine learning for building and training deep neural networks. It provides APIs in most environments needed like Android, IoS, Mac OS, Windows, Linux, and Raspberry Pi.</p><p><strong>Keras is</strong> a high-level API that is built on top of TensorFlow. we can build neural networks quickly with the Model and the Sequential API in Keras.</p><blockquote>Refer <a href="https://datacamp-community-prod.s3.amazonaws.com/94fc681d-5422-40cb-a129-2218e9522f17">here</a> for keras data camp cheatsheet.</blockquote><p>You can follow below Machine learning Series, to get your hand dirty with a machine learning concept and examples</p><p><a href="https://blog.francium.tech/get-started-with-machine-learning-part-1-e24e980fa8a8">Get Started with Machine Learning - Part 1</a></p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="/service/mailto:contact@francium.tech"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ce97085837" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/get-started-with-machine-learning-handy-python-tools-a1ce97085837">Get Started with Machine Learning — Handy Python Tools</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Machine Learning for Color Calibration  with a color-checker]]></title>
            <link>https://blog.francium.tech/using-machine-learning-for-color-calibration-with-a-color-checker-d9f0895eafdb?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f0895eafdb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 10:05:54 GMT</pubDate>
            <atom:updated>2019-10-22T12:37:03.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Machine Learning for Color Calibration with a Color Checker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoEteXXsuW_LT2w5GxoukQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/YEYEQINQIN-3533307/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1744817">YEYEQINQIN</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1744817">Pixabay</a></figcaption></figure><p><strong>Computer Vision</strong> plays a vital role in Artificial Intelligence. In Francium Tech, we have delivered numerous solutions specifically in that field. Especially in <em>Document segmentation, Noise removal in the documents, Form Detection, Optical character recognition, Face Authentication and video Anti-spoofing,</em> etc.,</p><blockquote>Those solutions addressed major problems in the <em>financial</em>, health care, and insurance industry.</blockquote><h4><strong>Color Calibration</strong></h4><p><strong>Color Calibration</strong> is one of the segments that we addressed for a biological discipline. Apart from object detection and segmentation, it requires color correction for a color-based analysis.</p><p>The major problem in color analysis is that it is hard to control the lighting condition while taking the photo. The same color will be measured as a different color for photos taken under different lighting conditions.</p><blockquote>Color calibration applied in many disciplines like space research, health care, food industry, and other color-managed workflow.</blockquote><h3>Problem Statement</h3><p>Our problem is somewhat similar to the color calibration used in the photography field using the color checker chart. The image has a set of known color regions like a color checker (not exactly) and we need to find the actual color of the unknown region which is used for clinical analysis.</p><h4>Example Data</h4><p>For example, Let&#39;s take the <a href="https://en.wikipedia.org/wiki/ColorChecker">Color Checker</a> image example from its Wikipedia page.</p><p><em>Below are images of </em><strong><em>Macbeth ColorChecker </em></strong><em>(cardboard with 24 squares of painted samples) and photo with the color checker chart taken with certain lighting conditions</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HIui3BErUTtMb2TRXbBBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*QoMeOyhAVSOndh7ueAAH0w.jpeg" /><figcaption><strong>(A) </strong><em>Macbeth ColorChecker chart with sRGB number for the 24 squares. </em><strong><em>(B)</em></strong><em> The image with the color checker chart taken under certain light condition</em></figcaption></figure><p>Here,</p><ul><li>The <strong><em>actual</em></strong> colors of the 24 squares can be extracted from the <strong><em>right</em></strong> side image using OpenCV. We take it as input, X</li><li>We know the colors of these 24 squares from the <em>Macbeth ColorChecker chart. </em>We take it as output, Y</li></ul><p>Using the extracted color of as input(X) and actual colors of the known color region as output(Y), we need to find the transformation relationship(function) between X and Y.</p><p>Using the transformation relationship, we can calibrate the color of the unknown regions in the image.</p><h4>Colors Representation</h4><p>Images are digitally represented in n-dimensional space holding the color details. In Computer Vision, the images are read as 2 dimensional bit array holding the value of pixel value. Each pixel value can be represented in a different color model called color space like RGB, LAB, HSV.</p><blockquote><strong>Color space </strong>is a mathematical representation of color as tuples of numbers, typically as 3 or 4 values. For e.g., RGB is representation colors using <a href="https://en.wikipedia.org/wiki/Additive_primary_colors">additive primary colors</a>, Red, Blue and Greeen</blockquote><h4>Data Set</h4><p>The actual color of the 24 squares is,</p><pre><strong>reference_colors</strong> = [[115,82,68],[194,150,130],[98,122,157][87,108,67],[133,128,177],[103,189,170],[214,126,44],[80,91,166],[193,90,99],[94,60,108],[157,188,64],[224,163,46],[56,61,150],[70,148,73],[175,54,60],[231,199,31],[187,86,149],[8,133,161],[243,243,242],[200,200,200],[160,160,160],[121,122,121],[85,85,85],[52,52,52]]</pre><p>Below is the color of the 24 squares extracted from the photo using open cv <em>(by segmentation and finding the most dominant color)</em>.</p><pre><strong>extracted_color</strong> = [[121,95,67],[209,178,148],[139,146,171],[108,130,65],[171,156,182],[182,208,183],[215,149,59],[96,88,178],[201,109,99],[82,51,101],[190,209,92],[219,181,65],[54,46,151],[123,177,90],[188,83,53],[226,211,74],[200,108,151],[105,152,184],[235,231,219],[219,214,197],[196,189,172],[153,147,131],[75,84,80],[32,33,37]]</pre><blockquote>One of the most important factors to consider when dealing with color calibration is having a valid source. If the color measuring source does not match the display’s capabilities, the calibration will be ineffective and give false readings.</blockquote><h3>Using Machine Learning</h3><p>If we look at the problem closely,</p><ul><li>We can understand this a supervised machine learning problem as we have known the output Y.</li><li>It is a regression problem as the value to be predicted is continuous.</li><li>Here the output is multidimensional. So, it is <strong>multivariate </strong>regression</li></ul><p>In machine learning, this case is solved using <em>multivariate algorithms</em> like Partial Least Squares or by combining <em>polynomial algorithms</em> or using a <em>neural network.</em></p><p>Also, it can be solved using a <a href="https://en.wikipedia.org/wiki/Spline_(mathematics)">spline</a>-based technique like Thin plate spline as explained in <a href="https://www.ncbi.nlm.nih.gov/pubmed/22969337">this paper</a></p><p>Using a neural network is an expensive idea for color calibration techniques as it takes more time to train. We will try a few other concepts in this blog.</p><h4>Using Partial Least Squares</h4><p>In simple word, PLS find the fundamental relations between two matrices (X and Y) by,</p><ul><li>reducing both X and Y dimension using PCA, and</li><li>finding the relation between the dimension reduced variable and label.</li></ul><p>Lets, try it with the scikit PLSRegression method for the data set.</p><p>Train with extracted_colors and reference_colors using PLS,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RRQGDyZPgzyZIz_vRPOLw.png" /></figure><p>The R Square score shows that color fitting is not bad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuspzB56vUHHSFTaw2R2cQ.png" /></figure><p>Let&#39;s check this model by calibrating the entire picture,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8R0cShcQwB0D_3ziFkv-XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSj02mmurNwPkkWeAPI33Q.png" /></figure><p>From the color checkerboard, we can see the colors get transformed as per the reference colors.</p><h4>Using Polynomial Algorithms</h4><p>There are many techniques published on this. For e.g.<em> Color Correction Using Root-Polynomial Regression by Graham D. Finlayson, Michal Mackiewicz, and Anya Hurlbert (Refer </em><a href="https://ieeexplore.ieee.org/document/7047834/authors"><em>here</em></a><em>)</em></p><p>Using this technique, a color_correction matrix is derived as a coefficient from the input and output matrices. We can find its implementation in the <a href="https://pypi.org/project/colour-science/#colour-correction-colour-characterisation">color-science library</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5yGDzdYPsIktU7Q-rvlzg.png" /></figure><p>There are also other color correction implementation found in the library for the following two techniques,</p><ul><li>Using <a href="https://en.wikipedia.org/wiki/Vandermonde_matrix">Vandermonde_matrix</a></li><li>A comparative study of the characterisation of colour cameras by means of neural networks and polynomial transforms <em>by Vien Cheung, Stephen Westland, David Connah, and Caterina Ripamonti(Refer </em><a href="https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1478-4408.2004.tb00201.x"><em>here</em></a><em>)</em>.</li></ul><h4>Using the Thin-Plate Spline Technique</h4><p>Apart from this technique, there is another article that uses the thin-plate spline technique to calibrate the color.</p><p>RGB Color Calibration for Quantitative Image Analysis: The “3D Thin-Plate Spline” Warping Approach<em> by Paolo Menesatti ,Claudio Angelini ,Federico Pallottino ,Francesca Antonucci ,Jacopo Aguzzi ,and Corrado Costa (Refer </em><a href="https://www.mdpi.com/1424-8220/12/6/7063"><em>here</em></a><em>)</em></p><p>Thin plate Spline is an n-dimensional interpolation technique and it is the generalizations of single-dimensional cubic splines technique.</p><blockquote>Cubic splines give an interpolating polynomial that is smoother and has smaller error than some other interpolating polynomial. Similarly, Thin-Plate Spline techique extented this technique n dimentional space by bending image as thin sheet of metal with multiple control points</blockquote><p>This technique is used to estimate the deformation between two images. This warping approach is used in a number of applications including medical image analysis, optical flow computation in anti-spoofing, character recognition of scribble writing in OCR, face and finger matching.</p><p>The same technique is used to warp the input color matrix with the reference matrix and the unknown color region is transformed using the warping.</p><p>Here is the code that I have translated from the MATLAB code mentioned in the paper.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a0ecfd5411a19eda54e17d381e407be/href">https://medium.com/media/0a0ecfd5411a19eda54e17d381e407be/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TolLnLeGLDy5Y7en4rUIuQ.png" /></figure><p><em>On comparative study, Finlayson’s Root-Polynomial Regression technique worked for our case giving correct color calibration results in most cases.</em></p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="/service/mailto:contact@francium.tech"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f0895eafdb" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/using-machine-learning-for-color-calibration-with-a-color-checker-d9f0895eafdb">Using Machine Learning for Color Calibration  with a color-checker</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Model to AWS Lambda with Serverless]]></title>
            <link>https://blog.francium.tech/deploying-machine-learning-model-to-aws-lambda-with-serverless-a121a8253901?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/a121a8253901</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 03:47:59 GMT</pubDate>
            <atom:updated>2020-11-25T15:20:48.284Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying Machine Learning Model to AWS Lambda using Serverless</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K7wEuGZdjXAIdvmp-BRlQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/sasint-3639875/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1822412">Sasin Tipchai</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1822412">Pixabay</a></figcaption></figure><p>Deploying the machine learning model to AWS lambda is a well-known step. That is.,</p><ul><li>Dump the machine model object using <a href="https://pypi.org/project/joblib/">joblib</a>.</li><li>Upload the model dump to s3 bucket, and</li><li>Load the s3 dump in AWS lambda and use it for prediction.</li></ul><p>In this article, I am sharing one of our ML use cases and things considered in deploying it to AWS lambda.</p><h4>Use case</h4><p>The use case is simple,</p><ul><li>Our Ruby on Rails(ROR) project needs to access the prediction model.</li><li>It needs the prediction for a single set of data.</li><li>The related ML use case is well discussed in this previous article,</li></ul><p><a href="https://blog.francium.tech/building-prediction-model-from-conditionally-dependent-data-5bb0504864ea">Prediction from Conditionally Dependent Data in Machine Learning</a></p><ul><li>In the preprocessing step, we need to make a <strong>co-occurrence matrix </strong>of the events. Also, we need to do one-hot encoding for categorical variables and scale the continuous variable.</li></ul><p>Let’s see things considered for deploying this use case.</p><h3>Things Considered</h3><ul><li>As we need to run the prediction model in rails, we go with cloud service either <strong><em>sagemaker</em></strong> or <strong><em>lambda</em></strong> for running the prediction function.</li><li><strong><em>AWS Lambda</em></strong> is chosen instead of sagemaker as our model is a simple classical algorithm and prediction needs to be done for only single data at a time.</li><li><strong><em>Avoiding pandas</em></strong> at the prediction layer to reduce package size as we are going to preprocess only single data.</li><li>Use common projects to maintain the training and prediction layer. Also, share common code for preprocessing.</li></ul><h4>Use Serverless for deployment</h4><p>For AWS Lambda deployment, we considered using <strong>serverless</strong> and its plugins for addressing the following set of requirements. I don&#39;t see any other tool matured enough.</p><p>Use <strong>serverless-dotenv-plugin</strong> to share common .env variable in lambda like <em>s3 bucket name</em>.</p><p>Use <strong>serverless-python-requirements </strong>plugin,</p><ul><li>to use the same requirements.txt used in training and skip the unnecessary package for prediction.</li><li>Pack the package with native dependency using docker.</li><li>Reducing package size by removing the tests, information, and caches from the installed packages. For more details about this plugin, refer this blog</li></ul><p><a href="https://blog.francium.tech/deploying-python-packages-to-lambda-layers-using-serverless-plugin-c8fe1371e0b">Lambda Dependency Management using Serverless Plugin</a></p><h3>Project Setup</h3><h4>Training Layer</h4><p>Based on the notebook of the previous article, I have created a training script to train and dump the model to the S3 bucket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5987571f6bccd07559569f5d096fcfed/href">https://medium.com/media/5987571f6bccd07559569f5d096fcfed/href</a></iframe><p>Along with the trained model, required data and objects for preprocessing are also dumped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_0inFUVxpBGd5HTQJgdSA.png" /></figure><h4>Prediction Layer</h4><p>The input data for prediction is passed in following JSON format,</p><pre>{&#39;custype&#39;: &#39;Type 1&#39;,<br> &#39;cus_point&#39;: 2517,<br> &#39;purchase_events&#39;: {&#39;Product D&#39;: &#39;Brand 59&#39;, <br>                     &#39;Product N&#39;: &#39;Brand 2&#39; }}</pre><p>The lambda function gets the model dump from s3, preprocess it and predicts the value.</p><pre>def <strong>handler</strong>(<em>event</em>, <em>context</em>):<br>   dump=util.<strong>getModel</strong>()<br>   <br>    <em># Preprocess<br>   </em>data=<strong>pre_process</strong>(event,dump)<br>   <br><em>    # Predict the value and its probability<br>    </em>value,probability=<strong>predict</strong>(dump[&quot;model&quot;],data)</pre><pre><strong><em>return</em></strong> json.dumps({&quot;value&quot;: value, &quot;confidence&quot;: probability})</pre><p>Other data from a dump like <em>event matrix, data scaler &amp; categories for one encoding</em> are used to preprocess the input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ea0EQC8EwfHzc_2twJgHMA.png" /></figure><p>I have created a simple encoder method to do one hot encoding instead of usingpandas.dummies . Other than that we don’t have any use case to include pandas in the prediction layer</p><pre>def one_hot_encoder(categories,data):<br>    oh_array=np.zeros(len(categories),dtype=int)<br>    try:<br>        oh_array[categories.index(data)]=1<br>    except:<br>        pass<br>    return oh_array</pre><h4>Common Util for both layer</h4><p>Moved the common script of training and prediction to the util<em> </em>script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734b7d24c309145d9d73293656a4cff4/href">https://medium.com/media/734b7d24c309145d9d73293656a4cff4/href</a></iframe><h3>Serverless Configuration</h3><h4>Plugin Configuration</h4><p>Below is the configuration for the dot_env and python requirement plugin.</p><ul><li>Using dotenv plugin to include environment variables to lambda</li><li>dockerizePip: true install the packed in lambi docker.</li><li>slim:true remove unnecessary files and cache in the installed package.</li><li>noDeploy skip the listed packages from requirement.txt for lambda</li><li>layer upload the dependency package to the lambda layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GefJ0B5vAfYILDHoSiw5ng.png" /></figure><h4>Function Configuration</h4><p>The functions are configured to upload only lambda related function and skip other files related to training.</p><pre><strong>functions</strong>:<br>  predict-brand:<br>    handler: src/model/predict.handler<br>    layers:<br>      - {Ref: PythonRequirementsLambdaLayer}<br>    package:<br>      include: <br>        - src/model/predict_vendor.py<br>        - src/model/util.py</pre><pre>#Exclude the files in functions<br><strong>package</strong>:<br>  individually: true<br>  exclude:<br>    - ./**</pre><h4>S3 bucket Role Permission</h4><p>Configure role permission for lambda to read s3 bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOZ9NOA6dQN-NYsIRbu8vA.png" /></figure><h3>Deploying model and lambda function</h3><p>The complete code is here,</p><p><a href="https://github.com/navarasu/brand_prediction">navarasu/brand_prediction</a></p><h4>Train and Upload model to s3</h4><pre>cd brand_prediction<br>virtualenv venv<br>source venv/bin/activate<br>pip install -r requirements.txt</pre><pre><strong># Train and upload model to s3 bucket</strong><br>python src/model/train.py</pre><h4>Deploying Lambda function</h4><pre>npm install -g serverless</pre><pre>npm i -D serverless-dotenv-plugin</pre><pre>sls plugin install -n serverless-python-requirements</pre><pre><strong># Deploy function to aws lambda</strong></pre><pre>sls deploy</pre><h4>Invoke lambda function</h4><pre>sls invoke -f predict-brand --data &#39;{&quot;cus_type&quot;: &quot;Type 1&quot;,\ &quot;cus_point&quot;: 2517,&quot;purchase_events&quot;: {&quot;Product D&quot;: &quot;Brand 59&quot;,&quot;Product N&quot;: &quot;Brand 2&quot;}}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nF9qS5OVo4pb8uBrueuoAg.png" /></figure><blockquote>Repeating the preprocessing steps in the prediction can be avoided using scikit pipeline. Also instead of dumping all related preprocessing data, it is enough dump the pipeline object alone.</blockquote><p><em>In the next article, we can see how to use scikit pipeline to simplify the prediction lambda script and also discuss other pipeline use cases.</em></p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="/service/mailto:contact@francium.tech"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a121a8253901" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/deploying-machine-learning-model-to-aws-lambda-with-serverless-a121a8253901">Deploying Machine Learning Model to AWS Lambda with Serverless</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Knative Service directly from source code using Kaniko / Ko]]></title>
            <link>https://blog.francium.tech/deploy-knative-service-directly-from-source-code-using-kaniko-ko-62f628a010d2?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f628a010d2</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[knative]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 08:07:06 GMT</pubDate>
            <atom:updated>2019-10-14T12:12:13.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33ac7ahdelqJXkridHTK_w.png" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a follow up of the previous knative article where we got a brief intro into knative and learned how to deploy knative service. Before moving into this blog, look at the previous article for knative setup and to understand the context of this blog.</p><p><a href="https://blog.francium.tech/build-your-own-serverless-platform-on-kubernetes-with-knative-87c82eb1b14d">Build Your Own Serverless Platform on Kubernetes with Knative</a></p><p>In the hello world knative service deployment, we used local docker and docker registry for handling the image of our serverless service. It is the Kubernetes way of deployment. But when compared with a serverless way of deployment, these steps look inessential. i.e. managing a docker file, an image registry, docker daemon to build image and using a base image, etc.</p><h4>Deploy from Source code</h4><p>These concerns can be addressed by deploying the source code directly from source code. This can be done in two ways.</p><ul><li><strong>Using Kaniko:</strong> We can build an image inside the Kubernetes cluster using the source code with docker file. So, we don’t need a local docker daemon to the build image.</li><li><strong>Using Ko:</strong> This is limited to go language. Ko uses the go import concept to fetch the binary our go app and pack it with <a href="https://github.com/GoogleContainerTools/distroless">distroless</a> image. So, we don’t need a docker file.</li></ul><p>Both approaches need a docker registry to push and pull the image.</p><h3>Using Kaniko</h3><h4>Install and Configure Kaniko</h4><p>Install kaniko in the Kubernetes</p><pre>kubectl apply --filename <a href="https://raw.githubusercontent.com/knative/build-templates/master/kaniko/kaniko.yaml">https://raw.githubusercontent.com/knative/build-templates/master/kaniko/kaniko.yaml</a></pre><h4>Configure DockerHub Secrets for Kaniko</h4><p>Encode your docker hub username and password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*1sN3SkE1jwBaDl63W_100Q.png" /></figure><p>Add this encoded string to the secrets with data key as username and password</p><pre>echo &#39;apiVersion<strong>:</strong> v1<br>   kind<strong>:</strong> Secret<br>   metadata<strong>:</strong><br>     name<strong>:</strong> basic-user-pass<br>     annotations<strong>:</strong><br>       build.knative.dev/docker-<strong>0:</strong> https<strong>:</strong>//index.docker.io/v1/<br>   type<strong>:</strong> kubernetes.io/basic-auth<br>   data<strong>:</strong><br>     username<strong>:</strong> <strong>dXNlcm5hbWU=</strong><br>     password<strong>:</strong> <strong>cGFzc3dvcmQ=</strong>&#39; &gt; docker-secret.yaml</pre><pre><strong># Create a secret</strong></pre><pre>kubectl apply --filename docker-secret.yaml secret &quot;basic-user-pass&quot; created</pre><p>It also needs a service account to access this secret</p><pre>echo &#39;   apiVersion<strong>:</strong> v1<br>   kind<strong>:</strong> ServiceAccount<br>   metadata<strong>:</strong><br>     name<strong>:</strong> build-bot<br>   secrets<strong>:</strong><br>     - name<strong>:</strong> basic-user-pass&#39; &gt;  service-account.yaml</pre><pre><strong># Create a service account</strong></pre><pre>kubectl apply --filename service-account.yaml serviceaccount &quot;build-bot&quot; created</pre><h3>Build using Kaniko</h3><p>Let’s use the same go web app example.</p><pre>mkdir go_example</pre><pre>cd go_example</pre><pre>echo &#39;package main<br>import &quot;github.com/gin-gonic/gin&quot;<br>func ping(c *gin.Context) {<br>     c.JSON(200, gin.H{ &quot;message&quot;: &quot;pong&quot;,})<br>}<br>func main() {<br>        r := gin.Default()<br>        r.GET(&quot;/&quot;, ping)<br>        r.Run() // listen and serve on 0.0.0.0:8080<br>}&#39; &gt; helloworld.go</pre><p>Init Go Modules for dependency management. Refer to <a href="https://blog.francium.tech/go-modules-go-project-set-up-without-gopath-1ae601a4e868">this blog</a> for more detail.</p><pre>go mod init go_example</pre><p>Create a Dockerfile for the app</p><pre>echo &#39;FROM golang:alpine AS build-executableRUN mkdir /app<br>ADD . /app<br>WORKDIR /appRUN apk --no-cache add git<br>RUN go build<strong><em># Using a Docker multi-stage build to create a lean image.</em></strong>FROM alpine<br>RUN mkdir /app<br>RUN apk --no-cache --update add ca-certificates<br>COPY --from=build-executable /app/go_example /app/go_example</pre><pre>CMD [&quot;./app/go_example&quot;]&#39; &gt; Dockerfile</pre><h4>Push the code</h4><pre>git init <br>git add * <br>git commit -m &quot;Created knative go example for kaniko&quot; <br>git remote add origin https://github.com/navarasu/goknative.git<br>git push -u origin master</pre><h4>Deploy directly from source code</h4><p>Let&#39;s create service.yaml for deploying Knative service from source code.</p><pre>echo &#39;apiVersion<strong>:</strong> serving.knative.dev/v1alpha1<br>   kind<strong>:</strong> Service<br>   metadata<strong>:</strong><br>     name<strong>:</strong> app-from-source<br>     namespace<strong>:</strong> default<br>   spec<strong>:</strong><br>     runLatest<strong>:</strong><br>       configuration<strong>:</strong><br>         build<strong>:</strong><br>           apiVersion<strong>:</strong> build.knative.dev/v1alpha1<br>           kind<strong>:</strong> Build<br>           spec<strong>:</strong><br>             serviceAccountName<strong>:</strong> build-bot<br>             source<strong>:</strong><br>               git<strong>:</strong><br>                 url<strong>:</strong> <strong>https://github.com/navarasu/goknative</strong><strong>.git</strong><br>                 revision<strong>:</strong> master<br>             template<strong>:</strong><br>               name<strong>:</strong> kaniko<br>               arguments<strong>:</strong><br>                 - name<strong>:</strong> IMAGE<br>                   value<strong>:</strong> <strong>docker.io/navarasu/app-from-source:latest</strong><br>             timeout<strong>:</strong> 10m<br>         revisionTemplate<strong>:</strong><br>           spec<strong>:</strong><br>             container<strong>:</strong><br>               image<strong>:</strong> <strong>docker.io/navarasu/app-from-source:latest</strong><br>               imagePullPolicy<strong>:</strong> Always&#39; &gt; service.yaml</pre><p>Deploy the knative service.</p><pre>kubectl apply --filename service.yaml</pre><p>Here, the <strong>build</strong> step creates an image using the docker file in source code and pushes it to the docker registry. Then as in the usual step, the pushed image is used to create knative service.</p><h4>Access the app</h4><pre>curl -H &quot;Host: app-from-source.default.example.com&quot; <a href="http://35.203.155.229/">http://35.203.155.229</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-n55HnNifutLcWpcTngvxA.png" /></figure><p>Here,</p><ul><li>we can find Host value for the function using the alias ksvc of knative service.</li></ul><pre>kubectl get ksvc app-from-source</pre><ul><li>we can retrieve the IP Address of istio-ingressgateway</li></ul><pre><em>kubectl get svc istio-ingressgateway --namespace istio-system</em></pre><h3>Using Ko</h3><h4>Install ko</h4><pre>GO111MODULE=on go get github.com/google/ko/cmd/ko</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*M9gL2YQJHMUlj9T_bY0Msg.png" /></figure><h4>Configure docker registry path</h4><pre>export KO_DOCKER_REPO=docker.io/navarasu/app-from-source</pre><h3>Build using Ko</h3><p>Let’s use the same go example. But this time without any docker file.</p><pre>mkdir go_example</pre><pre>cd go_example</pre><pre>echo &#39;package main<br>import &quot;github.com/gin-gonic/gin&quot;<br>func ping(c *gin.Context) {<br>     c.JSON(200, gin.H{ &quot;message&quot;: &quot;pong&quot;,})<br>}<br>func main() {<br>        r := gin.Default()<br>        r.GET(&quot;/&quot;, ping)<br>        r.Run() // listen and serve on 0.0.0.0:8080<br>}&#39; &gt; helloworld.go</pre><pre><strong># Init go module</strong></pre><pre>go mod init go_example</pre><h4>Push the code</h4><pre>git init <br>git add * <br>git commit -m &quot;Created knative go example for ko&quot; <br>git remote add origin https://github.com/navarasu/knativeko.git<br>git push -u origin master</pre><h4>Deploy from source code</h4><p>Let&#39;s create service.yaml for deploying Knative service using go import path of the git repository instead of a docker image.</p><blockquote><strong>For e.g.,</strong></blockquote><blockquote>Go import for our git repo will be import(‘github.com/navarasu/knativeko’)</blockquote><pre>echo &#39;apiVersion<strong>:</strong> serving.knative.dev/v1alpha1 <br>kind<strong>:</strong> Service<br>metadata<strong>:</strong><br>  name<strong>:</strong> ko-example<br>  namespace<strong>:</strong> default <br>spec<strong>:</strong><br>  runLatest<strong>:</strong><br>    configuration<strong>:</strong><br>      revisionTemplate<strong>:</strong><br>        spec<strong>:</strong><br>          container<strong>:</strong><br>            image<strong>:</strong> github.com/navarasu/knativeko&#39; &gt; service.yaml</pre><p>Now, deploy using ko</p><pre>ko apply -f service.yaml</pre><p><a href="https://francium.tech/?source=post_page---------------------------"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="http://contact@francium.tech/?source=post_page---------------------------"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f628a010d2" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/deploy-knative-service-directly-from-source-code-using-kaniko-ko-62f628a010d2">Deploy Knative Service directly from source code using Kaniko / Ko</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started with Machine Learning - Part 1]]></title>
            <link>https://blog.francium.tech/get-started-with-machine-learning-part-1-e24e980fa8a8?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24e980fa8a8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Sat, 05 Oct 2019 20:41:07 GMT</pubDate>
            <atom:updated>2019-11-10T12:51:42.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWpuMFQc9rIZHd1skpDbxw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@agkdesign?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alex Knight</a> on <a href="https://unsplash.com/s/photos/robot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Below one is a conversation with my friend last week. He asked about how to get started with Data Science. When I shared him the </em><a href="https://www.youtube.com/playlist?list=PLblh5JKOoLUICTaGLRoHQDuF_7q2GfuJF"><strong><em>StatQuest</em></strong><em> Machine learning video link</em></a><em>, he asked me the difference between ML and Data Science?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlccOaYs83S5OZSecDVnRQ.png" /></figure><p><em>Every beginner will come across these buzzwords </em><strong><em>Machine Learning</em></strong><em>, </em><strong><em>Artificial Intelligence, </em></strong><em>and </em><strong><em>Data Science</em></strong><em>.</em></p><p>Artificial Intelligence and Data Science are two dominant fields in today’s world redefining business to the next generation.</p><p>Let’s get a brief overview of that before moving into Machine Learning</p><h3>Artificial Intelligence and Data Science</h3><p><strong><em>Artificial Intelligence</em></strong> is wide term to discuss here. It aims to make the computer perform autonomous action by modeling human and animal capabilities.</p><p>In reality, it has a long way to go. The current AI is <em>‘Narrow AI’ </em>which do not have full autonomy like a human but they are trained to perform certain task.<em> For. e.g., a Self-driving car is trained to drive a car autonomously but it does not know it is driving a car.</em></p><p><strong><em>Data Science</em></strong> is an interdisciplinary field and it aims in processing any format of data and extracting useful information out of it.</p><p>Both AI and Data Science share techniques, tools and concepts among them to full fill their specific goal. We can’t isolate these techniques specific to certain fields.</p><h4>Tools and Techniques</h4><p>There are numerous techniques, tools, and concepts used by AI &amp; Data Science to fulfill their specific goals. Few of them are,</p><ul><li>Machine Learning</li><li>Image Processing</li><li>Cloud Computing</li><li>Big Data Techniques</li><li>Data Visualisation</li><li>and more …</li></ul><p>Among those techniques, Machine Learning is the most common concept used by both Data Science and AI. Let&#39;s move into the Machine learning concept.</p><h3>Machine Learning</h3><p>Machine Learning is a technique that analyzes the provided data using predefined algorithms and can make a prediction on new unanalyzed data.</p><blockquote>From the definition of <a href="https://en.wikipedia.org/wiki/Arthur_Samuel">Arthur Samuel</a>, a pioneer in the field of artificial intelligence who coined the word ‘Machine Learning’</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmRDjDRo8CM8RDojqdNmsw.png" /></figure><h4>How it differs from Traditional Programming?</h4><p>In usual programming, we program the logic manually to get the desired output.</p><blockquote><strong><em>Traditional Programing: </em></strong><em>I</em>nput + hardcoded logic/rules = output</blockquote><p>While in Machine Learning, we use algorithms to study logic/pattern behind the given input and output data. So that they don’t have to be programmed to get the desired output.</p><blockquote><strong>Machine Learning : </strong>Input + output = derived logic / rules using algorithm</blockquote><p>The core idea is to make a machine learn problem-solving itself with the help of machine learning algorithms.</p><h4>Machine Learning Algorithms</h4><p>As of now, we have understood that machine learning solves a problem using predefined algorithms. Let us see what they are. Machine Learning can be categorized into two, Classical Learning and Deep Learning.</p><ul><li><strong><em>Classical Learning</em></strong><em> are statistics-based methods and they are mostly interpretable. Some popular algorithms are Linear Regression, Logistic Regression, Decision Tree, Naive bayes, K nearest neighbour, K means, etc.,</em></li></ul><blockquote>Apart from these algorithms,we have other two concepts like <strong>Ensemble</strong> and <strong>Reinforcement </strong>which helps to enhance classical algorithms.</blockquote><ul><li><strong><em>Deep Learning</em></strong><em> are modern methods performed using neural network and it can replace all above classical methods. Some popular architectures are Convolutional Neural Network (CNN), Recurrent Neural Networks (RNN), </em>Feedforward Neural Network, <em>etc.,</em></li></ul><blockquote>Even Though Deep Learning has proved high performance in tasks like speech and image recognition, Classical algorithms still play better role than big neural network in many cases.</blockquote><h3>Get started with Machine Learning</h3><p>To get started with Machine Learning, it is good to start with the classical algorithm. Classical algorithms are mostly categorized into supervised and unsupervised learning.</p><h4>Supervised learning Vs Unsupervised Learning</h4><p>In <strong>Supervised Learning</strong>, we will have input, <strong>X</strong> and corresponding output, <strong>Y</strong>. We will be finding the relationship between <strong>X</strong> and <strong>Y</strong>.</p><p><strong><em>For e.g.</em></strong><em>, Let say we have height and weight of 500 people. Identifying the weight of a person from a height is supervised learning. We can find the weight from the height by finding the relationship between height </em><strong><em>X</em></strong><em> and weight </em><strong><em>Y </em></strong><em>.</em></p><blockquote><strong>Classification</strong> and <strong>Regression</strong> concepts come under <em>supervised learning</em>.</blockquote><p>In <strong>unsupervised learning</strong>, we will have only an input variable <strong>X</strong> and we won’t have corresponding output variable <strong>Y </strong>. We will be predicting based on the common details present in the input variables.</p><p><strong><em>For e.g.,</em></strong><em> Let&#39;s say we have runs and wickets of 500 cricket players and we don’t have information whether the player is a batsman or bowler. Identifying bowler and batsman among them is unsupervised learning.</em></p><blockquote><strong>Association</strong> and <strong>Clustering</strong> concepts come under un<em>supervised learning</em></blockquote><p>In classical algorithms, Linear Regression is a simple concept and a good first algorithm to start with.</p><p>Let&#39;s understand it with an example dataset and problem.</p><h4>DataSet</h4><p>I have taken the well known <a href="https://www.kaggle.com/mustafaali96/weight-height">gender -height -weight kaggle dataset</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXQYkkbwHwot9TjJFaS-EA.png" /></figure><h4><strong>Problems</strong></h4><ol><li>Find the <strong>weight</strong> based on height is well known <strong>regression</strong> problem</li><li>Find the <strong>gender-based</strong> on weight and height is a <strong>classification</strong> problem</li></ol><h3>Linear Regression</h3><p>Both in regression and classification problem, we find the relationship between input <strong>X</strong> and output <strong>Y </strong>. In Linear Regression, we use to predict a quantitative output value <strong>Y</strong> from the input <strong>X </strong>by finding the linear relationship between them</p><blockquote><strong>Terms: Features and Labels</strong></blockquote><blockquote>In Machine Learning, the input variable <strong>X </strong>is referred as <strong>features </strong>and output variable <strong>Y </strong>is referred as <strong>labels</strong></blockquote><p>For e.g., If we plot a graph between X and Y values,</p><ul><li>Linear Regression finds the best line to fit the plotted data points</li><li>Using this best fit line, we can find the value of the corresponding Y value from the X geometrically.</li></ul><h4><strong>Finding the best fit line</strong></h4><ul><li>Trying with different linear lines and predicting the new Y value from the X value using the drawn line.</li><li>Then we find the difference between the predicted Y value with actual Y value. This is called the <strong>error </strong>in the prediction.</li><li>The aim is to find the line which has the least error for all data points</li><li>There are different techniques to find this least error like <a href="https://en.wikipedia.org/wiki/Ordinary_least_squares"><strong><em>Ordinary Least Squares</em></strong></a><strong><em>, </em></strong><a href="https://en.wikipedia.org/wiki/Gradient_descent"><strong><em>Gradient Descent</em></strong></a><strong><em>, </em></strong><a href="https://en.wikipedia.org/wiki/Lasso_(statistics)"><strong><em>Lasso Regression</em></strong></a><strong><em>, </em></strong><em>and</em><strong><em> </em></strong><a href="https://en.wikipedia.org/wiki/Tikhonov_regularization"><strong><em>Ridge Regression</em></strong></a><strong><em>.</em></strong></li></ul><h4><strong>Mathematically</strong></h4><ul><li>The equation of this line is represented as y = (<strong><em>m</em></strong><em> * x) </em>+ <strong><em>b </em></strong><em>where </em><strong><em>m</em></strong><em> and </em><strong><em>b</em></strong><em> are coefficients.</em></li></ul><blockquote>Here, <strong>b</strong> is the <strong>intercept</strong> (point where line meets the y axis) and <strong>m</strong> is the <strong>slope</strong>.</blockquote><ul><li>We change these two coefficients to draw different lines to find the best fitting line among them.</li><li>In other words, the Linear regression model finds the best value of the two coefficient <strong>m</strong> and <strong>b, </strong>which results in a best-fit line for the given training data.</li></ul><blockquote><strong>Terms: Model and Training</strong></blockquote><blockquote>In Machine Learning,the process of finding the best fit relationship function is referred as <strong>Training </strong>and relationship function derived is referred as <strong>Model</strong> . The data is used for train is referred as <strong>Training Data</strong></blockquote><h3>Predicting Weight from Height using Linear Regression</h3><p>Refer the article for environmental setup and tools to get started with machine learning,</p><p><a href="https://blog.francium.tech/get-started-with-machine-learning-handy-python-tools-a1ce97085837">https://blog.francium.tech/get-started-with-machine-learning-handy-python-tools-a1ce97085837</a></p><h4>Prepare Data</h4><p>Prepare input <strong>X</strong> and output <strong>y</strong> from data,</p><pre>import pandas as pd<br>data = pd.read_csv(&quot;weight-height.csv&quot;)</pre><pre>X = data.drop([&quot;Height&quot;,&quot;Gender&quot;],axis=1)<br>y = data[&quot;Height&quot;]</pre><p>Separate the <strong>test</strong> data and <strong>train</strong> data,</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.61,random_state=7)</pre><p>Find the best model for the training data using scikit Linear Regression method(sklearn.linear_model.LinearRegression) . This method uses Ordinary Least Square to find the best fit line.</p><pre>from sklearn.linear_model import LinearRegression<br>lr = LinearRegression()<br>lr.fit(X_train, y_train)</pre><h4>Visualize the best fit model</h4><p>lr object holds the best fit model. As we discussed earlier, it holds the value of the coefficients of the best fit line, <strong>m</strong> slope , and <strong>b </strong>intercept</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NJnoJv-9Bo-RKwj9iss8g.png" /></figure><p>Here <strong>Y </strong>is weight and <strong>x</strong> is the height. By substituting the weight in <strong>x</strong> value in the above linear equation, we get the predicted height.</p><p>The plot of the data points and best-fit line of the training data is as below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLuclZSMHRHb462ErcpBmA.png" /></figure><h3>Evaluating a Regression algorithm</h3><p>The most important part of Machine Learning is evaluating the performance of the trained model,<strong> i.e,</strong> about evaluating the accuracy of the prediction.</p><p>As we are predicting a numerical value in the regression problem. We cannot verify by equalizing predicted value with actual. The predicted value will have minimal differences with actual value. This we call as an error.</p><p>This error value of all test data is evaluated with these three most common metrics, <strong>Mean Absolute Error,</strong> <strong>Mean Squared Error</strong> and <strong>Root Mean Squared Error</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VBmFTgEHTvp9x6eXkndmA.png" /></figure><p>Lower error value in all metrics shows better performance of the model.</p><p><em>In the </em><strong><em>next blog</em></strong><em>, we try the classification problem of the above data set, </em><strong>i.e</strong>., predicting the gender from height and weight. <em>Also, list metrics to evaluate the classification model.</em></p><p><a href="https://francium.tech/?source=post_page---------------------------"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="http://contact@francium.tech/?source=post_page---------------------------"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24e980fa8a8" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/get-started-with-machine-learning-part-1-e24e980fa8a8">Get Started with Machine Learning - Part 1</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prediction from Conditionally Dependent Data in Machine Learning]]></title>
            <link>https://blog.francium.tech/building-prediction-model-from-conditionally-dependent-data-5bb0504864ea?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bb0504864ea</guid>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 04:48:44 GMT</pubDate>
            <atom:updated>2019-08-13T16:06:08.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWS1cEY1Lkz0pXErZIbWSA.png" /></figure><p>Recently we have delivered prediction system for our client which has different data set with almost 95% categorical and 5% nominal features. The data set looks like a recommendation problem but we need to do a prediction out of it.</p><p>The problem some what looks like this, we need to predict which brand a customer would bought based on his purchase history and overall purchase trend. <em>For e.g., if a customer bought </em><strong><em>R</em>efrigerator</strong><em> and </em><strong><em>AC</em></strong><em> from some brand, then we need to predict from which </em><strong><em>brand</em></strong><em> he would have bought </em><strong><em>television.</em></strong></p><p>The problem is to predict only for one target product. for e.g., in above example, we need to predict the brand of the television.</p><h3><strong>DataSet</strong></h3><p>In actual data, we have few more features like <strong>customer type</strong> and <strong>customer point </strong>as well. I have prepared a dummy data set denoting the above problem. It is as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CfYO0SJgYTAvYGPfikOlg.png" /></figure><p>Here <strong>product</strong> is denotes the type of product Television, AC.etc while <strong>brand</strong> denotes the brand of the product. Let’s assume that <strong>cus_points</strong> is some numerical value denoting customer purchase capacity.</p><p><strong>To Predict: </strong>Brand of the <strong>Product A</strong></p><h3>Data Analysis</h3><p>On a outward look, the problem looks like a recommendation problem. From the customer angle , we can visualize an <strong><em>also bought</em></strong><em> </em><strong><em>trend. i.e., </em></strong><em>Also bought from same brand trend.</em></p><h4><strong>Also bought Trend</strong></h4><p>We can analyse also bought trend of product D using item to item collaborative filtering. We can create co-occurrence matrix by encoding buying events to binary with <strong>1</strong> for product having <strong>same</strong> <strong>brand</strong> as <strong>Product A </strong>and <strong>0</strong> for the else case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgikqCdHNO0CdwBcusGJSg.png" /><figcaption>Co-occurrence Matrix</figcaption></figure><p>As it is binary, jaccard_similarity_score will help us find the correlation among the products.</p><pre><em>from</em> sklearn.metrics <em>import</em> jaccard_similarity_score</pre><pre>cor = also_bought.corr(<em>method</em>=lambda <em>x</em>, <em>y</em>: jaccard_similarity_score(x, y))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMns4mEKaK0EeBEvTceM-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqKTpt-jL5fZkwiiFqwPRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEvtHLLoUYbq9-E6nz-L3w.png" /><figcaption>Products also bought with<strong> Product A</strong></figcaption></figure><blockquote>Product N ,D and BD are having high correlation with Product A. They are bought from same brand on most of the cases than Product AP,AL and I.</blockquote><p><strong>For e.g.</strong>,Whenever a customer has bought AC and Refrigerator from a brand, he also bought television from same brand. But not when he bought headset or book as they are not correlated or not sold in the brand.</p><h4><strong>Conditional Dependence</strong></h4><p>If we closely look at the above correlation result, we can notice a conditional dependence between the each buying event.</p><blockquote>From <a href="https://en.wikipedia.org/wiki/Conditional_dependence">wiki</a>, <strong>conditional dependence</strong> is a relationship between two or more events that are dependent when a third event occurs. <strong>For e.g.</strong>, if <em>A</em> and <em>B</em> are two events that individually increase the probability of a third event <em>C</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8o04S4gEGcHg2hTOQa52iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zu0Z4_FvLFnpLu4Ohd_PNQ.png" /></figure><h4><strong>Analysing Customer Type</strong></h4><p>If we plot the Customer type vs Brands of Product A, we can notice few brand were sold only to specific customer type. Based on this product example, it may look invalid. But for my actual data this type has influence factor for selecting the brand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*TIaPXh6gCvSuEPbR9bRkGg.png" /></figure><h4>Analysing Customer Points</h4><p>Let’s take mean of the customer points for each Brand of Product A to analyse its influence in selecting the brand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnifywRSyX-PTzN-BdWeNw.png" /></figure><p>Brand 10, 18 and 19 are purchased by customer having more purchase points. It may be due to high cost of the product.</p><h4>Analysing Prediction Label (Imbalanced Data Set)</h4><p>Below is the plot of brands count of Product A and we can see the labels are imbalanced.Brand 3 and Brand 8 have large data set than others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgMC-8KFMkln3lXXF1RJhQ.png" /></figure><p>Mostly these kind of data set will balanced either by increasing the smaller samples or decreasing higher samples. But in our case the main influencing data is the conditional dependency. Changing the data will impact this purchase trend and can reduce the accuracy. Again the more purchase of a particular brand is also an information to be considered for prediction. So I don’t to do any re-sampling with this data.</p><h3>Choosing a Prediction Model</h3><p>In above data analysis, we can understand that event of ‘buying related product from same brand’ has more influence in predicting the label. So, the brand of Product A can be predicted by measuring the <strong>conditional probability distribution </strong>of all the buying events of the products.</p><blockquote><strong>Conditional probability</strong> is a measure of the <a href="https://en.wikipedia.org/wiki/Probability">probability</a> of an <a href="https://en.wikipedia.org/wiki/Event_(probability_theory)">event</a> occurring given that another event has occurred.</blockquote><p>In Supervised Machine Learning, <strong>conditional probability-based prediction </strong>can be done by <strong>discriminative classifiers </strong>like Logistic Regression, SVM etc.</p><p>Even the <strong>Generative Classifiers</strong> like Naive Bayes can be used to predict the label. But generative classifiers like Naive Bayes well performs only with smaller dataset. When data grows, discriminative classifiers<strong> </strong>performs better as generative model reaches the asymptotic solution for fewer training sets than the discriminative model. This is well explained in the <a href="http://ai.stanford.edu/~ang/papers/nips01-discriminativegenerative.pdf"><strong>experimental paper by Andrew Ng and Michael Jordan.</strong></a></p><blockquote>Discriminative model ‌measures the <strong>conditional probability distribution </strong><strong>p(y|x), </strong>which can be used for predicting <strong>y </strong>(label to be predicted)<strong> </strong>from <strong>x </strong>(input data).</blockquote><blockquote>Generative model ‌measures the <strong>joint probability distribution </strong><strong>p(x,y) </strong>and make the prediction <strong><em>p(y|x)</em></strong> using <strong>Bayes Theorem.</strong></blockquote><p>Let’s start with most popular Discriminative classifier, Logistic Regression.Also we cross verify with Generative classifier like Naive Bayes and other Discriminative classifiers.</p><h3>Preprocessing the data</h3><p>Let’s group the data with cust_id and transpose the product to columns,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gphpaB9M8X7ZoxY46vjdYw.png" /></figure><h4><strong>Cleaning Dirty Data</strong></h4><p>Dropping all none values from prediction label (Product A)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ejAlrImSdp8W6bBI0qwmw.png" /></figure><p>As Product data is most influencing features, we can drop rows which doesn’t have purchase history other than Product A. So, dropping rows with all Products columns having none value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDfTaMtqJfLdAk8luV-FwQ.png" /></figure><h4><strong>Split Training and Test Data</strong></h4><p>Extract the training label <strong>y</strong> and input data <strong>x</strong> from the grouped data and split the dataset for training and testing in 60:40 ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qq2k2bCN1CCjV3TQVjuGOA.png" /></figure><h4><strong>Encoded Buying Events of Product</strong></h4><p>The occurrence of an event not occurrence is encoded into binary. Let&#39;s generate the possible event combination for product and brand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixdXbg7VHg5xT-nynSSl9w.png" /></figure><p>Totally we have got 351 events. Using these combinations as columns, we can encode the buying event of each customer to form <strong>co-occurrence matrix</strong> for the events</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqgytR31ik1WuiQ429BErA.png" /></figure><h4>Encoded Categorical Data and Scaled Continuous Data</h4><p>Encoded Customer Type value using One Hot Encoding and scaled the customer points using min-max scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hB1T_Hilx3JKlcLjY5hMpQ.png" /></figure><h3>Building the Prediction Model</h3><p>Trained the model using <strong>Logistic Regression</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWX1Xr6xW868cseJLX7YqA.png" /></figure><p>Pre-process the test data and evaluate the accuracy of the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esutR0L_F1FPq61J_ki7Pg.png" /></figure><p>We get <strong>82.8%</strong> accuracy with logistic regression</p><h4>Compare With Naive Bayes</h4><p>When we try the same data with Naive Bayes and we get <strong>78%</strong> accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzuYBOk9GYHa3I8RFfQISg.png" /></figure><blockquote><em>For</em><strong><em> k fold cross validation, </em></strong><em>Logistic Regression and Naive Bayes gets </em><strong><em>81.55%</em></strong><em> and </em><strong><em>76.56%</em></strong><em> accuracy score . It shows the logistic regression perform well then Naive Bayes.</em></blockquote><h4>Compare With Other Discriminative Classifiers</h4><p>First we can try with one typical discriminative classifier, Support Vector Machine (SVM).</p><p><strong><em>With Support Vector Machine (Linear Kernel)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jI6iUdj7PcFFxfZh1-qfA.png" /></figure><p><strong><em>With Support Vector Machine (Gaussian Kernel)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3stTzBI5zotqBm-uZ2STOQ.png" /></figure><p>SVM is almost performs same as Logistic Regression as the almost having same algorithm. Surprisingly, SVM using gaussian kernel slightly out performs than Logistic and SVM with linear kernel.</p><p><strong><em>With K Nearest Neighbour (is it Discriminative Classifier?)</em></strong></p><p>It is some times debated that KNN is discriminative or generative . You can see a debate <a href="https://stats.stackexchange.com/questions/105979/is-knn-a-discriminative-learning-algorithm">here</a>. Even though it comes under kind of discriminative category, it performed lower and almost same as Naive Bayes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A408yWTAdNfVcPvgebRelQ.png" /></figure><h3>Evaluating the Model</h3><p>In the above analysis, we notice most of them performing good based on classification accuracy. It is not enough parameter to validate which model is performing well.</p><h4>K Fold cross-validation</h4><p>First, we can evaluate the accuracy with K Fold cross-validation for the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNpkFhwCE7vkq6JxxIFNcw.png" /></figure><p>Here dots denote accuracy of each fold of training set. As our data is imbalanced, you can see the accuracy performs well for few data set and lower for some.</p><p>SVM (Gaussian) and Linear Regression performs well than others like our existing accuracy result.</p><p>Here the dots of SVM (Gaussian) are clustered between best and worst data set. It shows that SVM (Gaussian) is <strong><em>marginally performing</em></strong> better than LR. It may due to their loss function as Logistic loss diverges faster than hinge loss.</p><blockquote>SVM minimizes hinge loss while logistic regression minimizes logistic loss.</blockquote><h4>ROC Curve and Precision Recall Curve</h4><p>The above accuracy is the ratio of number of correct predictions to the total number of input samples. It is doesn’t check <strong>errors</strong> of the prediction model like false positives and false negatives.</p><blockquote>There are 4 parameter for the interpretation,</blockquote><ul><li><strong>True Positive: </strong>Predict an event when there was an event.</li><li><strong>True Negative:</strong> Predict no event when in fact there was no event.</li><li><strong>False Positive: </strong>Predict an event when there was no event.</li><li><strong>False Negative:</strong> Predict no event when in fact there was an event.</li></ul><p>Receiver Operating Characteristic(<strong>ROC</strong>) Curves and <strong>Precision-Recall curves</strong> are supports to interpret the prediction of probabilities.</p><p>ROC curve plots between True Positive Rate (<strong>Sensitivity) </strong>and False Positive Rate (<strong>1 — Specificity) </strong>while Precision-Recall curve plots between <strong>Precision</strong> and <strong>Recall</strong>.</p><blockquote><em>Here,</em></blockquote><ul><li><em>Recall\True Positive Rate= True Positives / (True Positives + False Negatives)</em></li><li><em>Precision = True Positives / (True Positives + False Positives)</em></li><li><em>False Positive Rate = False Positives / (False Positives + True Negatives)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wJ6bJCSqNYi3D88SDCXvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQ7NgF9dbYAbvJXh5_rbvA.png" /></figure><p>In the above graph, the area under each curve (AUC) is used to summarize the skill of the model.</p><p>As our data are imbalanced, the precision recall curve plays a major role in defining the skill of the model. If we look at curves of both graph, Logistic Regression and SVM (Gaussian) have larger AUC (area under the curve) than others.</p><p>As the number of features (353) is relatively small than the number of training examples (4548), SVM (Gaussian) marginally well perform than Logistic Regression as discussed <a href="https://stats.stackexchange.com/questions/95340/comparing-svm-and-logistic-regression">here</a>.</p><blockquote>But if data grows, the SVM will perform lower than logistic regression.</blockquote><p>As the difference is almost minor between the two, we go with Logistic regression as it comparatively simpler and faster model.</p><h4>Confusion Matrix and Its Report</h4><p>In the below matrix, diagonal cells represent true positives (expected value is correctly predicted) while other cells indicate the wrong prediction. The higher the diagonal values indicates the model is skillful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naxRz0fZ_AUrYVNqDMHEHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*n5XOrcWt6NcENY2lhrWi1Q.png" /></figure><p>Classification Report provides <strong>precision, recall and f1 score</strong> of all the Brand classification and the average of all.</p><blockquote>Here, <strong>Precision </strong>measures of exactness of the prediction while <strong>Recall </strong>measure of completeness of the prediction. The <strong>f1 score</strong> is the weighted average of precision and recall.</blockquote><p>All the three parameters with 0.8 above score looks encouraging.</p><p><strong><em>The same problem can be used to build a recommendation system using logistic regression. We can try it with a recommendation data set in next article.</em></strong></p><p><a href="https://francium.tech/?source=post_page---------------------------"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="http://contact@francium.tech/?source=post_page---------------------------"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bb0504864ea" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/building-prediction-model-from-conditionally-dependent-data-5bb0504864ea">Prediction from Conditionally Dependent Data in Machine Learning</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda Dependency Management using Serverless Plugin]]></title>
            <link>https://blog.francium.tech/deploying-python-packages-to-lambda-layers-using-serverless-plugin-c8fe1371e0b?source=rss-8df2e9eedd42------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8fe1371e0b</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lambda-layer]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Navarasu]]></dc:creator>
            <pubDate>Sat, 29 Jun 2019 22:38:04 GMT</pubDate>
            <atom:updated>2019-08-13T13:52:23.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dai8QgdAwrznSgvI5UDveg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/ColiN00B-346653/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3104355">Colin Behrens</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3104355">Pixabay</a></figcaption></figure><p>Packaging dependencies for lambda functions has two major points to be considered.</p><ul><li>One the libraries which has native\compiled dependencies.</li><li>Other deploying them to lambda layers instead of packing it along with functions.</li></ul><p>In the previous article, we have well discussed about deploying ruby gems with native dependencies to lambda layers.</p><p><a href="https://blog.francium.tech/deploying-ruby-to-aws-lambda-function-and-layers-a6c00b53a5d0">Deploying Ruby Script to AWS Lambda Function and Layers</a></p><h4><strong>How did we handle for Ruby gems?</strong></h4><ul><li>We have installed gems inside a <a href="https://github.com/lambci/docker-lambda">lamci</a> docker, <em>the docker which closely replicates the live AWS Lambda.</em></li></ul><pre>docker run --rm -it -v $PWD:/var/gem_build -w /var/gem_build lambci/lambda:build-ruby2.5 bundle install --path=.</pre><ul><li>Then deployed gem folder to lambda layers using aws cli.</li></ul><pre>zip -r gem_layer.zip ./ruby/ -x ./ruby/2.5.0/cache/\*</pre><pre>aws lambda publish-layer-version \<br>         --layer-name ruby_gem \<br>         --region us-west-1 \<br>         --compatible-runtimes ruby2.5 \<br>         --zip-file fileb://gem_layer.zip</pre><ul><li>And configured the layers and environment variables to use the layer’s gem in lambda functions</li></ul><pre>export LAYER_ARN=`aws lambda list-layer-versions --region us-west-1 --layer-name ruby_gem | jq -r &quot;.LayerVersions[0].LayerVersionArn&quot;`</pre><pre>aws lambda update-function-configuration \<br>      --function-name hello_world\<br>      --region us-west-1 \<br>      --layers $LAYER_ARN \<br>      --environment &#39;{&quot;Variables&quot;: {&quot;GEM_PATH&quot;:&quot;/opt/ruby/2.5.0&quot;}}&#39;</pre><h4>Handling Python Packages</h4><p>Like few ruby gems, many python packages has native dependencies. For example, Pandas has portions of its code written in C to make it run faster. These C extension will create native dependencies to os on compilation.</p><p>Like we did for Ruby gems, similar approach can be applied to deploy python requirements as well i.e, installing python packages inside lamci docker and deploying to the layers.</p><pre>export PKG_DIR=&quot;py_layer/python&quot;</pre><pre>rm -rf ${PKG_DIR} &amp;&amp; mkdir -p ${PKG_DIR}</pre><pre>docker run --rm -it -v $$PWD:/var/layer -w /var/layer lambci/lambda:build-python3.7 pip install -r requirements.txt --no-deps -t ${PKG_DIR}</pre><p>Now we can pack this py_layer folder and deploy it to lambda layer using aws cli as we did earlier.</p><h4>Using Serverless for layers</h4><p>If we are using Serverless framework, we can configure serverless with this docker output folder path. This can be done by putting this path under layers section in serverless.xml as below,</p><p><strong><em>For python</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNXMgJMna5eqmQZTBzcHZQ.png" /><figcaption>serverless.yml</figcaption></figure><p><strong><em>For Ruby</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J347lt-qLxEKl4Pqluf8zg.png" /></figure><p>Here we need to run docker command first to get the dependencies in the required folder. Then sls deploy command will do the layers deployment job along with function deployment.</p><h3>Using Serverless Plugin for Python</h3><p>In a simple way, we can use <a href="https://github.com/UnitedIncome/serverless-python-requirements"><strong><em>serverless-python-requirements</em></strong></a><strong><em> </em></strong>serverless plugin for python to do all this job in single shot. <em>i.e, when we trigger command </em><em>sls deploy</em></p><p>Lets try with simple use case by deploying pandas to lambda layers. Also we can exclude certain local packages from deploying to lamda, <em>for e.g. pytest</em></p><h4>Pre-setup</h4><p>Install Serverless</p><pre>brew install node</pre><pre>npm install -g serverless</pre><p>Install and configure AWS CLI</p><pre>pip3 install awscli</pre><pre>aws configure</pre><h4><strong>Create Sample Project</strong></h4><p>Create a serverless boilerplate for python</p><pre>sls create --t aws-python3 -p mlservice</pre><p>Configure VirtualEnv</p><pre>cd mlservice</pre><pre>virtualenv venv</pre><pre>source venv/bin/activate</pre><p>Install dependencies and freeze the requirement.</p><pre>pip install pandas pytest</pre><pre>pip freeze &gt; requirements.txt</pre><p>Update the handler.py for using Pandas to check our deployment.</p><pre>echo &#39;import pandas as pd</pre><pre>def main(event, context):<br>    dict = {&quot;country&quot;: [&quot;Brazil&quot;, &quot;Russia&quot;, &quot;India&quot;, &quot;China&quot;, &quot;South Africa&quot;],<br>       &quot;area&quot;: [8.516, 17.10, 3.286, 9.597, 1.221],<br>       &quot;population&quot;: [200.4, 143.5, 1252, 1357, 52.98] }<br>    brics = pd.DataFrame(dict)</pre><pre>return {&quot;Dataframe shape created using Pandas&quot; : brics.shape}&#39; &gt; handler.py</pre><h4>Install Serverless Plugin</h4><p>The installation happens inside our project folder cd mlservice and this will create package.json file</p><pre>sls plugin install -n serverless-python-requirements</pre><h4>Configure serverless to use plugin</h4><p>This how the serverless.yml is configured to pack python packages using docker and deploy it to lamda layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzGoY-yo4WOBvp7gwgCstw.png" /><figcaption>serverless.yml</figcaption></figure><p>With sls deploy ,</p><ul><li>dockerizePip: true config enables plugin to install package in docker</li><li>noDeploy excludes the pytest in requirement.txt before installation.</li><li>As mentioned in layer config inside pythonRequirements, the packages is deployed to lambda layers.</li><li>- {Ref: PythonRequirementsLambdaLayer} simply ties the lambda layer to function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwpVMsP_mZY30TTddNdliA.png" /></figure><p>Lets finally test our deployment by invoking the function,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*H2k3ftYjQFQhbMfmaDEnxw.png" /></figure><h3>Summary</h3><p>This plugin covers most of the use case that we needed for deploying the python packages to lambda</p><p>Some prominent use cases are,</p><ul><li>Using docker for packages</li><li>Using local machine if we don’t have any native os dependencies.</li><li>Excluding the package that we don’t need for lambda from the requirement.txt.</li><li>Handling different requirement.txt for each function.</li><li>Using layers for deploying packages.</li></ul><p>For more use cases, you can find <a href="https://github.com/UnitedIncome/serverless-python-requirements">here</a>.</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focussed on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="http://contact@francium.tech/"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8fe1371e0b" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/deploying-python-packages-to-lambda-layers-using-serverless-plugin-c8fe1371e0b">Lambda Dependency Management using Serverless Plugin</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>