<?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 Amine Lemaizi on Medium]]></title>
        <description><![CDATA[Stories by Amine Lemaizi on Medium]]></description>
        <link>https://medium.com/@amine.lemaizi?source=rss-9029e676d26b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wPWPlYbKecGTeXSOexERXg.jpeg</url>
            <title>Stories by Amine Lemaizi on Medium</title>
            <link>https://medium.com/@amine.lemaizi?source=rss-9029e676d26b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:28:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amine.lemaizi/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[Dockerize your Machine Learning model to train it on GCP!]]></title>
            <link>https://medium.com/analytics-vidhya/dockerize-your-machine-learning-model-to-train-it-on-gcp-3957e018faaa?source=rss-9029e676d26b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3957e018faaa</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Amine Lemaizi]]></dc:creator>
            <pubDate>Tue, 26 May 2020 20:52:07 GMT</pubDate>
            <atom:updated>2020-05-27T16:13:27.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVGyAQan-7R224xl4H6Jdg.jpeg" /></figure><p><em>The related code can be found here in </em><a href="https://github.com/aminelemaizi/docker-gcp-ml"><em>my GitHub repo</em></a><em>, you can use it as you please.</em></p><h3>What’s the use case ?</h3><p>You’ve just made a dope machine learning model that you need to train and unfortunately you don’t have the needed resources to do your computation, so the first idea you may have is heading to an existing cloud solutions like GCP, which will give you “cheap” computation power…but…how can we use it with ease and elegance to train and gather our model, do some predictions and get the results as a sweet csv, excel or whatever ? I know that most data scientists are a bit afraid of the big fluffy monster named “Cloud”, so I will show you how to proceed and make this operation as straightforward as possible.</p><h3>The general idea ?</h3><p>The graph bellow describe summarily how we will proceed and what are the main pillars to achieve what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bizSK7YCzZjq7HP6Q5Fr2w.png" /></figure><ul><li><strong>Index 1</strong> : A Docker image based on Ubuntu, to which we’ll add the needed dependencies to make Python work with all the necessary requirements. The main script for doing the learning and communicating with our cloud storage bucket we’ll be contained inside this image. After creating the image locally we’ll push it to the Google Container Registry so it can be private and callable from within.</li><li><strong>Index 2</strong> : A GCP computing instance, we call it VM (Virtual Machine) and this is our “computer” or “server”.</li><li><strong>Index 3</strong> : We will link our VM instance to the created Docker image (located in the Google Container Registry), so when the instance is launching it will load the container for the dockerized application.</li><li><strong>Index 4</strong> : Our training dataset is in the cloud storage bucket. When loading the Docker image our script (main.py) we&#39;ll load the training dataset using the GCP API used in Python.</li><li><strong>Index 5</strong> : After doing our training using the resources of our VM instance we’ll save our trained model in the cloud storage bucket.</li></ul><p>You can adapt this architecture and the code that will follow to your needs and use case, what to get here is the general idea about how to dockerize your process and then put or pull data from your bucket.</p><h3>Creating the main script</h3><p>The script we’re presenting here is just a dummy one, we’ll do a learning using a Decision Tree on the iris species dataset, but the general idea is the same and it can be extended or adapted to your case. It consists of three parts :</p><ol><li>Loading the training dataset from the bucket.</li><li>Doing the training and saving the model as a pickle inside the container.</li><li>Write the pickled model to your bucket.</li></ol><p>The two parts that interests us are the first and the third one.</p><h4>How to load the data from the bucket</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adb90f45d277123359b8b0f369851af3/href">https://medium.com/media/adb90f45d277123359b8b0f369851af3/href</a></iframe><p>The storage.Client() is what makes the connection to our cloud storage, there is no need to give it credentials because it will run from our GCP ecosystem. The only thing we&#39;ll need is to run the container in a privileged mode (we will see this a bit further).</p><p>storage_client.download_blob_to_file save the training dataset inside our docker container and it takes two arguments, the first one is gs://iris_ml_bucket/iris.csv which indicates the training dataset path contained in the bucket, in your case it has to have the following form gs://&lt;name-of-your-bucket&gt;/path/to/file, and the second one is the file object, here named train_file, to write the dataset locally inside the container.</p><h4>How to transfer the saved model from our container into the bucket</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d19dd38aca1f56897c5249fe89da410e/href">https://medium.com/media/d19dd38aca1f56897c5249fe89da410e/href</a></iframe><p>Here again storage.Client() makes the connection to our cloud storage. Then to select the specific bucket we use bucket = storage_client.get_bucket(&#39;iris_ml_bucket&#39;), iris_ml_bucket is the name of the bucket. Put accordingly the right name for your own <strong>existing</strong> bucket.</p><p>blob = bucket.blob(&quot;trained_model.pkl&quot;) defines the &quot;end point&quot;, in other terms we&#39;re saying to our code &quot;<em>we plan to create a file inside the bucket named </em><em>trained_model.pkl</em>&quot;.</p><p>Now that we’ve planned the where and what name to give to our future saved model, it is time to upload it by using blob.upload_from_filename and the argument it takes is the container local file path to the saved model.</p><p>In addition to the Python script, we’ll need its requirements in terms of packages. We’ll put both files inside a folder named app.</p><pre>app<br>├── main.py<br>└── requirements.txt</pre><h3>Creating the Docker image and pushing it to the Google Container Registry</h3><h4>Create the Docker image</h4><p><em>In case you need Docker references here is a cheat sheet I’ve made : </em><a href="https://github.com/aminelemaizi/cheat-sheets/blob/master/Docker-Cheat-Sheet.md"><em>https://github.com/aminelemaizi/cheat-sheets/blob/master/Docker-Cheat-Sheet.md</em></a><em>.</em></p><p>We need to dockerize our process, for this the main step is to create our Dockerfile. Here the commented Dockerfile to explain each step :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f39a5fb856fbdd581293de3ee02dc72/href">https://medium.com/media/2f39a5fb856fbdd581293de3ee02dc72/href</a></iframe><p>What follows is the building of this image, named ml-iris:</p><pre>docker build -t ml-iris .</pre><p>Make sure the folder app is at the same level of our Dockerfile.</p><pre>.<br>├── app<br>│   ├── main.py<br>│   └── requirements.txt<br>└── Dockerfile</pre><h4>Push the Docker image to Google Container Registry</h4><p>Make sure you have the GCP client installed on your machine so you can use gcloud command. This link we&#39;ll show you how to proceed : <a href="https://cloud.google.com/sdk/docs/quickstarts">https://cloud.google.com/sdk/docs/quickstarts</a>.</p><p>To guarantee that our image is private, we’ll now try to push it to our Google Container Registry but first we have to make sure this service is activated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*b0e4Bofup2wjsnpfqi15qw.gif" /></figure><p>Now let us prepare the Docker image with the right tag, for this you have to execute the following command:</p><pre>docker tag ml-iris gcr.io/&lt;gcp-project-id&gt;/ml-iris</pre><p>Your tag has to respect a certain layout which is grc.io/&lt;gcp-project-id&gt;/&lt;image-name&gt;, first grc.io indicates the Google Container Registry, then you have to put your used GCP project id and at last your Docker image name.</p><p>Now that the image has the right tag, we have to make sure that we’re authenticated from our own computer to our GCP account by running:</p><pre>gcloud auth login</pre><p>All what is remaining is just to push the Docker image to the Google Container Registry using :</p><pre>gcloud docker -- push gcr.io/lems-odyssey/ml-iris</pre><p>If everything is ok, you will see your Docker image showing up on your cloud registry, and as you can notice it bellow the visibility is as “Private” meaning nobody has access to our top secret machine learning script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*1yilda7rHmgIAHHkLDKMKA.png" /></figure><h3>Creating a cloud storage bucket</h3><p>For creating a new bucket under GCP, you need to select on the left side menu the <strong>Storage</strong> option under the <strong>STORAGE</strong> segment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*EKEjvX5qUzN_x3yJjZTdsg.png" /></figure><p>Choose a unique name for your bucket, and for the sake of the demo there is no need to change the other options, so if you have some specific use cases then change the storage options accordingly (like making sure having all your GCP products in the same zone region for reduced latency, for example). The only option to change for this demo is the <strong>Access Control</strong>, it has to be set to “Uniform” (no need in our demo to create a special access list).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*U1WwlsUvEEa2Sza0RDvolA.png" /></figure><p>Make sure that the chosen bucket name is mentioned on your Docker Python script (main.py). As you can see here, the bucket I&#39;ve created to store my iris machine learning dataset is displayed (iris_ml_bucket).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51N9BKginefXaa2TJ3ZwsQ.png" /></figure><p>And don’t forget to upload your training dataset inside this newly created bucket (same name as mentioned inside the Python script).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*kEyIg9UWq87z_jr3B5jrgg.png" /></figure><h3>Creating a VM instance linked to our Docker Image</h3><p>Now it is the “core part”, creating the instance is in itself running the learning and saving the generated trained machine learning model. How ? the fact to choose a VM instance based on a Docker image will execute our main.py script when launching VM (i.e. launching the container). So after creating the Docker VM instance we just have to wait a bit to find on our linked bucket the trained model saved as a pickle.</p><p>To create an instance you have to choose on the <strong>COMPUTE</strong> segment the option called <strong>Compute Engine</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jfpJSeXITtkwgjyGvVLQzQ.png" /></figure><p>Then choose to create a new VM instance, give it a meaningful name. For the sake of our demo we’ll be just interested on modifying the two important main options to make this work.</p><p>First, under the <strong>Container</strong> section check the <strong><em>Deploy a container image to this VM instance</em></strong> option and indicate the Docker image tag used for the Google Container Registry in the <strong><em>Container image</em></strong> field (in my case it’s gcr.io/lems-odyssey/ml-iris). After that click on <strong><em>Advanced container options</em></strong> and check the <strong><em>Run as privileged</em></strong> option, this way the container can communicate with the storage with no problem and write on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*cXsZZzMewWovBtUyg7zoDQ.png" /></figure><p>Secondly, in addition to run our container as privileged we need to give read and write access for our VM instance to the cloud storage. To do that, under the <strong><em>Identity and API access</em></strong> section of the VM instance creation and for the <strong><em>Access scopes</em></strong> sub-section choose the <strong><em>Set access for each API</em></strong> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*r-qwT0nWEcbn6JzA3Sp9Mg.png" /></figure><p>Go under until you find the option for <strong>Storage</strong> and then choose <em>Read Write</em> instead of the <em>Read</em> only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*FN1pE52nwHTKp-HHVoR5hQ.png" /></figure><p>Now all what is remaining is creating the instance and waiting a bit (even with a dummy example you have to wait like 3 to 4 minutes) and then go check the bucket. With this, we will found our trained model saved as a pickle file inside our bucket as you can see here (trained_model.pkl).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*CqFjJfPHy4UYieT3hUaphw.png" /></figure><h3>Can we do all this only in the shell with no graphical user interface ?</h3><p>The answer is yes ! We can redo all this just from the comfort of our shell and we’ll see together the commands to achieve the same results.</p><p>First, make sure you have the same layout as this :</p><pre>.<br>├── app<br>│   ├── main.py<br>│   └── requirements.txt<br>├── Dockerfile<br>└── iris.csv</pre><p>And here is the shell script to use :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f5f5f0f6fb0ddaef560cda2e5141d71/href">https://medium.com/media/2f5f5f0f6fb0ddaef560cda2e5141d71/href</a></iframe><p>If there is options in this script that you don’t understand, better google them!</p><p>This is all folks!</p><p>You can follow me on <a href="https://twitter.com/ALemaizi">Twitter</a>, <a href="https://www.facebook.com/lemsodyssey/">Facebook</a>, <a href="https://www.linkedin.com/company/lemsodyssey/">LinkedIn</a> or <a href="https://medium.com/@amine.lemaizi">Medium</a> to be notified when new posts are published!</p><p>LEM OUT!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3957e018faaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/dockerize-your-machine-learning-model-to-train-it-on-gcp-3957e018faaa">Dockerize your Machine Learning model to train it on GCP!</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Very Basic Machine Learning Automation Using Fabric 2]]></title>
            <link>https://medium.com/analytics-vidhya/very-basic-machine-learning-automation-using-fabric-2-4549665f611b?source=rss-9029e676d26b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4549665f611b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Amine Lemaizi]]></dc:creator>
            <pubDate>Tue, 31 Mar 2020 12:56:22 GMT</pubDate>
            <atom:updated>2020-03-31T12:56:22.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx6ZtogoEokXv3cxxyu1Lg.png" /></figure><p>What if by the magic of automation, you can run your machine learning training or prediction on a remote server just by typing three or two commands lines, without going through the hustle of connecting to your virtual machine, configuring your Python environment, uploading your data and doing all those repetitive tasks again and again. With all the existing cloud platforms like GCP, AWS or Azure, this use case is handled really well by a variety of existing solutions they offer, that’s been said it’s not always the right fit for you if for example you’re the only “data guy” on your team with a very very restricted budget and your boss is only allowing you one GCP VM to work with and you’ve got a love hate relationship with data engineering…you know, the “common case”.</p><p>Fabric 2 can be a good fit for this task. What is Fabric 2 you will ask, it’s a Python library that gives you the possibility to run shell commands on a remote machine over SSH. So with the use of Fabric 2, I can train a model on a remote server, which I’ve never configured before, just by typing on my local shell the three following commands :</p><pre>fab2 prepare-os<br>fab2 prepare-menv<br>fab2 train-model --dataset=&lt;link_to_train_data&gt; --epochs=50</pre><p>The first command will install all needed packages (like installing Python itself) in the remote server, the second one will upload the needed assets for the training and will create Python virtual environment with the required libraries and then the last command will do the proper training and download locally a copy of the final model.</p><p>As you can see on the third command, we can add arguments to customize our function and make it as adaptive as possible like specifying the train dataset and an argument of how many epochs we’ll need.</p><pre>fab2 train-model --dataset=&lt;link_to_train_data&gt; --epochs=50</pre><p>I will show you how all this works and you can use it yourself by adapting the code I’ve written on this <a href="https://github.com/aminelemaizi/fabric2-ml-automation">github repo</a>.</p><h3>Use case scenario</h3><p>My use case scenario her is the design of a MNIST Autoencoder, which I will use to generate autoencoded images. I will automate this process, so I can in any Ubuntu server (18.04 LTS) run the training, get the model and generate autoencoded images to be retrieved to my local machine.</p><h3>Installing Fabric 2</h3><p>To install Fabric 2, you can use <strong>pip</strong> to do so:</p><pre>pip install fabric2</pre><h3>Assets &amp; Project Layout</h3><p>The project root will contain three main elements :</p><ul><li><strong>fabfile.py</strong> : it is the file containing all the tasks automating our workflow. It is important to have this name, so when running fab2 at the project root it will recognize which file contains the list of tasks.</li><li><strong>assets</strong> : it&#39;s the directory containing elements and information related to remote server authentication or any relevant data to use for the distant machine, as encryption keys, passwords, hostnames or username.</li><li><strong>ml_assets</strong> : this is the directory containing our assets related to the machine learning model, like the model itself, requirements to install into the virtual machine or the training data. it&#39;s the only folder to be uploaded to the remote server.</li></ul><p>This is the layout that I’ve adopted for this project, feel free to adapt it better to your needs :</p><pre>.<br>├── fabfile.py<br>├── assets<br>│   ├── secrets.json<br>│   └── server_ssh_key<br>└── ml_assets<br>    ├── mnist_train.csv<br>    ├── model.py<br>    └── Requirements.txt</pre><p>Before discussing the creation of tasks in fabfile.py, we will first tackle the content of our assets folders, assets and ml_assets.</p><h4>assets folder</h4><pre>├── assets<br>│   ├── secrets.json<br>│   └── server_ssh_key</pre><p>The first file is secrets.json, as its name suggests it contains our little “secrets” mainly session passwords, SSH Key passphrase and anything you think is sensitive and doesn’t have to show up on your code.</p><pre>{    <br>    &quot;password&quot; : &quot;&lt;password&gt;&quot;,<br>    &quot;passphrase&quot; : &quot;&lt;passphrase&gt;&quot;<br>}</pre><p>This folder also contains the encryption key, so you can securely access your remote server if needed. For this matter, you have to make sure that you’re not tracking this folder in git and it is well included inside your <strong>.gitignore</strong>.</p><h4>ml_assets folder</h4><pre>└── ml_assets<br>    ├── mnist_train.csv<br>    ├── model.py<br>    └── Requirements.txt</pre><p>The <strong>Requirements.txt</strong> is very important : in addition to list the needed libraries, it helps to specify the exact version you want to use for your different Python libraries, so there is no unexpected behavior. Automation needs a kind of predictability. And in our use case, we&#39;re focused on the following versions :</p><pre>pandas==1.0.2<br>tensorflow==1.13.1<br>matplotlib==3.1.3</pre><p>We also have to put our training dataset, which is <strong>mnist_train.csv</strong>, inside this folder. My logic here is that the data training set is part of what defines your model, hence it has to be part of the machine learning assets.</p><p>And the last element to have is our model script <strong>model.py</strong>, which contains the two main functions <strong>train</strong> and <strong>predict</strong>. The script decide which of this two functions to use based on the shell entry arguments that we&#39;ll pass to it, as expressed in the main.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/addc53da18ff37ccddecbc36086c7b02/href">https://medium.com/media/addc53da18ff37ccddecbc36086c7b02/href</a></iframe><h3>Creating tasks using Fabric 2</h3><p>Now we’ll attack the <strong>fabfile.py</strong> file where all the magic happens. To do so, I will explain the code contained inside this file fragment by fragment so you can get the logic behind it and how to use Fabric 2 in general.</p><p>In this segment we import the main Fabric 2 tools, which are the <strong>Connection</strong> class to connect to our remote server, the <strong>Config</strong> class to define some configuration linked to authentication and a function decorator, <strong>task</strong>, that makes Fabric 2 functions (called tasks) recognizable when executing them on the shell, like <strong>fab2 fab-task</strong>. We will define four global variables for the username, the remote server ip-address, the location of the encryption key and our &quot;secrets&quot; (password and passphrase).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e44a0185cdf56e1bd21ed3630cb11a6/href">https://medium.com/media/0e44a0185cdf56e1bd21ed3630cb11a6/href</a></iframe><p>Here we define a function to connect to our remote server and as you can see it specifies the password to use when using the <strong>sudo</strong> commands.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b79bd016c055bc95e200be2a9e8b1d9/href">https://medium.com/media/2b79bd016c055bc95e200be2a9e8b1d9/href</a></iframe><p>This task defines the information of our remote server, so when using the <strong>connect_to_host</strong> with no previous established connection it will have what is needed to connect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b00215688f04155744de100a00146008/href">https://medium.com/media/b00215688f04155744de100a00146008/href</a></iframe><p>For this one, we’re simply updating our OS packages list and then installing all needed packages (like Python 3) so we can have a proper working OS. As you can notice, we’re running shell commands as strings and we’re mentioning that it has to run as a sudo by using <strong>conn.sudo(&quot;...&quot;)</strong>. To define the steps for this segment in words, this is what it does :</p><ul><li>Define information of the remote host.</li><li>Connect to remote host.</li><li>Update packages list as a sudo.</li><li>Install needed packages as a sudo.</li><li>Close connection.</li></ul><p>Something to be mentioned, all tasks defined with an underscore get a hyphen when called in the shell for execution, so the task <strong>prepare_os</strong> when called is written as <strong>prepare-os</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a68ec0a8d1480091b9067203711ed0d/href">https://medium.com/media/1a68ec0a8d1480091b9067203711ed0d/href</a></iframe><p>Now we need a task to upload our machine learning assets and create a Python virtual environment containing all required libraries. Fabric 2 doesn’t offer folder uploading, so to get around this we will compress our <strong>ml_assets</strong> folder into a file then uploading it to be decompressed in the remote server. The shell commands here doesn&#39;t need to be run as a sudo this is why we&#39;re using <strong>conn.run(...)</strong>, and for running commands in the local machine and not in the remote server we use <strong>conn.local(...)</strong>.</p><p>This task does the following actions:</p><ul><li>Define information of the remote host.</li><li>Connect to remote host.</li><li>Compressing the <strong>ml_assets</strong> folder.</li><li>Uploading the compressed file using <strong>conn.put(&lt;local_file&gt;, &lt;remote_folder&gt;)</strong>.</li><li>Decompressing the file in the remote server.</li><li>Deleting the compressed file both locally and remotely.</li><li>Create a Python virtual environment called <strong>modelenv</strong>.</li><li>Upgrading <strong>pip</strong> inside <strong>modelenv</strong>.</li><li>Installing required Python libraries contained inside <strong>Requirements.txt</strong>.</li><li>Show the list of installed Python libraries.</li><li>Close connection.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/157c32b277b76f9121b6d5d4c38d0ae0/href">https://medium.com/media/157c32b277b76f9121b6d5d4c38d0ae0/href</a></iframe><p>We’re having the right OS and Python environment and all what is needed now is our main execution. This task does the training by calling our Python script <strong>model.py</strong> and defining the expected arguments to inform it that we&#39;re requesting a training, defining our dataset to be trained and the number of epochs. After the learning phase, we will download a copy of the model into our local machine using the <strong>conn.get(&lt;remote_file&gt;, &lt;local_file&gt;)</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c297d1e6c01c946c9e46150611e728b/href">https://medium.com/media/8c297d1e6c01c946c9e46150611e728b/href</a></iframe><p>This task can be called as follow :</p><pre>fab2 train-model --dataset=&lt;link_to_train_data&gt; --epochs=50</pre><p>The last piece is the prediction, and it contains the following actions :</p><ul><li>Define information of the remote host.</li><li>Connect to remote host.</li><li>Upload the dataset for prediction to the remote server.</li><li>Upload a copy of the model trained to the remote server.</li><li>Make a folder called <strong>autoencoded</strong> where we will save our autoencoded images.</li><li>Run prediction.</li><li>Compressing the <strong>autoencoded</strong> folder.</li><li>Downloading the compressed file.</li><li>Deleting the model copy, the prediction dataset, the <strong>autoencoded</strong> folder and its compressed file present in the remote server.</li><li>Decompressing locally the <strong>autoencoded.zip</strong> file.</li><li>Removing the compressed file.</li><li>Close connection.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3296b0b134b143ba937cc52412fad9ce/href">https://medium.com/media/3296b0b134b143ba937cc52412fad9ce/href</a></iframe><p>It is to mention that we distinguish between the training and the prediction. What I mean is those two processes can be run in two different servers. What is important, is during the prediction our copy of the model is present in the machine learning assets, which would be the case if we’ve run at least once the training task.</p><h3>Automation in action</h3><p>Now let us see how in practice this functions work by running each task and observe what are the outputs!</p><h4>Preparing our remote host OS (Ubuntu 18.04 LTS)</h4><pre>fab2 prepare-os</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6INRWeFSAOlXiWd_OfuwzA.png" /></figure><h4>Uploading assets and preparing Python virtual environment</h4><pre>fab2 prepare-menv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*XDK0VzG_fGDC3BQkRg1Xag.png" /></figure><h4>Training the autoencoder</h4><pre>fab2 train-model --dataset=./ml_assets/mnist_train.csv --epochs=5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*J8iB0LsPrWR7AaQN4X2fYQ.png" /></figure><p>After this, the copy of the model is created locally :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*xtuNG6zVoHjsXzXmxI4AHg.png" /></figure><h4>Creating autoencoded images</h4><pre>fab2 predict-data --dataset=./ml_assets/mnist_predict.csv</pre><p>This code will create the autoencoded images locally as shown here bellow, and voilà!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*rgrqyS5HgP8jXWoBduSTrg.png" /></figure><p>This is all folks!</p><p>You can follow me on <a href="https://twitter.com/ALemaizi">Twitter</a>, <a href="https://www.facebook.com/lemsodyssey/">Facebook</a> or <a href="https://medium.com/@amine.lemaizi">Medium</a> to be notified when new posts are published!</p><p>LEM OUT!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4549665f611b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/very-basic-machine-learning-automation-using-fabric-2-4549665f611b">Very Basic Machine Learning Automation Using Fabric 2</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Best Worst Idea to Have : Creating my Own Machine Learning Library “Ostorlab”]]></title>
            <link>https://medium.com/@amine.lemaizi/the-best-worst-idea-to-have-creating-my-own-machine-learning-library-ostorlab-b246d89d988c?source=rss-9029e676d26b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b246d89d988c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amine Lemaizi]]></dc:creator>
            <pubDate>Sun, 12 Jan 2020 13:28:03 GMT</pubDate>
            <atom:updated>2020-01-12T13:28:03.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Best Worst Idea to Have : Creating my Own Machine Learning Library “Ostorlab”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THXwZlphLL1eHInom5yR0A.jpeg" /></figure><p>You’re certainly reading this post title with a very cringey face like “how the hell someone creates his own machine learning library in 2020 ?! Are you a moron or what !!!” kudos to you gatekeepers, I understand pretty well your motivations and your deep desire to curse me with a thousand names. I will explain the obvious of why you should never consider creating your own machine learning library, before stating my case.</p><h4>Primo : A lot of mature solutions in machine learning already exists</h4><p>There is a LOT of mature libraries already out there, for any language you may imagine and for any “application” context you may consider (like clusters vs single machines). Any pragmatic and practical fellow will choose right away an existing mature solution and will stick to it.</p><h4>Secundo : You will write an unsharable code</h4><p>The biggest issue with writing your own library and making projects with it is, the obvious fact, that you’re not looking for a general adoption, few people will venture out and test your code but the big majority won’t even bother because your code is like a planet in the outer rim of the galaxy, it may be beautiful but not near the core of day to day scripts and tools used by everybody.</p><h4>Tertio : Nobody wants something with no guarantee</h4><p>You may have created the most sophisticated library ever seen since <a href="https://github.com/ajalt/fuckitpy/blob/master/README.md">FuckIt.py</a>, and the humanity’s salvation is at your own hands…but you’ve had enough of this side project and it is time to move on, just imagine all the people that trusted your messianic library, they are now doomed. Technology adoption with no continuity does not only suck but it is very dangerous to projects livelihood that adopted it…people prefer a mediocre solution guaranteed to be around in four years than an ephemeral perfect fit.</p><p>Ok, now that <a href="https://www.youtube.com/watch?v=dumA6TvyoRU">I have spoken</a> and made <strong>YOUR</strong> case clear, no need to crucify me. You’ve certainly concluded that I understand “a bad idea, it is”…but! There is a lot to gain by doing this, so I will try to make my case clear.</p><p>What I’m aiming for is creating a machine learning library with two variants written in Python and JavaScript, that I will call respectively <a href="https://pypi.org/search/?q=ostorlab">Ostorlab</a> and <a href="https://www.npmjs.com/package/ostorlab">OstorlabJS</a>. Why this name? It’s the Arabic pronunciation of astrolabe, a very elegant and handy tool for astronomical measurements perfected by the Islamic culture during medieval times. I have a huge fascination for Islamic astrolabes : they mix beauty and practicality, a “philosophy” to which I’m really attracted to, it’s like art and science mixing together to express the beauty and sophistication that emerges from the human mind! So, I hope this will be my leitmotif and the name is here to remind me of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Kg4OhtiOeesamYMKT5Oc4g.jpeg" /><figcaption>An 18th Century Persian astrolabe (Wikimedia Commons)</figcaption></figure><p>Back to the “bad idea”. How on earth, starting such a side project can be the “best worst idea” you may have, and here is my case :</p><h4>Ego!</h4><p>A lot of people won’t admit it, but sometimes ego is the pure motivation for starting a lot of stuff. There was many situation where I wanted just to shout out to some dumbasses “I fucking understand and know how to create what you assume I’m not able to grasp”, and having my own library is like the kick in the balls for such people. Ok to put this in context, now I happen to live in Paris, France, and there is a weird elitism here, if you didn’t graduate from the local “Ivy League” engineering schools it is assumed, for a big number of people, that you don’t have the necessary intellectual abilities to understand math, machine learning and statistics, and you’re just another coder who use from sklearn import without giving you any chance to prove them wrong (true story...). Yeah, pure ego...so let&#39;s make a twist to there prejudice by using from myfunckinglibrary import.</p><h4>Sharpening your coding skills</h4><p>Let’s be frank, Jupyter notebook is the “go to” coding tool for data scientists and the way we write code on it is really bad. It is far from being production ready, the code isn’t well written nor structured and with time we harness bad habits. Creating a machine learning or any “official” library will force you to adopt best practices, write unit tests, think in terms of scaling the app and see beyond your “cell”.</p><p>Also, I’ve never had the chance to make big projects in JavaScript, my use cases were limited to the creation of some scripts and using some well known frameworks, so I’ve decided in addition to writing Ostorlab in Python, I will do the same in JavaScript just to force myself to deep dive into this language.</p><h4>Deepening your knowledge</h4><p>If you’re transparent with yourself, going from a machine learning theoretical notion to a functioning code requires a deep and precise understanding to implement it properly. The best thing to do for deepening your machine learning knowledge is to build “everything” from scratch, it forces you to challenge what you think you master, understand or grasp and gives you the chance to strengthen further your base knowledge.</p><h4>Having an excuse to create content</h4><p>I’m planning to write a set of blog posts where I will try to demystify some machine learning theories, algorithms and concepts. So creating my own machine learning library is a great excuse to write this blog posts and add to them an aspect of practicality. It’s like presenting the theory first then go and apply it by adding another puzzle piece to the Ostorlab jigsaw.</p><p>I think I’ve stated my case, and you can follow the progresses of my two libraries on there respective repos, for <a href="https://github.com/aminelemaizi/ostorlab">Python</a> and <a href="https://github.com/aminelemaizi/ostorlabjs">JavaScript</a>. And for the linked machine learning blog posts, I will list published posts at <a href="https://github.com/aminelemaizi/machine_learning">this repo here</a>.</p><p>You can follow me on <a href="https://twitter.com/ALemaizi">Twitter</a>, <a href="https://www.facebook.com/lemsodyssey/">Facebook</a> or <a href="https://medium.com/@amine.lemaizi">Medium</a> to be notified when new posts are published!</p><p>LEM OUT!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b246d89d988c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Your Own Micro-Cluster]]></title>
            <link>https://medium.com/analytics-vidhya/creating-your-own-micro-cluster-5b75c1500ead?source=rss-9029e676d26b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b75c1500ead</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Amine Lemaizi]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 12:05:04 GMT</pubDate>
            <atom:updated>2022-12-23T22:59:22.653Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Docker, To Experiment With Spark &amp; Dask on Yarn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXC67m_cQRRZ7YPto2yXxQ.jpeg" /></figure><p><em>Before starting, I have a quick disclaimer : This post is not a Docker tutorial but a post on how to use Docker to create a cluster on your own machine. If you’ve never heard of it before (which would be surprising) or you’ve never had the chance to play with it, I highly recommend you to watch this very great introductory </em><a href="https://www.youtube.com/watch?v=zJ6WbK9zFpI"><em>video</em></a><em> made by </em><a href="https://github.com/mmumshad"><em>Mumshad Mannambeth</em></a><em>. I’ve also made a very short and consistent </em><a href="https://github.com/aminelemaizi/cheat-sheets/blob/master/Docker-Cheat-Sheet.md"><em>cheat-sheet</em></a><em> that you can refer to.</em></p><p><em>In addition to that, I will assume you already know what Dask, Spark, Yarn and Hadoop are all about. Again this isn’t an introductory tutorial but more of a “cookbook”, so to speak.</em></p><p><em>In case you’re here for the code and want to have a turnkey cluster on your own machine don’t hesitate to use my code on </em><a href="https://github.com/aminelemaizi/micro-cluster-lab"><em>my git repo</em></a><em> as you please.</em></p><p>When first learning Spark or Dask, we generally run them on our local machine, it is convenient and somehow simple but far from being a real life application scenario where we would be using distributed computations on many nodes. And sometime we want just to test one or two things on Spark or Dask, so we remember that we’ve deleted that standalone folder from last time or we’ve thrown away the python virtual environment where we’ve sweetly installed Dask and Pyspark and redoing configurations is a real pain in the a**.</p><p>Docker can be a good tool to make our life a bit easier regarding this, it can simulate a “real life” environment on your own machine, where we will harness its OS-level virtualization power to put Yarn, Spark and Dask on a 1-Master 2-Slaves cluster (more or less depending on your machine’s power).</p><p>The first reaction you may have, if you’re not very familiar with Docker, is to ask why not using many virtual machines to do the job?! It is a valid question in my opinion and for that I have two answers: firstly Docker do virtualization too, but in a low level which means a high gain in terms of resources consumption, more room for ressources means more virtual machines (called containers), plus Docker’s virtualization isn’t the “objective” but just a mean to run application contained on virtual machines which brings me to my second point that Docker is a “Platform as a Service”, or in a more cool-forced way a PaaS, which means the presence of a consistent API to run our containers and configure them without any hustle.</p><h3>Cluster Architecture</h3><p>The architecture I’m imagining is a cluster with three nodes. One is a master, it won’t do any “work” but will be sort of a manager to other nodes, plus it will host the web interfaces (a Jupyter notebook and the Yarn resource manager UI) that we’ll be using to run and check our works on top of the cluster. The two other nodes are slaves (computer science can be harsh sometimes), they will do the heavy lift and execute any compute-map-reducy-machine-learny stuff we want them to do.</p><p>As presented in the following image, Docker is running inside the host (your own computer in less fashionable words) and will run three containers corresponding to the three nodes I’ve discussed before. This architecture depends on your resources (number of CPUs and quantity of RAM your machine has), you can go up to 6 nodes if you wish or go down to 2 nodes if your resources are limited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*srWtJ8-Oj1UgIqcB2kdG7w.png" /><figcaption>A 1-Master 2-Slaves Architecture, you can see the cluster is confined inside Docker</figcaption></figure><h3>Files Tree to Use</h3><p>This <a href="https://github.com/aminelemaizi/micro-cluster-lab">project</a> will be organized as follow :</p><pre>├── docker-compose.yml<br>├── Dockerfile<br>├── confs<br>│   ├── config<br>│   ├── core-site.xml<br>│   ├── hdfs-site.xml<br>│   ├── mapred-site.xml<br>│   ├── requirements.req<br>│   ├── slaves<br>│   ├── spark-defaults.conf<br>│   └── yarn-site.xml<br>├── datasets<br>│   ├── alice_in_wonderland.txt<br>│   └── iris.csv<br>├── notebooks<br>│   ├── Bash-Interface.ipynb<br>│   ├── Dask-Yarn.ipynb<br>│   ├── Python-Spark.ipynb<br>│   └── Scala-Spark.ipynb<br>└── script_files<br>    └── bootstrap.sh</pre><ul><li><strong>docker-compose.yml</strong> : here where the magic happens, this file will contain all the set of directives that Docker will use to create the whole cluster, configure the network and set properties for each node.</li><li><strong>Dockerfile</strong> : this is what Docker use to create the image (OS + needed applications) that we’ll use for our containers.</li><li><strong>confs </strong>: this folder will contain the configuration files for Hadoop, Yarn and Spark in addition to the requirements for python.</li><li><strong>datasets</strong> : this folder contains the “starter” datasets to use for experimenting with our cluster. I’ve chosen very small datasets to play with, remember this cluster is not for “real” work but just to test stuff.</li><li><strong>notebooks</strong> : those are the notebooks “starters”, each one contains the basic commands to launch our cluster for Scala-Spark (the real Spark you say?!), Python-Spark (yeah, I know Pyspark…) and Dask. In addition to those three, there is a notebook running a Bash-Kernel so you can have an interface with the command shell.</li><li><strong>script_files</strong> : I will put here all the bash scripts to be executed. Right now, I have only one named bootstrap.sh, it will be executed at each time the container is starting. I&#39;ll explain a bit further what it does exactly.</li></ul><h3>Resources &amp; Preset configuration for Hadoop, Yarn &amp; Spark</h3><p>Configuration is a huge deal here, because of the resources you have. Remember, we’re trying to simulate many nodes on one machine, so if you have for example 4 GB of RAM and a lonely CPU…I think better not to bother with all this and stick to whatever is running on your machine. But if you happen to have like 16 GB of RAM and 4 cores or more, yeah go ahead this will give you the ability to simulate a cluster, if you don’t have any within your reach (even 8 GB can do the job but you have to limit yourself to one slave node…) .</p><p>That’s been said, I will introduce here the default configuration I’ve used to run the three nodes, and you can of course change them so it can suit your needs and machine limits.</p><p>spark-defaults.conf (Spark)</p><pre># We inform Spark that it has to use Yarn<br>spark.master                     yarn<br># Client mode is important so we can interact with Spark using Jupyter<br>spark.submit.deployMode          client<br># Spark driver and executor memory<br>spark.driver.memory              512m<br>spark.executor.memory            512m<br># This has to be lower than yarn.nodemanager.resource.memory-mb (inside yarn-site.xml)<br>spark.yarn.am.memory             1G</pre><p>slave (Yarn/Hadoop), here we define the names of our salves, as we will see it further those names are defined at the level of the docker-compose.yml file. The internal Docker DNS manages to match those names with their respective machines.</p><pre>node-slave1<br>node-slave2</pre><p>core-site.xml (Yarn/Hadoop), we&#39;re defining here the Master Node&#39;s name (&quot;the host&quot;) and the port for using HDFS communication. In this case my Master Node name is node-master and the HDFS port is 9000.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;?xml-stylesheet type=&quot;text/xsl&quot; href=&quot;configuration.xsl&quot;?&gt;<br>​<br>&lt;configuration&gt;<br>        &lt;property&gt;<br>            &lt;name&gt;fs.default.name&lt;/name&gt;<br>            &lt;value&gt;hdfs://node-master:9000&lt;/value&gt;<br>        &lt;/property&gt;<br>&lt;/configuration&gt;</pre><p>hdfs-site.xml (Hadoop), we are defining here some properties related to the HDFS system. We&#39;ve set the number of replication (dfs.replication) to be equal to the number of nodes, in this case 2 means each file will be duplicated through the cluster. Other than that, we are simply setting the directory for the namenode and the datanode.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;?xml-stylesheet type=&quot;text/xsl&quot; href=&quot;configuration.xsl&quot;?&gt;<br>​<br>&lt;configuration&gt;<br>   &lt;property&gt;<br>            &lt;name&gt;dfs.namenode.name.dir&lt;/name&gt;<br>            &lt;value&gt;/opt/hadoop/data/nameNode&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>            &lt;name&gt;dfs.datanode.data.dir&lt;/name&gt;<br>            &lt;value&gt;/opt/hadoop/data/dataNode&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>            &lt;name&gt;dfs.replication&lt;/name&gt;<br>            &lt;value&gt;2&lt;/value&gt;<br>    &lt;/property&gt;<br>&lt;/configuration&gt;<br>​</pre><p>yarn-site.xml (Yarn), here we&#39;re setting Yarn&#39;s resources consumption and indicating who&#39;s the Master Node. Each slave will then use only one core (yarn.nodemanager.resource.cpu-vcores), and a maximum memory of 1536 MB (yarn.nodemanager.resource.memory-mb).</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;configuration&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.acl.enable&lt;/name&gt;<br>                &lt;value&gt;0&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.resourcemanager.hostname&lt;/name&gt;<br>                &lt;value&gt;node-master&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.nodemanager.aux-services&lt;/name&gt;<br>                &lt;value&gt;mapreduce_shuffle&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.nodemanager.resource.cpu-vcores&lt;/name&gt;<br>                &lt;value&gt;1&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.nodemanager.resource.memory-mb&lt;/name&gt;<br>                &lt;value&gt;1536&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.scheduler.minimum-allocation-mb&lt;/name&gt;<br>                &lt;value&gt;256&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.scheduler.maximum-allocation-mb&lt;/name&gt;<br>                &lt;value&gt;1536&lt;/value&gt;<br>        &lt;/property&gt;<br>        &lt;property&gt;<br>                &lt;name&gt;yarn.nodemanager.vmem-check-enabled&lt;/name&gt;<br>                &lt;value&gt;false&lt;/value&gt;<br>        &lt;/property&gt;<br>&lt;/configuration&gt;</pre><p>mapred-site.xml (Yarn/Hadoop), this time it is the map and reduce processing we&#39;re configuring.</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;?xml-stylesheet type=&quot;text/xsl&quot; href=&quot;configuration.xsl&quot;?&gt;<br>​<br>&lt;configuration&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.framework.name&lt;/name&gt;<br>      &lt;value&gt;yarn&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;yarn.app.mapreduce.am.env&lt;/name&gt;<br>      &lt;value&gt;HADOOP_MAPRED_HOME=$HADOOP_HOME&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.map.env&lt;/name&gt;<br>      &lt;value&gt;HADOOP_MAPRED_HOME=$HADOOP_HOME&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.reduce.env&lt;/name&gt;<br>      &lt;value&gt;HADOOP_MAPRED_HOME=$HADOOP_HOME&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;yarn.app.mapreduce.am.resource.mb&lt;/name&gt;<br>      &lt;value&gt;1536&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;yarn.app.mapreduce.am.command-opts&lt;/name&gt;<br>      &lt;value&gt;400&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.map.memory.mb&lt;/name&gt;<br>      &lt;value&gt;256&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.reduce.memory.mb&lt;/name&gt;<br>      &lt;value&gt;256&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.map.java.opts&lt;/name&gt;<br>      &lt;value&gt;200&lt;/value&gt;<br>  &lt;/property&gt;<br>  &lt;property&gt;<br>      &lt;name&gt;mapreduce.reduce.java.opts&lt;/name&gt;<br>      &lt;value&gt;400&lt;/value&gt;<br>  &lt;/property&gt;<br>&lt;/configuration&gt;</pre><p>If you don’t know how to choose the right values that matches your resources, Cloudera has <a href="https://docs.cloudera.com/HDPDocuments/HDP2/HDP-2.6.5/bk_command-line-installation/content/determine-hdp-memory-config.html">this article</a> explaining some heuristics to be used.</p><h3>Creating the Base Image</h3><p>Now we need a special “distribution” (called an image in the Docker jargon) that we will run on our three containers, it must include the necessary applications and configurations so we can have a little sweet OS with Python, Spark, Hadoop &amp; Yarn and all friends on it!</p><p>To do this, we will put the necessary instruction inside the file named Dockerfile. We start by specifying what is the base OS/Image to use, in our case it would be an Ubuntu Bionic Beaver also known as Ubuntu 18.04 LTS.</p><pre>FROM ubuntu:bionic</pre><p>Right after we will define all necessary environment variables for the (to be) running session. The comments explain the role of each line.</p><pre># showing to hadoop and spark where to find java!<br>ENV JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre<br>​<br># after downloading hadoop (a bit further) we have to inform any concerned<br># app where to find it<br>ENV HADOOP_HOME /opt/hadoop<br>​<br># same for the hadoop configuration<br>ENV HADOOP_CONF_DIR /opt/hadoop/etc/hadoop<br>​<br># and same for spark<br>ENV SPARK_HOME /opt/spark<br>​<br># with this we can run all hadoop and spark scripts and commands directly from the shell<br># without using the absolute path<br>ENV PATH=&quot;${HADOOP_HOME}/bin:${HADOOP_HOME}/sbin:${SPARK_HOME}/bin:${SPARK_HOME}/sbin:${PATH}&quot;<br>​<br># just informing the hadoop version, this isn&#39;t really necessary<br>ENV HADOOP_VERSION 2.7.0<br>​<br># if you happend to run pyspark from shell, it will launch it on a Jupyter Notebook<br># this is just two fancy lines, really no need for it<br>ENV PYSPARK_DRIVER_PYTHON=jupyter<br>ENV PYSPARK_DRIVER_PYTHON_OPTS=&#39;notebook&#39;<br>​<br># showing pyspark which &quot;python&quot; command to use<br>ENV PYSPARK_PYTHON=python3</pre><p>We will now update the OS; install Java, an SSH server and Python (including pip and other dependencies). You can also see that we’ve installed wget (to download from urls) and nano (to access and modify files), it may seem weird but the basic distribution used by Docker ubuntu:bionic is very very lean and contains only what is necessary to define the distribution itself.</p><pre>RUN apt-get update &amp;&amp; \<br>    apt-get install -y wget nano openjdk-8-jdk ssh openssh-server<br>RUN apt update &amp;&amp; apt install -y python3 python3-pip python3-dev build-essential libssl-dev libffi-dev libpq-dev</pre><p>Now we will copy the requirements file inside the image and then install them on Python.</p><pre>COPY /confs/requirements.req /<br>RUN pip3 install -r requirements.req<br>RUN pip3 install dask[bag] --upgrade<br>RUN pip3 install --upgrade toree<br>RUN python3 -m bash_kernel.install</pre><p>It is time to download Hadoop and Spark and extract each one of them into its specific folder.</p><pre>RUN wget -P /tmp/ <a href="https://archive.apache.org/dist/hadoop/common/hadoop-2.7.0/hadoop-2.7.0.tar.gz">https://archive.apache.org/dist/hadoop/common/hadoop-2.7.0/hadoop-2.7.0.tar.gz</a><br>RUN tar xvf /tmp/hadoop-2.7.0.tar.gz -C /tmp &amp;&amp; \<br>  mv /tmp/hadoop-2.7.0 /opt/hadoop<br>​<br>RUN wget -P /tmp/ <a href="http://mirror.ibcp.fr/pub/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz">http://mirror.ibcp.fr/pub/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz</a><br>RUN tar xvf /tmp/spark-2.4.4-bin-hadoop2.7.tgz -C /tmp &amp;&amp; \<br>    mv /tmp/spark-2.4.4-bin-hadoop2.7 ${SPARK_HOME}</pre><p>We need to generate an SSH key to allow communication between our containers as expected by Hadoop and Spark. Just to clarify something, installing Hadoop is necessary to run Yarn and using the HDFS.</p><pre>RUN ssh-keygen -t rsa -P &#39;&#39; -f ~/.ssh/id_rsa &amp;&amp; \<br>  cat ~/.ssh/id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys &amp;&amp; \<br>  chmod 600 ~/.ssh/authorized_keys<br>COPY /confs/config /root/.ssh<br>RUN chmod 600 /root/.ssh/config</pre><p>Now we will copy the preset configurations and the ENTRYPOINT script ( a script to be executed each time we will run a container with this image).</p><pre>COPY /confs/*.xml /opt/hadoop/etc/hadoop/<br>COPY /confs/slaves /opt/hadoop/etc/hadoop/<br>COPY /script_files/bootstrap.sh /<br>COPY /confs/spark-defaults.conf ${SPARK_HOME}/conf</pre><p>Exposing ports so the container can listen to them, by default it’s a TCP port.</p><pre>EXPOSE 9000<br>EXPOSE 7077<br>EXPOSE 4040<br>EXPOSE 8020<br>EXPOSE 22</pre><p>Finally we will copy the starters (notebooks and datasets) and specify the command to run as the ENTRYPOINT of our image, in our case it’s simply running the bootstrap.sh script.</p><pre>RUN mkdir lab<br>COPY notebooks/*.ipynb /root/lab/<br>COPY datasets /root/lab/datasets<br>​<br>ENTRYPOINT [&quot;/bin/bash&quot;, &quot;bootstrap.sh&quot;]</pre><p>The bootstrap.sh script is doing four things :</p><ul><li>Formating the namenode to support HDFS.</li><li>Running the SSH client.</li><li>Check if we are at the Master Node or not, if it’s the case it will start Hadoop, Yarn and run Jupypter (properly so no tokens or passwords are needed).</li><li>Launch an empty loop so our node will reamin up without terminating the container.</li></ul><pre>#!/bin/bash<br>​<br>hdfs namenode -format<br>service ssh start<br>if [ &quot;$HOSTNAME&quot; = node-master ]; then<br>    start-dfs.sh<br>    start-yarn.sh<br>    cd /root/lab<br>    jupyter trust Bash-Interface.ipynb<br>    jupyter trust Dask-Yarn.ipynb<br>    jupyter trust Python-Spark.ipynb<br>    jupyter trust Scala-Spark.ipynb<br>    jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root --NotebookApp.token=&#39;&#39; --NotebookApp.password=&#39;&#39; &amp;<br>fi<br>​<br>while :; do :; done &amp; kill -STOP $! &amp;&amp; wait $!</pre><p>Using all this chunks, the final Dockerfile has to be like this :</p><pre>FROM ubuntu:bionic<br>​<br>ENV JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre<br>ENV HADOOP_HOME /opt/hadoop<br>ENV HADOOP_CONF_DIR /opt/hadoop/etc/hadoop<br>ENV SPARK_HOME /opt/spark<br>ENV PATH=&quot;${HADOOP_HOME}/bin:${HADOOP_HOME}/sbin:${SPARK_HOME}/bin:${SPARK_HOME}/sbin:${PATH}&quot;<br>ENV HADOOP_VERSION 2.7.0<br>ENV PYSPARK_DRIVER_PYTHON=jupyter<br>ENV PYSPARK_DRIVER_PYTHON_OPTS=&#39;notebook&#39;<br>ENV PYSPARK_PYTHON=python3<br>​<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y wget nano openjdk-8-jdk ssh openssh-server<br>RUN apt update &amp;&amp; apt install -y python3 python3-pip python3-dev build-essential libssl-dev libffi-dev libpq-dev<br>​<br>COPY /confs/requirements.req /<br>RUN pip3 install -r requirements.req<br>RUN pip3 install dask[bag] --upgrade<br>RUN pip3 install --upgrade toree<br>RUN python3 -m bash_kernel.install<br>​<br>RUN wget -P /tmp/ <a href="https://archive.apache.org/dist/hadoop/common/hadoop-2.7.0/hadoop-2.7.0.tar.gz">https://archive.apache.org/dist/hadoop/common/hadoop-2.7.0/hadoop-2.7.0.tar.gz</a><br>RUN tar xvf /tmp/hadoop-2.7.0.tar.gz -C /tmp &amp;&amp; \<br>  mv /tmp/hadoop-2.7.0 /opt/hadoop<br>​<br>RUN wget -P /tmp/ <a href="http://mirror.ibcp.fr/pub/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz">http://mirror.ibcp.fr/pub/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz</a><br>RUN tar xvf /tmp/spark-2.4.4-bin-hadoop2.7.tgz -C /tmp &amp;&amp; \<br>    mv /tmp/spark-2.4.4-bin-hadoop2.7 ${SPARK_HOME}<br>​<br>RUN ssh-keygen -t rsa -P &#39;&#39; -f ~/.ssh/id_rsa &amp;&amp; \<br>  cat ~/.ssh/id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys &amp;&amp; \<br>  chmod 600 ~/.ssh/authorized_keys<br>COPY /confs/config /root/.ssh<br>RUN chmod 600 /root/.ssh/config<br>​<br>COPY /confs/*.xml /opt/hadoop/etc/hadoop/<br>COPY /confs/slaves /opt/hadoop/etc/hadoop/<br>COPY /script_files/bootstrap.sh /<br>COPY /confs/spark-defaults.conf ${SPARK_HOME}/conf<br>​<br>RUN jupyter toree install --spark_home=${SPARK_HOME}<br>RUN echo &quot;export JAVA_HOME=${JAVA_HOME}&quot; &gt;&gt; /etc/environment<br>​<br>EXPOSE 9000<br>EXPOSE 7077<br>EXPOSE 4040<br>EXPOSE 8020<br>EXPOSE 22<br>​<br>RUN mkdir lab<br>COPY notebooks/*.ipynb /root/lab/<br>COPY datasets /root/lab/datasets<br>​<br>ENTRYPOINT [&quot;/bin/bash&quot;, &quot;bootstrap.sh&quot;]</pre><p>Now we need to build our image, and to do that we simply run the following command at the same folder level as the Dockerfile :</p><pre>docker build . -t cluster-base</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZubMb8MADBxmdgnf-6SVQ.png" /></figure><p>It is very important that the image name used here (cluster-base) matches the specified image name on the docker-compose.yml file.</p><h3>Docker Compose or how to make the cluster comes to life</h3><p>Instead of launching and configuring each node independently, Docker Compose facilitates doing this by specifying the characteristics of all our nodes, and by characteristics I mean the image to use, the hostname to set, the network to be part of and anything that you can more or less write down using Docker command lines.</p><p>Bellow is the YAML file I’ve used, I will add comments to it so you can understand what it does.</p><pre>version: &quot;3.3&quot;<br># Here we will list all nodes/containers!<br>services:<br># First container will be named node-master<br>  node-master:<br># We will tell Docker to run the slaves first before running the Master Node<br>    depends_on:<br>      - node-slave1<br>      - node-slave2<br># The image to be used is the image we&#39;ve built before<br>    image: cluster-base:latest<br># It explains itself, what it the container name<br>    container_name: node-master<br># The hostname for this container<br>    hostname: node-master<br># Connecting your terminal to the stdin and stdout stream of the container so you can see<br># all the messages it outputs<br>    tty: true<br># Ports redirection to Host<br>    ports:<br>      - &quot;8088:8088&quot;<br>      - &quot;50070:50070&quot;<br>      - &quot;50030:50030&quot;<br>      - &quot;8080:8080&quot;<br>      - &quot;8042:8042&quot;<br>      - &quot;8888:8888&quot;<br># Linking this container to the following network and defining an alias to be used<br>    networks:<br>      cluster-network:<br>        aliases: <br>          - node-master<br># First Slave Node, same thing as previously seen<br>  node-slave1:<br>    image: cluster-base:latest<br>    container_name: node-slave1<br>    hostname: node-slave1<br>    tty: true<br>    ports:<br>      - &quot;7042:8042&quot;<br>    networks:<br>      cluster-network:<br>        aliases: <br>          - node-slave1<br># Second Slave Node<br>  node-slave2:<br>    image: cluster-base:latest<br>    container_name: node-slave2<br>    hostname: node-slave2<br>    tty: true<br>    ports:<br>      - &quot;9042:8042&quot;<br>    networks:<br>      cluster-network:<br>        aliases: <br>          - node-slave2<br># Defining a new network of Bridge type to be created<br>networks:<br>  cluster-network:<br>    driver: bridge<br>    ipam:<br>      driver: default</pre><p>To run the cluster and launch it, all is needed now is to run the command bellow at the same folder level as the docker-compose.yml:</p><pre>docker-compose up</pre><p>Now that your cluster is up and running you should have something like this, displayed on your shell :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVNfde9LXFFnNkinALUj-Q.png" /></figure><p>You can even access Yarn resource manager UI to see the slave nodes part of your cluster (localhost:8088/cluster/nodes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAe4i0qtMb-XKu2WmcDFmA.png" /></figure><p>And now you can access Jupyter Notebook at localhost:8888. You can use the starter notebooks and start playing around with Spark (Scala or Python) and Dask :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aa_6fIpl6lq2-AOuzWo5Pg.png" /></figure><p>For stopping your cluster use Ctrl + C and then run the command docker-compose down to completly remove the containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHJpU4-oTGUJuYEh1XqRxQ.png" /></figure><p>So, that’s it folks! I hope this post was a bit useful for you.</p><p>You can follow me on <a href="https://twitter.com/ALemaizi">Twitter</a> to be notified when new posts are published!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b75c1500ead" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/creating-your-own-micro-cluster-5b75c1500ead">Creating Your Own Micro-Cluster</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Clustering & The Curse of Dimensionality]]></title>
            <link>https://medium.com/analytics-vidhya/time-series-clustering-the-curse-of-dimensionality-c0d837f00415?source=rss-9029e676d26b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0d837f00415</guid>
            <category><![CDATA[curse-of-dimensionality]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Amine Lemaizi]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 11:50:23 GMT</pubDate>
            <atom:updated>2022-12-23T22:56:49.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuaB0nNXzAiGG5uz30D-hA.jpeg" /></figure><p>So imagine that you’ve got a bunch of time series representing the same type of observations, like retail daily sales, heartbeats of joggers or some obscure sensors. There is a big benefit for applying clustering either during data discovery or for modeling the dataset itself, this benefit is mainly linked to the understanding of existing similarities between some fractions of the dataset, like gathering together retail points-of-sale that are booming during summer vs the ones booming during Christmas time, or looking for the right explanation for why 1,000 joggers are considered as part of the same group, is there any health issue common to them or is it related to living at high altitudes for example. You’ve guessed it, there is a lot of positive outputs that can emerge from clustering time series hence the importance of doing it right by avoiding some pitfalls that can make this ineffective or absolutely erroneous.</p><p>Before going any further, let us take a couple of seconds to ask a fundamental question: What makes time series so special compared to other types of datasets ? Mainly two things, the first one is the “series” part which means each observation is linked to a sequence, a frequency of some sort, a beat, a pulse or something like that. The second thing, represented on the “time” and “chronology” part, is the order of observations, changing the order will be considered as generating a totally different time series. In the following graph, shuffling the <strong><em>sin</em></strong> signal will produce something other than a <strong><em>sin</em></strong> even if the dataset is similar (without considering the order of course) because the chronological position for each observation is very important to define our time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*o463DTUQAv_vg5Rl8tr8iA.png" /></figure><p>Something else to be mentioned, a time series is in general defined in a high dimension space. If you happen to record the daily sales of an ice-cream shop during one year, that’s a dimension with a cardinality equal to 365, so just imagine if we’re having a decade worth of data.</p><h3>The Curse of Dimensionality</h3><h4>A word or two about distances</h4><p>When we’re speaking about distances, we tend to think right away about the Euclidean distance. Just a quick reminder, the Euclidean distance is defined in an <a href="https://en.wikipedia.org/wiki/Euclidean_space">Euclidean Space</a> as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rC147ZA1DY5SDNtW7e7ujA.png" /></figure><p>Where <strong><em>a</em></strong> and <strong><em>b</em></strong> are two points in space with their respective space coordinates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCySrZR9HaosGAdS9-qe2Q.png" /></figure><p>and <em>n </em>is a strictly positive integer, meaning <em>n </em>∈ ℕ*.</p><p>The truth is that the concept of distance is a much more abstract and general one, the Euclidean distance is just one out of many existing distances. We can call a distance anything that fulfill some set of mathematical conditions: If we consider the function d operating in a set E, with d: E× E→ℝ⁺, d is called a distance if it satisfies the following conditions :</p><ul><li><strong>Symmetry</strong> : ∀ (a, b) ∈ E², d(a, b)=d(b, a)</li><li><strong>Coincidence</strong> : ∀ (a, b) ∈ E², d(a, b)=0 ⇔ a=b</li><li><strong>Triangle Inequality</strong> : ∀ (a, b, c) ∈ E³, d(a, c)≤ d(a, b)+d(b, c)</li></ul><p>So if you happen to create a function that meets this three constraints, congratulations you’ve created a distance metric!</p><p>But why am I talking about all this? How this is relevant to what I’m trying to say ? In fact my main point here is that the Euclidean distance, that we’re using instinctively, is not the only existing distance and there is a bunch of other ones like <a href="https://en.wikipedia.org/wiki/Taxicab_geometry">the Manhattan distance</a>, <a href="https://en.wikipedia.org/wiki/Cosine_similarity">the Cosine distance</a>, <a href="https://en.wikipedia.org/wiki/Chebyshev_distance">the Chebyshev distance</a>, <a href="https://en.wikipedia.org/wiki/Minkowski_distance">the Minkowski distance</a> just to name a few. And clustering algorithms are strongly based on distance measures, similar points in space means they happen to be close to each others, so changing the distance metric can change to a great extent the behavior of our clustering algorithm. In fact, this applies to a big chunk of machine learning concepts.</p><h4>High dimension &amp; the curse!</h4><p>Until now, everything is good and we’re happy with our distance metrics. The big question to ask here is, does distance behave similarly in high dimensions ? Can we trust some distance measures to discriminate, which means knowing similarities and non-similarities of the population we’re having on our dataset, in high dimension spaces ?</p><p>I won’t answer right away, but instead I will make a simple experiment. Let’s generate 500 random points, uniformly distributed, and then compute the Euclidean distances between all possible pairs (124,750 pairs), then we will plot the distribution of those distances. We will do that by increasing the dimension of our space to see what will happen exactly at high dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*WS23DvYr4G91ZIskTgCTtQ.png" /></figure><p>You can test this by yourself by using the following code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d95fbe59baf5006489697959689bcee6/href">https://medium.com/media/d95fbe59baf5006489697959689bcee6/href</a></iframe><p>We observe that at high dimensions there is a decrease of distance variance, with the extrême case of 10,000 dimensions where pairwise distances converge to a very narrow value, it’s like all points in space are in a Mexican standoff with no real winner. The fact that we loose the variance of pairwise distances means we can’t discriminate the population or find any significant similarities therefore the effort of clustering is doomed to failure.</p><p>In the context of clustering time series, a lot of people tend to use the most classical clustering algorithm namely, the <a href="https://en.wikipedia.org/wiki/K-means_clustering">K-Means clustering</a>. In its most classical form, it is based on euclidian distance and applying it to time series, like daily sales of ice-cream shops during a decade, is equivalent to use euclidean metric in high dimension which will definitely lead to the curse of dimensionality.</p><h3>What shall we do then ?</h3><p>So now that I’ve given you the bad news, don’t think you’re hopeless…I will share with you two main strategies to counter the effect of the curse of dimensionality when clustering time series.</p><h4>Reducing the space by features extraction!</h4><p>If you want to maintain the way you cluster your time series with no fancy techniques, the best approach is to reduce the space on which your time series are defined. In fact by “reducing” I mean shifting your time series to a complete different space by computing some relevant features observed on your time series like trends, means, maximum values on certain days or entropy for example (here’s a list of a non-exhaustive <a href="https://tsfresh.readthedocs.io/en/latest/text/list_of_features.html">relevant features</a> to be computed). So if we imagine that you’ll need just 10 features to describe your time series, depending on your context of course, it will always be definitely better than daily values during a decade (that’s around 3,650 features).</p><p><em>There is a very useful library you can use for computing those features called </em><a href="https://github.com/blue-yonder/tsfresh"><em>TSFRESH</em></a><em>.</em></p><h4>Changing how we measure similarities</h4><p>The second strategy is to completely change the metric, as we’ve seen it before there is many existing distance metrics and what we need on our case is to pick the metric that will manage to reduce the effect and unfortunately this is not a safe bet.</p><p>That’s been said, the best measure to use is <a href="https://en.wikipedia.org/wiki/Dynamic_time_warping">Dynamic Time Warping</a> (or DTW), even if it’s not, mathematically speaking, a <a href="https://www.sciencedirect.com/science/article/abs/pii/0167639385900585">distance metric</a>. DTW is an algorithm that measures similarities between two time series, we can use it as a measure for a <a href="https://tslearn.readthedocs.io/en/latest/auto_examples/plot_kmeans.html">K-Means clustering</a> and it is, in our context, immune to the curse of dimensionality because at its core the algorithm operates in a two dimensional space.</p><p>DTW can be a good solution to counter the curse, but it has two major problems when dealing with a dataset with too many time series. The first issue is the need to compute pairwise distances for all existing time series, which is equivalent to create an upper triangular matrix (we consider symmetrical DTW) with an all zero diagonal (a DTW of a time series to itself is zero). For that, we need to compute (m²-m)/2 DTWs (where m​ is the number of time series we have), so for 1,000 time series we have to compute 499,500 DTW values. The following graph represents the DTW distance matrix shape for 16 time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hqmf_k0GADZwzkRRbUTlkQ.png" /></figure><p>The second issue is the algorithmic performance : the DTW algorithm is a O(n²) , so for the 1,000 time series computing DTW 499,500 times can take forever!</p><p>I wish you’ll remember this article when dealing with clustering time series, and I hope it gave you a better understanding about the impact of the curse of dimensionality.</p><p>You can follow me on <a href="https://twitter.com/ALemaizi">Twitter</a> to be notified when new posts are published!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0d837f00415" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/time-series-clustering-the-curse-of-dimensionality-c0d837f00415">Time Series Clustering &amp; The Curse of Dimensionality</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking a Toy Drone to Put Artificial Intelligence on It, Part 1: The Hack!]]></title>
            <link>https://medium.com/@amine.lemaizi/hacking-a-toy-drone-to-put-artificial-intelligence-on-it-part-1-the-hack-7454e42de376?source=rss-9029e676d26b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7454e42de376</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[drones]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Amine Lemaizi]]></dc:creator>
            <pubDate>Tue, 31 Dec 2019 00:10:02 GMT</pubDate>
            <atom:updated>2022-12-23T22:58:00.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezJAlh0_LxV59ZsRVA2ytw.jpeg" /></figure><p><em>This article has been originally published on my personal </em><a href="https://lemaizi.com/blog/hacking-a-toy-drone-to-put-artificial-intelligence-on-it-part-i-the-hack/"><em>website</em></a><em>.</em></p><p>I’ve been working with some friends on an little academic project aiming to create a business model of a high-tech company related to data and artificial intelligence. The assignment itself was f’ing boring, so we found ourselves time to time just chatting and fooling around. One interesting chitchat (at least for myself) was about the capabilities that A.I. would bring to connected objects, vehicles and specifically drones, where I’ve expressed that I would love to do some experimentation with a drone if I had one within reach. Two, very lovely, friends recorded that and offered me a fpv (first person video) drone for my birthday, a Chinese toy drone to be more specific.</p><p>Now That I have a drone, it will all be fun and I will enjoy my time crafting a convolutional neural network or a real time object recognition for random applications to put this drone on steroids, the only thing I have to do now is to use its API…you said API?! I was a bit naive to believe that this toy drone (a Snaptain S5C) would have an interface to communicate with. I’ve spent a big amount of time googling various key words, looking in forums, reddit, random websites…there was no API you fool!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJtyHTb9ym4Vd_c8OzPxZQ.jpeg" /><figcaption><em>One lesson I’ve learned the hard way: don’t test your drone bladeless!</em></figcaption></figure><p>This quick conclusion saddened me A LOT…until I’ve realized something a bit interesting : to use this drone, you have to install an app on your phone, turn on the drone using a switch and then connect to a sweet <strong>non-secured</strong> Wifi hotspot, yep you’ve heard it (I mean read it) a <strong>non-secured</strong> Wifi where anyone and anything can connect to it without the need for any authentification or any security layer! Or as Michael Robinson said it, on one of the most entertaining DEFCON talks : <a href="https://youtu.be/5CzURm7OpAA?t=516">“The thing is its own flying router with DHCP enabled…AWESOME!”</a>. This is great news, the project I had on mind went from fun to exciting, hacking something to use it feels like being a caveman that will cook his own quarry for dinner.</p><p>Having a direct access to Wifi is not enough to call this a hack nor sufficient to command the drone. I need to figure out the communication protocol so I can control the drone from my computer and more importantly retrieve the video stream. For that I have a strategy based on one of the oldest trick on the book of hacking: sniffing packets! The following graph depicts what is my approach for this hack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PU7xr3iqrrRVdkzhkMPMfA.png" /></figure><p>So, I will use my smartphone (1) to communicate with the drone (3) through its official app. This communication between them is represented at (2) as a hexadecimal stream (a more convenient way to represent binary sockets). The idea is to connect to the same hotspot with a third party machine or agent (4) and listen (sniffing is the proper term) to the packets that have been exchanged between the two. Having this stream, I will try to imitate it, using my laptop this, time to communicate directly with the drone, so it will look like this representation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHOJiGDCg1AZ2FfyfcoRsQ.png" /></figure><p>Ok, now that the plan is set, I will connect from my laptop to the drone’s Wifi hotspot and do the most basic action : see what is my IP address. It seems that the IP address follows this structure 172.17.186.146, which means that I need to have a closer look at IP addresses starting with 172.17 when sniffing the packets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_NrpJWM0NPbBymH9AuyTQ.png" /></figure><p>I’ve used <a href="https://www.wireshark.org/">Wireshark</a> to have a first glance at the packets that’s been transmitted throw the hotspot, and this is what I’ve got :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPqc7akGUhYzXvgyPdVvfw.png" /></figure><p>I can see my laptop base IP address 172.17.181.146 and another one with the same basis 172.17.10.1. I&#39;m pretty sure this is the drone&#39;s IP. A lot of packets has been sent to the drone from my laptop which is not expected, I was hoping for another IP address with the same base representing my smartphone, but nothing is showing any activity related to the drone/smartphone communication, it&#39;s like the main signal is drowned in all this DNS requests and I don&#39;t have any clue on how to properly put aside what interests me. I think sniffing is not enough...and a <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">man-in-the-middle attack</a> is necessary to relay communication from the laptop to capture those packets.</p><p>Before using anything fancy, I think I will make a little change this time: instead of using my laptop to listen to the exchanged packets, I will use a third party agent installed inside the smartphone (a mobile app called <a href="https://play.google.com/store/apps/details?id=app.greyshirts.sslcapture&amp;hl=en">Packet Capture</a>) and only focus on the Snaptain’s app (the drone official app).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*QdDrm0CjM9e7qRisDVdspg.png" /></figure><p>After the app selection let’s launch it, receive the video stream and put the drone on “ON Mode” (ready-to-fly). Redoing this a couple of times will give us the chance to see if any pattern is emerging, which is the case in fact. Each time doing this, there is 5 connections made to the IP address 172.17.10.1 a.k.a the drone, four of them represents a TCP protocol on port 8888 and the one right after is a UDP protocol on port 9125.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*dq8jEzb-sALLjVMfMjU3ug.png" /></figure><p>Looking for the total “weight” of packets transmitted, the fourth one shows 22 Mb (don’t mind the Mo at the screenshot it is the french equivalent to Mb, bytes in french is “octets”) which is a value constantly increasing. I can assume that this specific connection is certainly linked to the video stream. So let us start by retrieving the video stream, and to do that I will take a closer look into the packets transmitted and received through this connection (blue is transmitted, red is received).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*vtS1MLnG42XhiNJAmZwfoQ.png" /></figure><p>As you can see, there is three phases in this packets transmission :</p><ul><li>Sending 106 bytes of data</li><li>Receiving 106 bytes of data</li><li>Open bar or streaming the video!</li></ul><p>I can emulate this by using my laptop (socket programming), then I’ll be using Wireshark to see what’s happening exactly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c5228090038f6906af550a4a511f11/href">https://medium.com/media/96c5228090038f6906af550a4a511f11/href</a></iframe><p>Wireshark shows us that we&#39;ve succeeded to connect to the drone, great!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cq1xHEM-_wrWQCYkG0usOw.png" /></figure><p>The only thing remaining now is to send the same “scavenged” data and voilà!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f25db9ab24cea706bc1044b2fb53e1c/href">https://medium.com/media/2f25db9ab24cea706bc1044b2fb53e1c/href</a></iframe><p>Uh-oh…the reception of the response is hanging and Wireshark is really showing some nasty messages …I’ve failed miserably…without really knowing why…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCq4SnZAL7CX8PQBUnfBgg.png" /></figure><p>After banging my head to multiple walls and ruthlessly googling, I’ve finally found one little phrase hinting to what I have to do (thanks to <a href="https://github.com/Hermann-SW">Hermann Stamm-Wilbrandt</a> and his repo <a href="https://github.com/Hermann-SW/wireless-control-Eachine-E52-drone">here</a> ):</p><blockquote><em>Opening a connection against stealth port with connect() hangs because no “SYN ACK” gets returned; […] sending a single (hand crafted) SYN packet (and do not deal with a response in case there is one) allows for single threaded operation of pull_video.</em></blockquote><p>Ok, this is not really a direct answer to my problem, but it gave me an eureka moment. What I need to do is replicate inch by inch the packets sent before the video stream, if I guessed it right, this is like a “handshake” or a confirmation that the drone is dealing with the right and true client…so I did just that!</p><p>The code bellow (yes it is a bit barbaric) represents the emulation of the first connection using the TCP protocol. Doing this, I&#39;ve got no reception hanging and all hexadecimals received corresponds perfectly to the ones seen during packets capturing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de65b581eb3deff565e1a967619c8ab4/href">https://medium.com/media/de65b581eb3deff565e1a967619c8ab4/href</a></iframe><p>The codecs.encode(sv.recv(106), &#39;hex&#39;) gets the first 106 bytes so we can skip it and all what follows will be written to a file with a H.264 video extension, you&#39;ll ask me &quot;how the hell do you know that this is the right format ?&quot;, and my answer is :</p><ul><li>Thanks to google, I’ve discovered that a lot of toy drones and many IP connected objects streaming videos are using this format, for a very reasonable reason that it supports signal discontinuity.</li><li>If you’ve noticed it before, the “Open bar” packet starts with this hexadecimals : 00 00 01 A1, which is a signature specefic to H.264 format.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ef6c6fa8be893e24dc6cb4fd5b1f2c0/href">https://medium.com/media/5ef6c6fa8be893e24dc6cb4fd5b1f2c0/href</a></iframe><p>Did I retrieve the video stream now ? The answer is a f’ing YES!!! I’ve got the VIDEO STREAM!!!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS1lSXkIofeo%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS1lSXkIofeo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FS1lSXkIofeo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f794fecacc248a6cc9d1af71221b968e/href">https://medium.com/media/f794fecacc248a6cc9d1af71221b968e/href</a></iframe><p>One of the two objectives has now been achieved, what remains now is sending a control signal to the drone and hope it will react to it.</p><p>The first 4 TCP connections seem to be related to protocole confirmation and video streaming, the fifth one is different in terms of the protocole used (a UDP) and the port number. With a closer look, the connection to the drone using UDP at port 9125 starts with sending empty bytes until a certain point in time where it emits an 8 bytes signal with this format : 66 80 80 7E 80 00 FE 99.</p><p>If you recall what I’ve written before, after starting the drone’s app and receiving the stream I’ve put it into “ON/ready-to-fly Mode”. I’m in a way confident that the behavior described through the packets is correlated to this series of events and that the hexadecimal signal we’re seeing here corresponds to the “ON” signal sent to the drone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*SzVyTXDWRqfDmrR8y_13vQ.png" /></figure><p>I did further examination by sending different commands, through the app, to the drone and the control packets are consistent in terms of there format. They are always 8 bytes signals, starting with 66 and finishing with 99, and the bytes in between are the ones changing so I will assume changing their values will give different navigation commands to the drone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*iJ0G529BM5T8pkyYSC6-hQ.png" /></figure><p>Let’s wake up the drone by sending what I think is the “ON/ready-to-fly” command (66 80 80 00 80 00 80 99). If the drone is receptive it will stop blinking its lights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97c20cef736cc869b058a3f5716fd406/href">https://medium.com/media/97c20cef736cc869b058a3f5716fd406/href</a></iframe><p>S#@t again…the drone seems stagnant and not receptive to my command as you can see it here…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5F258jiKigI%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5F258jiKigI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5F258jiKigI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca897a33f5ee5bed86dc88e765f61ffd/href">https://medium.com/media/ca897a33f5ee5bed86dc88e765f61ffd/href</a></iframe><p>So after rechecking the captured packets I’ve realized my mistake, the drone’s app seems to send not one and lonely command but it sends the same command over, and over and over again. It is like a buffer making sure that the drone is receiving a constant stream of live execution signals…so knowing that I’ve changed my code to reflect this by simulating a buffer with a 50 ms delay.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b8651e80e907f41ee3ec5dadd677fc/href">https://medium.com/media/e5b8651e80e907f41ee3ec5dadd677fc/href</a></iframe><p>And holy moly I’ve guessed it right, now the drone is receptive and it stops blinking! Second objective achieved!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHG7AwBoKRJA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHG7AwBoKRJA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHG7AwBoKRJA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5be44ab495ebae03cbd350a0f85b1640/href">https://medium.com/media/5be44ab495ebae03cbd350a0f85b1640/href</a></iframe><p>After achieving the two “it is a hack” criteria, I can officially declare that I’ve succeeded to hack this Chinese toy drone! Unfortunately drones for personal use are not allowed in Morocco, where I’m spending my vacation right now. So I will put aside this project until coming back to Paris…the project is not finished yet, two parts are still remaining.</p><ul><li><strong>Part 2 - Command and Conquer !</strong> : I will try to understand how control commands are functioning for this drone and create a Python API to fully control it using command lines. I also need a live stream of the video so I can use it during the machine learning phase.</li><li><strong>Part 3 - Is this Skynet ?!</strong> : The conclusion will be to convert this drone into a semi-autonomous drone doing some specific tasks using machine learning.</li></ul><p>You can follow me on <a href="https://twitter.com/ALemaizi">Twitter</a> to be notified when the next posts will be published!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7454e42de376" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>