<?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 Patrice Ferlet on Medium]]></title>
        <description><![CDATA[Stories by Patrice Ferlet on Medium]]></description>
        <link>https://medium.com/@patrice.ferlet?source=rss-63647e779dd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*piNFd7_orMK7B7HyqgKNcg.jpeg</url>
            <title>Stories by Patrice Ferlet on Medium</title>
            <link>https://medium.com/@patrice.ferlet?source=rss-63647e779dd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:32:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrice.ferlet/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[Simple and lightweight Kubernetes DevOps stack]]></title>
            <link>https://medium.com/smileinnovation/simple-and-lightweight-kubernetes-devops-stack-88ab032868fa?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/88ab032868fa</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[paas]]></category>
            <category><![CDATA[rancher]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 14:18:11 GMT</pubDate>
            <atom:updated>2020-02-07T15:45:39.428Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>We have chosen Rancher, Harbor, Gitea, and Drone on a real production Kubernetes cluster. We reduced CPU and memory usage as well as the storage, and of course carbon footprint.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yuJaY3WauFTB6GnN.jpg" /><figcaption><a href="https://pixabay.com/fr/photos/devops-affaires-3155972/">https://pixabay.com/fr/photos/devops-affaires-3155972/</a></figcaption></figure><p>Kubernetes is now the most used Container platform. It is complete, effective, productive and offers a lot of control. Furthermore, while Kubernetes is a “low-level platform”, it is possible to append tools like service mesh, ingress controllers, plugins to add more objects (e.g. Velero add Backup object), storage classes, and many more. And Kubernetes is an orchestrator, so you can manage “Deployment” objects to control application version, service links, and replications. Of course, you can control that deployment with a Continuous Delivery tool.</p><p>So, Kubernetes is a perfect platform for DevOps.</p><p>Nowadays, DevOps is strongly oriented over CI/CD (Continuous Integration/Delivery) and there is plenty of solutions to work. To be honest, DevOps generally work with:</p><ul><li>GitLab or GitHub for source control</li><li>Jenkins and/or GitLab runners for integration and/or deployment</li></ul><p>And there are several reasons for those solutions to be so widespread. They are complete and very well documented.</p><blockquote>But… there are flip sides: weight, complexity, resources</blockquote><p>Gitlab takes a lot of memory, and you probably don’t need the full functionalities and add-ons that are included, sometimes you only want to manage sources (with git), issues, pull requests, and so without the scrum board, reporting, or complex right management.</p><p>Gitlab runners are very well designed but can be a bit tricky to use.</p><p>Jenkins is also a bit heavy and offers many ways to build and deploy applications on several platforms, but I ask the question: do you need all the options?</p><p>A bit more of context — As a member of the AI4EU project consortium, with the responsibility of system integrator, we had to set up an environment that would allow this project to quickly evolve, to onboard OSS software and custom development from many 3rd parties, while keeping a standard process for development lifecycle and deployment</p><p>So, we need:</p><ul><li>to store applications sources in a Git control server</li><li>be able to build the image, store the image, launch tests and deploy the application when a pull-request is created (testing)</li><li>be able to be deployed when a merge is made from PR (staging)</li><li>be able to be deployed when a tag is released (production)</li><li>to store Docker images somewhere and to have control about vulnerability checks, storage and access rights on repositories</li></ul><p>Spoiler alert! That’s the stack we decided to use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TfzVBOziBI3if6k-ny-PQ.png" /><figcaption>General installation</figcaption></figure><p>The stack is composed by:</p><ul><li>Rancher to manage application catalog (Helm charts), monitoring, project access rights, and Kubernetes nodes</li><li>Gitea to manage the sources of applications and the Helm charts versioning</li><li>Harbor to store Docker images, check vulnerabilities, storage controls</li><li>Drone to build the image, launch tests, and deploy on different environments</li></ul><p>We needed to create two Drone plugins, but we will see that point following the article. It’s time to give you some precision.</p><h3>Rancher — it’s more than a UI</h3><p>Rancher is mainly used because it eases the installation and it proposes a nice view. That’s right, it is nice for those topics.</p><p>But Rancher is more than a simple UI, it proposes a very efficient monitoring installation, and it can manage <em>Helm charts</em> catalog with the option to use a questions.yaml file that yields forms to install applications.</p><p>Helm is a fantastic solution to create application templates and to manage the deployments with “variable” parameters. This is one of the most used solutions with Kubernetes, and there is a very consequent “official” catalog to deploy in one command some services like <em>Nginx-Controller</em>, <em>NFS-provisioner</em>, <em>registry</em>, <em>Magento</em>, <em>Drupal</em>… and it’s simple to access other repositories (custom or official one).</p><p><strong>That’s not a gadget. </strong>Helm is very well designed to build an application installation stack, Rancher adds a real user experience with that form generator, and we finally have more readability on what to tweak.</p><p>So, the “catalog” is graphically displayed, we can see information and form to drive the launch of the application.</p><p>As the catalog can be served from a “charts museum” or a simple Git repository, Rancher offers a way to declare custom helm charts repositories from the interface.</p><p>Rancher runs in a simple Docker container, and it has got a real advantage:</p><blockquote>You can import already installed Kubernetes clusters, and manage several cluster in one place! And, Rancher is not mandatory to leave the cluster to work alone. If Rancher crashes, if you want to abandon, your cluster will live anyway.</blockquote><p>Rancher is very impressive, adaptable, useful, complete, easy to use.</p><h3>Then, let’s talk about Harbor Docker Registry</h3><p>For years, we were using registry , proposed by Docker Inc, that does the job. Yes, it is simple and it doesn’t consume CPU or memory.</p><p>It works as expected, but it lakes of options. For example, it’s complicated to make it accessible outside the local environment, it has no good authentication and right separation, and it has no vulnerability check, storage cleanup automation…</p><p>That’s the only tool to change that will grow up the memory and CPU usage. No panic, the solution we propose is not so greedy.</p><p>After several tries, using GitLab and Nexus, for example, we gave a chance to “Go Harbor”.</p><p><a href="https://goharbor.io/">Harbor</a></p><p><em>Harbor</em> is very exciting. It is free, open-source, and provides absolutely everything we need:</p><ul><li>Graphical Web interface (one more time, as for Rancher, it is not mandatory but it helps a lot to manage the registry)</li><li>Docker registry (of course)</li><li>Authentication and Authorization on “projects” level</li><li>Certificate management + daemon to install the certificate on Kubernetes nodes</li><li>Image signature (notary server)</li><li>Helm chart museum</li><li>Vulnerability checks on images with an optional tweak to refuse to deploy that images</li><li>Replication, storage cleanup, and many other options…</li></ul><p>It also proposes an API to get information. For example, on our pipelines, we can push images on the registry, then call API to have vulnerability check results… Awesome! 💚</p><p>And, you know what? Rancher proposes a Harbor installation from the default catalog! Installation took 2 minutes.</p><p>In our environment, we didn’t need Chart Museum because we use a git repository to manage our helm charts.</p><h3>Git repository service</h3><p>GitLab is very complete, proposes a long list of tools. It also proposes CI options like using “runners”. And it can also manage the Kubernetes cluster, which means that GitLab can be used as a PaaS. Right…</p><p>But, what we need is to be able to choose a CI/CD tool. If you prefer Jenkins, that means that you will probably not use the GitLab option. Then, Rancher is already there to manage your clusters, so GitLab will be not used as PaaS…</p><p>And, unfortunately, even if we love GitLab, it is huge. It consumes a lot of memory and CPU, it is not that easy to scale… GitLab is very good if it is your main source control system deployed on a dedicated server. But here, we want to reduce the impact on the planet 🌍</p><p>So, is there a git server that offers everything we need, like issue tracker, webhooks, several authentication systems, LFS management…</p><p>Yes, there is one (at least), named Gitea!</p><p><a href="https://gitea.io/">Gitea</a></p><p>Gitea is a fork of an initial project named “Gogs” — it is developed in Go (like Rancher, Docker, Drone, OKD/Openshift…) and benefits to the reduced CPU and memory impact usage allowed by that language.</p><p>It is fast, lightweight, and very closed to the GitHub interface. Gitea is compatible with a lot of CI/CD solutions by using webhooks. That’s a chance, Drone.io can contact Gitea and that’s what we will use.</p><h3>And then, CI/CD with Drone</h3><p>We love Jenkins, really we love it. Nowadays, this is probably the best CI service that exists. It is not restrictive, proposes pipeline integration in a lot of cluster managers, and we appreciate the “pipeline syntax” language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGATVjReN4a1-KpWMCRDAQ.png" /><figcaption>A finalized Docker image build and deployment on Rancher with Drone</figcaption></figure><p>But, we have discussed a lot about the usage of Jenkins and about what we “really” need. That’s a bit philosophic, but let’s take a second to think about that:</p><blockquote>You’re using pipeline syntax, jobs and so on… because Jenkins proposes those tools, and because “common”. OK… but if it didn’t exist, how would you like to launch tests and deployments inside Kubernetes?</blockquote><p>Some of you will answer “actually, I would like what Jenkins propose”. We respect that.</p><p>Others will answer “I love Travis or GitLab runners, I describe pipelines in YAML format, and that’s all.” And now, we can propose other solutions.</p><p>So, you’ve got the choice, deploy Jenkins that is a bit huge in Memory (Java is not known to conserve memory 😜 ), or you take a look at “alternatives”. Of course, alternatives should be <strong>sustainable.</strong></p><p>In the CI/CD universe, one tool emerges:</p><p><a href="https://drone.io/">Drone CI - Automate Software Testing and Delivery</a></p><p>Drone is <strong><em>ideal </em></strong>when you’re working with containers.</p><p>It uses a simple YAML syntax in a file that is default named .drone.yml — inside that file, you describe steps that can be triggered with several event types (merge, pull-request, tag…)</p><p>Drone proposes a lot of plugins, for example, you can build images, deploy on Kubernetes, send a message in Slack, contact servers in SSH… And you can use any Docker image to launch commands. Let’s take a look at plugins:</p><p><a href="http://plugins.drone.io/">Plugins</a></p><p>For example, to launch Python tests with “nose”, you don’t need a special plugin:</p><pre>kind: pipeline</pre><pre>steps:<br>- name: launch-tests<br>  image: python:3-alpine<br>  commands:<br>  - pip install nose<br>  - nose -v</pre><p>About plugins, that’s very easy to create. You only need to build your image that launches a default command. To get parameters, <em>Drone</em> will simply give each one in an environment variable named PLUGIN_&lt;NAME&gt; — for example:</p><pre>- name: my-plugin-test<br>  image: your/image/here<br>  settings:<br>    foo: bar</pre><p>There, in my image, I will have an environment variable named PLUGIN_FOO that contains the value bar . So, let’s think about that, you will be able to create plugins in any language like Bash, Python, Go, Javascript…</p><p>That’s how we provided 2 plugins that we needed: a plugin to use “source to image” (<a href="https://github.com/openshift/source-to-image">https://github.com/openshift/source-to-image</a>) and another one to contact Rancher API (to change image version in answers, that deploys the image we’ve just built, for example)</p><p>That one is made in Bash:</p><p><a href="https://github.com/metal3d/drone-plugin-sti">metal3d/drone-plugin-sti</a></p><p>And this one is built with Python:</p><p><a href="https://github.com/metal3d/drone-plugin-rancher">metal3d/drone-plugin-rancher</a></p><p><em>Drone</em> can launch image using “docker in docker”, and since several months now it can launch the steps inside Kubernetes (in real Pods)</p><p><em>Drone</em> is compatible with a lot of Git servers, like GitHub, GitLab, BitBucket… and of course Gitea!</p><h3>More details</h3><p>Finally, the following diagram gives a more detailed point of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98mgc2nj-DYBpPFxXhqDiw.png" /><figcaption>Detailed diagram of the full CI/CD stack</figcaption></figure><p>Note that even if the previous diagram shows “Kubernetes” as a separate block, Harbor, Drone, and Gitea can (and are) deployed inside Kubernetes. You can see the Dev/Ops parts.</p><h3>What to say to conclude?</h3><p>It’s not a problem to use Jenkins, Gitlab, Github, other Docker registries (like the Docker hub). Actually, on our stack, it’s possible to remove some parts to replace them with others. And it’s possible to use several tools in parallel as well.</p><p>The choices we made are driven by the necessity of simplicity and ease of control. We prefer to use progressive enhancement instead of searching to simplify something complex from the beginning.</p><p>That stack is used in a production environment with a large platform (more than 100 Pods across 5 environments like production, staging, and testing…) for 10 months and we don’t need to change anything at this time.</p><h3>That’s all folks!</h3><p>Did you enjoy it? If so don’t hesitate to 👏 our article or <a href="https://mailchi.mp/c414f1508567/techwatch?source=post_page---------------------------">subscribe to our Innovation watch newsletter</a>! You can follow Smile on <a href="https://www.facebook.com/smileopensource?source=post_page---------------------------">Facebook</a>, <a href="https://www.twitter.com/GroupeSmile?source=post_page---------------------------">Twitter</a> &amp; <a href="http://www.youtube.com/user/SmileOpenSource?source=post_page---------------------------">Youtube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ab032868fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/simple-and-lightweight-kubernetes-devops-stack-88ab032868fa">Simple and lightweight Kubernetes DevOps stack</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training neural network with image sequence, an example with video as input]]></title>
            <link>https://medium.com/smileinnovation/training-neural-network-with-image-sequence-an-example-with-video-as-input-c3407f7a0b0f?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3407f7a0b0f</guid>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-recognition]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 11:08:44 GMT</pubDate>
            <atom:updated>2019-12-05T15:43:51.831Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Training a neural network with an image sequence — example with a video as input</h3><h4>How can we classify actions that happen on video? How to use Time Distributed layers with image sequence? How to manage the input shapes?</h4><p>Last time, we explain how works Time Distributed layers in Keras and we introduced the usage of <em>transfer learning</em> with that kind of neural network. We can prepare a little network to apply what we learned.</p><p>If you didn’t read our last article, you may do it now:</p><p><a href="https://medium.com/smileinnovation/how-to-work-with-time-distributed-data-in-a-neural-network-b8b39aa4ce00">How to work with Time Distributed data in a neural network</a></p><h3>What could we do?</h3><p>Discover an “action” in videos can be very interesting — let’s imagine the possibilities: detecting someone in danger, a characteristic movement in space to detect asteroids, meteorologic events from satellite images, sign language, and many more.</p><p>Detecting an action is possible by analyzing a series of images (that we name “frames”) that are taken in time. The Time Distributed layer provided by Keras helps a lot to make it easy to try. Our previous article explained how that works.</p><p>Let’s remind the “Time Distributed layer” concept, here with a ConvNet :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0dNoo5Y8AnUoXMSFLWpIyA.gif" /><figcaption>Time Distributed ConvNet concept</figcaption></figure><p>Now let’s practice 🏄.</p><h3>Get Data then practice</h3><blockquote>In the earlier article, I got several comments of people wondering how to send the “sequence” to the model, as Keras only offers an Image Data Generator that flows “one” image batches. The answer is, we need to create our generator that can produce batches of <em>N</em> frames.</blockquote><p>For this example, I will use the HMDB data set that provides several videos classified per action. It’s free to download and use.</p><p><a href="http://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/">HMDB: a large human motion database</a></p><p>This data set provides several .rar files named with the action that happens in the video.</p><p>The videos are short and with good resolution, enough to play with machine learning.</p><h3>The Data generator</h3><p>Usually, if you’re using Keras, you like to use ImageDataGenerator that will “flow” images from classified directories. That’s very easy to use and you can quickly make data augmentation (image manipulation to have more train samples). That’s OK for “single” image recognition, but not for our work.</p><blockquote>Why?</blockquote><p>The image generator yields <em>(N, W, H, C) </em>data, where <em>N</em> is the batch size, <em>W</em> and <em>H</em> are width and height, and <em>C</em> is the number of channels (3 for RGB, 1 for grayscaled images).</p><p>But we need to send a <strong>sequence</strong>, we need to send <strong>several frames</strong>. The needed shape is <em>(N, F, W, H, C) — </em>where <em>F</em> is the number of frames for our sequence. For example, if we train a sequence of 5 images that are RBG and with 112x112 size, the shape should be <em>(N, 5, 112, 112, 3)</em>. See?</p><p>The image data generator from Keras cannot produce such a format.</p><p>The second thing to manage is that each video hasn’t got the same number of frames. If the video is 5 seconds long and encoded with 24 frames per second, so there are 5 x 24 = 120 images for the entire video. But the other videos can be 10 seconds long, or 2 seconds… 😱</p><blockquote>So, what can we do?</blockquote><p>The first method is to get 5 first images from 0, then from 1, and so on…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MkBXlCI_pStE9018nGjoPA.gif" /><figcaption>Sliding frame sample</figcaption></figure><p>That’s only possible if you’re certain that the “action” you want to predict happens in those 5 frames. But that’s rarely the case. Each video dataset I used has got a little (or big) time at the beginning and the end of the video where “no action” happens. So, should we ask the generator to edit the entire set of videos to remove those parts? Waste of time, isn’t it?</p><p>The second possibility is to pick 5 distributed images from the entire video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nOit3fe_bfi2H83m5s9vDw.gif" /><figcaption>Picking frames from the entire video</figcaption></figure><p>It’s more efficient because<strong> if the first or last frames of the video have got no action, I’m sure to avoid them</strong>. The second benefit is that I now have <strong>the entire movement</strong> in the sequence.</p><p>The only thing to do is to prepare a custom Generator (that extends Sequence) that can:</p><ul><li>read the video (let’s use OpenCV)</li><li>pick N frames</li><li>return batches</li></ul><p>OK, go, I give you a couple of minutes to create it…</p><blockquote><em>Just kidding — I give you mine! 😋</em></blockquote><p>My generator can extract some frames, resize them, create a batch… It respects what Keras needs to “fit” the model for training time. It also creates validation data by splitting the input data set.</p><p>It uses OpenCV to capture video from files. And since we don’t need to train with the entire frameset, it knows how to extract a portion of frames from the video.</p><p>The VideoFrameGenerator I created can be installed via pip command:</p><pre>pip install keras-video-generators</pre><p><a href="https://pypi.org/project/keras-video-generators/">keras-video-generators</a></p><p>You can check sources on my Github page:</p><p><a href="https://github.com/metal3d/keras-video-generators">metal3d/keras-video-generators</a></p><p>My video frame generator can take ImageDataGenerator to produce data augmented frameset from the input videos.<br>You can say I’m nice, say it! 😜</p><p>Truly, there are 3 different generators included. But for now, let’s stick with the simple keras_video.VideoFrameGenerator which is very easy to use.</p><p>Finally, it can also keep the not-augmented original frames in a cache, and it tries to pick frames by avoiding the firsts ones to be sure that “something happens” in frames.</p><p>⚠️ About memory, if you’ve got a huge data set, so leave use_frame_cache to False</p><p>About the frame cache, it’s populated when you run the first epoch of training. Then, when the generator has proceeded the entire video, it will pick frames from memory instead of reading the video file again. OK, that’s sufficient to work I presume.</p><h3>Use the Video generator 🎬</h3><p>ℹ️ Be sure you’ve installed keras-video-generators package.</p><p>Let’s create the dataset from the HMDB database, with only 3 classes from the provided <em>rar</em> files:</p><ul><li>golf</li><li>dribble</li><li>kicking ball</li></ul><blockquote>Why only 3 classes?</blockquote><p>Because there are not enough videos to get good accuracy, and because we are only testing the idea. If the training is very long, and you’ll get bad results, you will be disappointed and probably you will hate me 😇 — so let’s stick with 3 classes, please.</p><p>On my computer, I created a directory named “videos” with 3 sub-directories named with class names.</p><p>I can now try my generator included in keras_generator package:</p><pre>import os<br>import glob<br>import keras</pre><pre>from keras_video import VideoFrameGenerator</pre><pre># use sub directories names as classes<br>classes = [i.split(os.path.sep)[1] for i in glob.glob(&#39;videos/*&#39;)]<br>classes.sort()</pre><pre># some global params<br>SIZE = (112, 112)<br>CHANNELS = 3<br>NBFRAME = 5<br>BS = 8</pre><pre># pattern to get videos and classes<br>glob_pattern=&#39;videos/{classname}/*.avi&#39;</pre><pre># for data augmentation<br>data_aug = keras.preprocessing.image.ImageDataGenerator(<br>    zoom_range=.1,<br>    horizontal_flip=True,<br>    rotation_range=8,<br>    width_shift_range=.2,<br>    height_shift_range=.2)</pre><pre># Create video frame generator<br>train = VideoFrameGenerator(<br>    classes=classes, <br>    glob_pattern=glob_pattern,<br>    nb_frames=NBFRAME,<br>    split=.33, <br>    shuffle=True,<br>    batch_size=BS,<br>    target_shape=SIZE,<br>    nb_channel=CHANNELS,<br>    transformation=data_aug,<br>    use_frame_cache=True)</pre><p>As you can see:</p><ul><li>the generator can make data augmentation</li><li>it creates validation dataset — here 33% of videos sampled from the dataset</li><li>it can use a “frame cache” that you <strong>must</strong> deactivate if you’ve got not huge RAM size (I’ve got 32 Go RAM, the frame cache took 16 Go for some tests…)</li></ul><p>To get the validation data:</p><pre>valid = train.get_validation_generator()</pre><p>After that, we can see something like this:</p><pre>get 3 classes for 255 files for train﻿﻿﻿<br>get 3 classes for 123 files for validation</pre><p>train and valid generators can now generate frame sequences. Here, I use 5 frames with batch size to 8. That means the generator produces 8 sequences of 5 frames picked from videos.</p><p>Here are samples from train generator — you can use:</p><pre>import keras_video.utils<br>keras_video.utils.show_sample(train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vstp_yyHEIWuFTyVLE6LyQ.png" /></figure><p>Well, it’s now time to build the network!</p><h3>Create the neural network</h3><p>We’ve got several ways to build the model. We can use a well-known model that we inject in time distributed layer, or we can build our own.</p><p>To have more understanding of how that works, I will show you how to make everything from scratch. Then how to use a standard model as input.</p><h4>With custom ConvNet</h4><p>Each input image of the sequence must pass to a convolutional network. The goal is to train that model for <strong>each</strong> frame and then decide the class to infer.</p><p>The concept is more or less :</p><ul><li>A <em>ConvNet</em> is created and <em>Time distributed</em> to detect “features”</li><li>The <em>Time distributed </em>output is injected to <em>GRU</em> or <em>LSTM</em> to treat “time series”</li><li>A <em>DenseNet</em> is then applied to take the decision, to “classify”</li></ul><p>It’s interesting to have that concept in mind:</p><blockquote>The ConvNet gets “features” in time, DenseNet decides .</blockquote><p>So, we need to create that <em>ConvNet</em>. I recommend creating a function that returns the model. Here, I’m using a simple model. I made several convolutions with batch normalization.</p><pre>from keras.layers import Conv2D, BatchNormalization, \<br>    MaxPool2D, GlobalMaxPool2D</pre><pre>def build_convnet(shape=(112, 112, 3)):<br>    momentum = .9<br>    model = keras.Sequential()<br>    model.add(Conv2D(64, (3,3), input_shape=shape,<br>        padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(Conv2D(64, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(BatchNormalization(momentum=momentum))<br>    <br>    model.add(MaxPool2D())<br>    <br>    model.add(Conv2D(128, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(Conv2D(128, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(BatchNormalization(momentum=momentum))<br>    <br>    model.add(MaxPool2D())<br>    <br>    model.add(Conv2D(256, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(Conv2D(256, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(BatchNormalization(momentum=momentum))<br>    <br>    model.add(MaxPool2D())<br>    <br>    model.add(Conv2D(512, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(Conv2D(512, (3,3), padding=&#39;same&#39;, activation=&#39;relu&#39;))<br>    model.add(BatchNormalization(momentum=momentum))<br>    <br>    # flatten...<br>    model.add(GlobalMaxPool2D())<br>    return model</pre><p>This simple model is enough to make feature detection. As you can see, the last layer produces one dimension for output, you can also use Flatten but GlobalMaxPool2D will reduce the number of outputs (getting only maximum values from the last convolution).</p><p>OK, it’s now time to build the time distributed model. I was using <em>LSTM</em> that is very efficient, but I finally use <em>GRU</em> that is conceptually the same but using less memory, but the cost is that it is less efficient. But one more time, we’re testing…</p><pre>from keras.layers import TimeDistributed, GRU, Dense, Dropout</pre><pre>def action_model(shape=(5, 112, 112, 3), nbout=3):<br>    # Create our convnet with (112, 112, 3) input shape<br>    convnet = build_convnet(shape[1:])<br>    <br>    # then create our final model<br>    model = keras.Sequential()</pre><pre>    # add the convnet with (5, 112, 112, 3) shape<br>    model.add(TimeDistributed(convnet, input_shape=shape))</pre><pre>    # here, you can also use GRU or LSTM<br>    model.add(GRU(64))</pre><pre>    # and finally, we make a decision network<br>    model.add(Dense(1024, activation=&#39;relu&#39;))<br>    model.add(Dropout(.5))<br>    model.add(Dense(512, activation=&#39;relu&#39;))<br>    model.add(Dropout(.5))<br>    model.add(Dense(128, activation=&#39;relu&#39;))<br>    model.add(Dropout(.5))<br>    model.add(Dense(64, activation=&#39;relu&#39;))<br>    model.add(Dense(nbout, activation=&#39;softmax&#39;))<br>    return model</pre><p>The action model builds the <em>ConvNet</em> first with only the <em>(112, 112, 3)</em> shape ( shape[1:]removes the “5” dimension index) — then it injects it in the TimeDistributed layer. This layer needs the full shape <em>(5, 112, 112, 3)</em> as input. That means that the “model” input wants 5 images of 112x112 with 3 channels (RGB).</p><p>Because the dataset is not very large, I recommend using Dropout to avoid overfitting (it will happen anyway… but at least we reduce the problem)</p><p>Let’s create the model:</p><pre>INSHAPE=(NBFRAME,) + SIZE + (CHANNELS,) # (5, 112, 112, 3)<br>model = action_model(INSHAPE, len(classes))<br>optimizer = keras.optimizers.Adam(0.001)<br>model.compile(<br>    optimizer,<br>    &#39;categorical_crossentropy&#39;,<br>    metrics=[&#39;acc&#39;]<br>)</pre><p>I tried several optimizers such as <em>SGD</em> or <em>AdaDelta</em>. Adam seems to give a better train curve.</p><blockquote>There we are. We can train!</blockquote><p>OK, just to resume:</p><ul><li>we’ve got train and valid generators</li><li>validators respect the Sequence class, so we can use them with fit_generator method from Keras</li><li>we’ve got a model that is time distributed</li></ul><p>So now, we will fit the generator:</p><pre>EPOCHS=50</pre><pre># create a &quot;chkp&quot; directory before to run that<br># because ModelCheckpoint will write models inside</pre><pre>callbacks = [<br>    keras.callbacks.ReduceLROnPlateau(verbose=1),<br>    keras.callbacks.ModelCheckpoint(<br>        &#39;chkp/weights.{epoch:02d}-{val_loss:.2f}.hdf5&#39;,<br>        verbose=1),<br>]</pre><pre>model.fit_generator(<br>    train,<br>    validation_data=valid,<br>    verbose=1,<br>    epochs=EPOCHS,<br>    callbacks=callbacks<br>)</pre><p>🤓 On my 1060Ti with 3Go RAM (+32Go on computer) — it takes 20 minutes to train the model.</p><p>I made also a callback that produces graphs to check how the model evolves. Let’s take a look (and keep calm!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Fqhl0kBpcBhHq_Sn4ccUNw.png" /></figure><p>Accuracy seems to… grow, it’s not very “clean” but that seems to work… Let’s take a look at “loss” now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*swETTCX8NX8KKrknAjqmcA.png" /></figure><p>😶 Oh my… god… <strong>what happens? </strong>The training loss seems to be OK but what’s the problem with validation loss?</p><p>Well, that’s a well-known problem… Those are the cause:</p><ul><li>I’ve got not enough data for validation</li><li>I’ve got not enough data to train, so the model may overfit</li><li>The model is probably not good enough 😡</li></ul><blockquote>But… that’s finally not so bad.</blockquote><p>Check twice, the loss is going down 📉, accuracy for validation increases 📈just like train accuracy. Keep in mind we’re testing for now. So, well yeah, the model is not so bad after all.<br>OK, so let’s make some checks.</p><p>I kept some videos outside the training data set to make some tests. Here are some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ET65reZC3ULROZ-DXI4mWQ.png" /><figcaption>Golfing: checked</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhB2QcovJT55qNex475iyg.png" /><figcaption>Kicking ball: checked</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnDnEfmY5hdODrQNgUQEOQ.png" /><figcaption>Dribbling: checked</figcaption></figure><p>Not that bad, don’t you think?</p><h4>Now, let’s use a standard model</h4><p>We built our <em>ConvNet</em>, that’s fine. But what about using a well-known model, and why not a “pre-trained” model?</p><p>OK, let’s use… <em>MobileNet</em>. It is quick and well trained.</p><p>Our <em>GRU</em> model (or <em>LSTM</em>) needs one dimension, but if you get <em>MobileNetV2</em> without “top layers” (that is the category outputs, we don’t need them) so you’ll have a “Convolution” layer. We need to add one layer to have the one dimension shape compatible with <em>GRU</em>.</p><p>Also, <em>MobileNet</em> is <strong>not</strong> initially meant to detect “actions”, but only to make image recognition. So, if you tweak the entire layers as not “trainable”, you will not have accuracy improvements or “loss ” enhancement. For example, I make the last 9 layers trainable. You can try with 6 or 12 for as well.</p><p>That’s the function to try it:</p><pre>def build_mobilenet(shape=(224, 224, 3), nbout=3):<br>    model = keras.applications.mobilenet.MobileNet(<br>        include_top=False,<br>        input_shape=shape,<br>        weights=&#39;imagenet&#39;)</pre><pre>    # Keep 9 layers to train﻿﻿<br>    trainable = 9<br>    for layer in model.layers[:-trainable]:<br>        layer.trainable = False<br>    for layer in model.layers[-trainable:]:<br>        layer.trainable = True</pre><pre>    output = keras.GlobalMaxPool2D()</pre><pre>    return keras.Sequential([model, output])</pre><p>Because we’re using a pre-trained model, we need to use the required <em>(224, 224, 3)</em> shape.</p><p>ℹ️ If you want to use a non-trained model (setting theweights parameter to None ) so you will change shape. But you will need to leave all the layers to be “trainable”.<br>⚠️ If you already have an opened notebook where you trained the previous model, please kill the kernel first.</p><p>So, let’s change our parameters:</p><pre># Set size to 224, 224<br>SIZE = (224, 224)<br>CHANNELS = 3<br>NBFRAME = 5<br>BS = 8</pre><p>And for our function that builds the action model, now use build_mobilenet :</p><pre>def action_model(shape=(5, 112, 112, 3), nbout=3):<br>    # Create our convnet with (112, 112, 3) input shape<br>    convnet = build_mobilenet(shape[1:])<br>    <br>    # then create our final model<br>    model = keras.Sequential()<br>    # ...</pre><p>And create the model with new parameters — note that after several tests, <em>SGD</em> gave me better results:</p><pre>INSHAPE=(NBFRAME,) + SIZE + (CHANNELS,) # (5, 224, 224, 3)<br>model = action_model(INSHAPE, len(classes))<br>optimizer = keras.optimizers.SGD()<br>model.compile(<br>    optimizer,<br>    &#39;categorical_crossentropy&#39;,<br>    metrics=[&#39;acc&#39;]<br>)</pre><p>Then, launch the training as usual.<br>This gives me the following training curves on my computer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iDkO5ti6NGDnG7CoscIkQ.png" /></figure><p>Ditto, validation loss is not great, but good enough for experimentation.<br>Then, you can now try to pick video frames, retry, and see that the results are correct as for our custom <em>ConvNet</em>.</p><h3>Others Generators approach</h3><p>The generator that we used for that article is adequate to train a model for testing purposes. But, if you want to go better in accuracy, there is an even better generator to use (from the package I provided before).</p><p>Actually, the showcased generator picks frames for the entire file, whatever the length of the video.</p><p>Instead of taking frames from zero to end, we can define the “time of movement” and get N frames in that time, and this, following the FPS. Then glides the cursor to get more and more samples. In the below animation, that’s what you can do for a movement that is 1 seconds long, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sYp6XY04hwqIuFpfcnPu6Q.gif" /><figcaption>A more efficient video frame generator</figcaption></figure><p>This is what does the keras_video.SlidingFrameGenerator. You can try it! It should give you more samples 👍 — because we can get shifted frames. And if you are sure about the movement time, you can set sequence_time value in seconds to force sequence to be fixed to that timeframe.</p><h3>Summing-up</h3><p>Time Distributed layer can be a bit “confusing” — I had uncertainty about it for a while. For example, I was wrong by thinking that the “input network” is duplicated for each frame. I spent a long time before I realized that it uses the same network for each input image.</p><p>The real challenge is to get a large enough data set of videos to make good training. Then to find the right <em>ConvNet</em> to use as input. Sometimes, it’s nice to use <em>VGG</em>, <em>MobileNet</em> (V1 or V2) — for some other cases a “basic” <em>ConvNet</em> was very efficient contrasted to others.</p><p>Pre-trained models for image recognition are finally not so “good”. After a few experimentations, I infer (😆) that a simple <em>ConvNet</em> is enough. The main reason is that we finally don’t want to have accurate recognition, but a good accuracy on frames variation.</p><p>I’m now trying to implement the following article technique to use time distributed frames + optical flow:</p><p><a href="https://arxiv.org/abs/1711.04161">[1711.04161] End-to-end Video-level Representation Learning for Action Recognition</a></p><p>I will probably present the results in the next article. The main idea is to use OpenCV to make absolute differences or with Farneback OpticalFlow. I’ve already built the extended generator (included in the keras-video-generators package), I now need to make the model training process to work.</p><p>Not so bad for a first try? Please, don’t hesitate to comment and challenge my assumptions here, always glad to exchange about the topic.</p><p>Did you enjoy it? If so don’t hesitate to 👏 our article or <a href="https://mailchi.mp/c414f1508567/techwatch?source=post_page---------------------------">subscribe to our Innovation watch newsletter</a>! You can follow Smile on <a href="https://www.facebook.com/smileopensource?source=post_page---------------------------">Facebook</a>, <a href="https://www.twitter.com/GroupeSmile?source=post_page---------------------------">Twitter</a> &amp; <a href="http://www.youtube.com/user/SmileOpenSource?source=post_page---------------------------">Youtube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3407f7a0b0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/training-neural-network-with-image-sequence-an-example-with-video-as-input-c3407f7a0b0f">Training neural network with image sequence, an example with video as input</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to work with Time Distributed data in a neural network]]></title>
            <link>https://medium.com/smileinnovation/how-to-work-with-time-distributed-data-in-a-neural-network-b8b39aa4ce00?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b39aa4ce00</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[image-recognition]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Tue, 23 Jul 2019 13:36:28 GMT</pubDate>
            <atom:updated>2019-11-26T11:30:55.050Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>And how to use it for videos input, movements detection, gestures recognition…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cuEyJGmcTiaTHxkZ" /><figcaption>Photo by <a href="https://unsplash.com/@dmjdenise?utm_source=medium&amp;utm_medium=referral">Denise Jans</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>⚠ <strong>Important note</strong>: There is an error in explanation I give in the article. I often say that weights are shared in each distributed branche (I said that each models in Time Distributed layers are the same). That’s <strong>wrong</strong>, I badly explained. What I mean is that weights are <strong>trained in the same backward pass</strong> and not separately (because there is only one layer applied to each inputs). That means that if you want to detect a cat that is jumping, the model will not try to “detect a cat in each frame”, but it will try to detect a jumping cat by analyzing the “sequence”. <br>I also said that each input has got a “branch”, but actually it’s the same layer that is applied to inputs one after the other. Then the weights are tweaked. Keep that in mind while you’re reading this article.<br>EDIT: I fixed many part of the article.</blockquote><p>In Machine Learning, you can now predict values on complex data by using Neural Networks. And for the majority of them, you will send one or several inputs to be analysed. Sometimes, these values are chronological. For example stock prices in time, video frames, or human-size at a certain age in its life. For this kind of data, we already have some nice layers to treat data in the time range, for example, LSTM. But what if you need to adapt each input before or after this layer? This is where Time Distributed layer can give a hand. Keras proposes this one, and we will first try to understand how to use it. Then, in the next article, we will try to use it with a movie as input to detect actions. Now, let’s check their use.</p><h4>What’s the problem to solve?</h4><p>If you already worked with Convolution Neural Networks (C-NN), you’ve probably created models that take only <em>one image</em> to be <em>classified</em>.</p><p>But what if you need to present several images that are chronologically ordered to detect movements, actions, directions…? What we need is to be able to inject a sequence as input, and to make predictions of what that sequence is showing.</p><p>Hopefully, Keras (and other frameworks of course) provides objects that can manage that kind of data.</p><p>🔔 This is named “Time Distributed” layer.</p><p>With this short introduction, you probably don’t realize why we use it. You need to have more explanation about what is a Time Distributed layer, and which are the problems it can resolve.</p><blockquote>💡 We also need another kind of layer that is the famous “LSTM” (or GRU). It is not mandatory but it will finalize the chronological resolution of inputs.</blockquote><p>And finally, we will enhance the model by making “fine-tuning”, also named “transfer learning”, to have very accurate results.</p><p>So many things to do… But ! that will be fun 🎉</p><p>I will not explain what is LSTM in-depth — keep in mind that it helps <strong>a lot</strong> to manage a series of data that are<em> chronologically ordered</em>. We already have made an article to explain how we use it to make <em>cryptocurrency</em> stock prices prediction.</p><p>That’s very powerful, almost magical :</p><p><a href="https://medium.com/smileinnovation/how-to-make-profits-in-cryptocurrency-trading-with-machine-learning-edb7ea33cee4">How to make profits in cryptocurrency trading with machine learning</a></p><p>While the previous article explains how to use cryptocurrency data, we need to work with images. And what do we generally need on machine learning while we are working with images? huh? yes! <strong>Convolutions!</strong> You’re right and win a gift: 🎁</p><p>OK, commonly, a C-NN receives only <strong>one image</strong> and we make convolution on that one. The goal is to find features on those images that will help to make a “prediction” to guess <strong>the object on that image</strong>.</p><p>For example, we present an image of a cat, and the model says “it’s a cat”.</p><p>But now, we don’t want to make that. We want… but we need to make “more” because the expected result is not “a cat”, but “a cat is jumping”.</p><p>You realize that what we need is to find features to find the cat, then use these features in “LSTM” to try to react on movements (or distortions). Finding a jumping cat now needs:</p><ul><li>find the cat on <strong>each frame</strong></li><li>then check if the cat <strong>movement</strong> corresponds to the “jumping” <strong>action</strong></li></ul><p>So we need to repeat <strong>several “cat” detection</strong>, and only after that we need to check the <strong>“action”,</strong> the “movements”.</p><blockquote>Time Distributed layers will save your day.</blockquote><h3>Images should not be fully connected in one convolution</h3><p>The problem is that we’ve got not only “one image” to manage, but we’ve also got potentially 2, 5,… 10 images to inject in the model. And we need to make convolutions for <strong>each image</strong>.</p><p>And because everything is never that simple, that’s not the only problem to solve 😟.</p><h4>The first problem, the input shape — and the unwanted “image merging”</h4><p>If we take a common Sequential neural network, each input is connected to the entire neuron list that resides in the first layer. For only one image, it’s OK — but with several images, we need to <strong>avoid merging several images in one </strong>because<strong> </strong>the <strong>whole pixel list of all images will be sent to the first layer</strong>.</p><p>That means that if I send several images in the first layer, then I will merge the images. And this is not what I need!</p><p>Anyway, if you try to make that, what is the “shape” to set up to that layer?</p><p>The next image is what we <strong>don’t want to do</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*2Lb3rOglouJVET0wJ8fTtg.png" /><figcaption>The problem: all image inputs are merged inside one convolution.</figcaption></figure><p>Let’s take an example of 5 images with 224x224 pixels in grayscale (one channel), Conv2D cannot use a (5, 224, 224, 1) shape (it requires 3 dimensions), and Conv3D is not made to manage that kind of input. No, we need to split the network to have one filter list for each image input (or any other structural data)</p><p>We need to pass <strong>one image to one “convolution block”</strong>, the second to another, and so on…</p><p>So this is what <strong>we need to do</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*KPajMJnBWNamFcbFFONmqw.png" /><figcaption>That’s what we need, one image has got one filter list, Conv2D then MaxPooling, then Dense… and finally, merge the result in other layers</figcaption></figure><p>Now, each image has got <strong>its own “convolutions flow”</strong> and we can, finally, continue the detection.</p><blockquote>It’s like we’ve got one neural network per image, then a last one to make inferences.</blockquote><p>If we separately train each “convolution flow”, so we will have several unwanted behaviors:</p><ul><li>we need very long training because we need to train several convolution flows (one per input image)</li><li>each convolution flows, for one sequence, can have several different weights, and so different features detection that are not linked</li><li>some convolution flows will not detect what others flows can</li></ul><p>We need to be sure that the entire list of convolution flows can find the same features. It’s possible that some convolution flows detect something else, but we need to reduce that risk.</p><p>TimeDistributed layer apply the<strong> same layer to several inputs</strong>. <strong>And it produce one output per input to get the result in time. That’s all !</strong></p><h4>What do we want to do 🤔 ?</h4><p>OK, so the need is simply to be able to get several images as input, making the <strong>same filtering for each image</strong>, and finally to be able to continue the model with other common layers (eg. LSTM…)</p><p><strong>We need to train each input neural network in each distributed branch for one detection (the action, the movement…) and…</strong></p><blockquote>..this is what allows “Time Distributed Layer” — our Savior 👼</blockquote><h3>Finally, let’s use Time Distributed Layers</h3><p><em>Time Distributed</em> layer will do that job, it can apply the same transformation for a list of input data. That can work with several inputs type, including images. All convolutions, Pooling, Dense…</p><p>Afterwards, you can leave the time distributed layer to continue to work with data.</p><p>Keep calm, that will be very nice and easy to do.</p><h4>How to use it?</h4><p>With Keras, the method is the following:</p><pre>model.add(TimeDistributed(TYPE))</pre><p>Where TYPE is a needed layer. For example:</p><pre>model.add(<br>    TimeDistributed(<br>        Conv2D(64, (3,3), activation=&#39;relu&#39;)<br>    ),<br>)</pre><p>That’s not so complicated. It generates 64 convolutions, for each input image. Wait… “input images”?</p><blockquote><strong>For the first layer, you generally need to specify the input shape.</strong></blockquote><p>Usually, a convolution network get one image with shape (width, height, channel_number) (3 dimensions shape).</p><p>Here, we need to define how many images will be injected into the model in one shot. So if the Time Distributed layer is the “input” of the model, we need to set up one more dimension that is the number of the image in one shot.</p><p>For example, if we need to inject 5 images that have the shape (224, 224, 3) (244x224 with 3 RGB channels): we need to add one dimension to present 5 x (224, 224, 3) — the shape is now (5, 224, 224, 3)</p><p>So, for the first layer, if you need to provide the input shape, you can do:</p><pre>model.add(<br>    TimeDistributed(<br>        Conv2D(64, activation=&#39;relu&#39;),<br>        input_shape=(5, 224, 224, 3)<br>    )<br>)</pre><p>And now, we’ve got 64 convolutions, on 5 images that are shaped 224 x 224 with 3 channels (RGB). This 5 convolution flow will be trained in parallel to match the wanted detection.</p><p>K̶e̶e̶p̶ ̶t̶h̶a̶t̶ ̶i̶n̶ ̶m̶i̶n̶d̶:̶ ̶t̶h̶a̶t̶ ̶g̶e̶n̶e̶r̶a̶t̶e̶s̶ ̶5̶ ̶x̶ ̶6̶4̶ ̶c̶o̶n̶v̶o̶l̶u̶t̶i̶o̶n̶s̶ ̶i̶n̶ ̶t̶h̶e̶ ̶m̶o̶d̶e̶l̶,̶ ̶i̶t̶’̶s̶ ̶n̶o̶t̶ ̶w̶i̶t̶h̶o̶u̶t̶ ̶c̶o̶n̶s̶e̶q̶u̶e̶n̶c̶e̶ ̶f̶o̶r̶ ̶m̶e̶m̶o̶r̶y̶,̶ ̶C̶P̶U̶s̶ ̶a̶n̶d̶ ̶G̶P̶U̶s̶.̶ Actually, what makes TimeDistributed layer is to apply the same convolution for each input, and it make it time one after the other.</p><p>For the next layers, we can let Keras guess the right shape to connect as it does for any other layer types. You don’t need to specify the shape.</p><p>What TimeDistributed layer proposes is exactly what we need, the allConv2D blocks that are created will be trained for our wanted detection, so our images will be processed to detect something that is not a simple object detection, but something that “changes” from frame to frame (for example).</p><p>That way, we can apply well-known topology to a series of input data. Here, a pseudo VGG for each frame (on the last section, we will use a simpler method to create that kind of model)</p><pre>model = Sequential()</pre><pre># input, with 64 convolutions for 5 images<br># that have (224, 224, 3) shape<br>model.add(<br>    TimeDistributed(<br>        Conv2D(64, (3,3), <br>            padding=&#39;same&#39;, strides=(2,2), activation=&#39;relu&#39;)<br>        input_shape = (5, 224, 224, 3)<br>    )<br>)<br>model.add(<br>    TimeDistributed( <br>        Conv2D(64, (3,3), <br>            padding=&#39;same&#39;, strides=(2,2), activation=&#39;relu&#39;)<br>    )<br>)<br>model.add(<br>    TimeDistributed(<br>        MaxPooling2D((2,2), strides=(2,2))<br>    )<br>)</pre><pre># Second conv, 128<br>model.add(<br>    TimeDistributed(<br>        Conv2D(128, (3,3),<br>            padding=&#39;same&#39;, strides=(2,2), activation=&#39;relu&#39;)<br>    )<br>)<br>model.add(<br>    TimeDistributed( <br>        Conv2D(128, (3,3),<br>            padding=&#39;same&#39;, strides=(2,2), activation=&#39;relu&#39;)<br>    )<br>)<br>model.add(<br>    TimeDistributed(<br>        MaxPooling2D((2,2), strides=(2,2))<br>    )<br>)</pre><pre>## and so on with 512, 1024... <br>## ...</pre><pre># then we can use Flatten to reduce dimension to 1<br>model.add(Flatten())</pre><pre>## and then... merge the entire outputs to<br>## be able to use Dense(), and make predictions...<br>model.add(Dense(10))<br># ...</pre><p>And that’s it! Not so complicated.</p><p>No need to make several “models” to connect together, no need to manage weights, <strong>e-a-s-y!</strong></p><blockquote>Keep in mind that each layer that is “Time Distributed” will share the same weights. If you injects 5 images, the weights are not tweaked 5 times, but only once, and distributed to every blocks defined in the current Time Distributed layer. That saves calculation time !</blockquote><p>At this time, we’re not far from the final working model. The last point is to be sure that we process images with the time notion. That means that we want to treat the frames in the exact order they come in, with a chronological notion. There is at least one neural computation that is very efficient for that: <strong>LSTM</strong></p><h3>“Hey <a href="https://medium.com/u/521bf7988788">Snips</a>, define LSTM!”</h3><p>LSTM for “Long Short Time Memory”, is a layer that can get several chronological inputs to find what is very useful to predict. It’s a simplified explanation, but it’s near the reality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*h_Yfh8Z6nY-7Fmh2DPgt1w.png" /><figcaption>Source: Wikipedia</figcaption></figure><p>As we are working on frames that are chronologically ordered, we want to be able to detect relation from frame to frame in a given time.</p><p>Because we’ve got inputs that are ordered in time, LSTM is perfect to filter useful values from those inputs.</p><p>There are commonly 2 possibilities:</p><ul><li>make convolution or other neural computation before LSTM</li><li>make the same kind of work after LSTM</li></ul><p>To decide which order to choose, you need to think about what you want to filter.</p><p>For our example, we need to check an object in motion, so we need to search the object before detecting the movement. So, here, we need to make convolutions before LSTM.</p><p>For another example, as cryptocurrency evolution, you can filter input values in time with LSTM, then make some manipulation on the output to find evidence. In this case, you can usefully connect layers after LSTM block.</p><p>But, both cases are not constructed the same way, you’ll need to tweak LSTM to adapt the output.</p><h3>Time Distributed before LSTM</h3><p>🚀 Goal: do some computation before managing the time.</p><p>Transforming input data that are distributed in time is OK, but the network is not yet able to use the LSTM power. We now need to let the network to be able to use memory and enhance the prediction by taking advantage of LSTM.</p><p>For the previous example, we worked with images that are “inputs”, so that’s obvious to make Time Distributed layers <strong>before</strong> the LSTM layer because we want to let LSTM work with <strong>convoluted images</strong>.</p><p>The LSTM output should not be a “sequence” (you can, but it’s useless here) — we only need to make some fully connected layers to find predicted “action” that is present on our input frames. So we set return_sequence to False</p><p>For images, the following python source is a pseudo example with Time Distributed layers before the LSTM layer:</p><pre>model = Sequential()</pre><pre># after having Conv2D...<br>model.add(<br>    TimeDistributed(<br>        Conv2D(64, (3,3), activation=&#39;relu&#39;), <br>        input_shape=(5, 224, 224, 3) # 5 images...<br>    )<br>)<br>model.add(<br>    TimeDistributed(<br>        Conv2D(64, (3,3), activation=&#39;relu&#39;)<br>    )<br>)</pre><pre># We need to have only one dimension per output<br># to insert them to the LSTM layer - Flatten or use Pooling<br>model.add(<br>    TimeDistributed(<br>        GlobalAveragePooling2D() # Or Flatten()<br>    )<br>)</pre><pre># previous layer gives 5 outputs, Keras will make the job<br># to configure LSTM inputs shape (5, ...)<br>model.add(<br>    LSTM(1024, activation=&#39;relu&#39;, return_sequences=False)<br>)</pre><pre># and then, common Dense layers... Dropout...<br># up to you<br>model.add(Dense(1024, activation=&#39;relu&#39;))<br>model.add(Dropout(.5))</pre><pre># For example, for 3 outputs classes <br>model.add(Dense(3, activation=&#39;sigmoid&#39;))</pre><pre>model.compile(&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;)</pre><p>The model is more or less:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Yf0K3Yd7RqxXWtbK06Iqw.png" /></figure><blockquote>Please note:<strong> </strong>The above graph is a representation, actually for each input, you will use the same Conv2D and Flatten layers. Keras will distribute the input in layers step by step.</blockquote><p>The Flatten layer is only needed because LSTM shape should have one dimension per input.</p><blockquote>👀 Our next article will show you examples on video, stay tuned !</blockquote><h3>Time Distributed after LSTM</h3><p>🚀 Goal: manipulate data after having managed the time.</p><p>This time, we need to set up LSTM to produce a sequence. We can imagine that we want to inject 5 items of 10 values and make some transformation on the sequence that LSTM can produce.</p><p>But this time, we want to make a fully connected computation on each filtered element. LSTM is not only a “filter”, but it also keeps each input computation in memory, so we can retrieve them to make our manipulation.</p><p>That’s what the return_sequences attribute provides. LSTM will now produce 5 outputs that can be time distributed.</p><pre>model = Sequential()</pre><pre># a model with LSTM layers, we are using 5 frames of <br># shape (10, 20)<br>model.add(<br>    LSTM(1024, <br>        activation=&#39;relu&#39;,<br>        return_sequences=True,<br>        input_shape=(5, 10)<br>    )<br>)</pre><pre># LSTM outputs 5 items <br># that is the correct shape to continue to work.<br># We need to get several outputs and make the same<br># process on each sequence item:<br>model.add(TimeDistributed(<br>    Dense(128, activation=&#39;relu&#39;)<br>))<br>model.add(TimeDistributed(<br>    Dense(64, activation=&#39;relu&#39;)<br>))</pre><pre># Flatten, then Dense... Dropout...<br># note: Flatten should not be time distributed because here,<br># we want to have only one dimension for the next layers<br>model.add(Flatten())<br>model.add(Dense(64))<br>model.add(Dropout(.5))</pre><pre># use N outputs<br>model.add(Dense(N, activation=&#39;softmax&#39;))</pre><p>That is more or less the following representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KJjce1Xnq87YpYXNiAbNw.png" /></figure><p>Of course, that’s an example to illustrate how to create a model. The above model is not useful, you’ll need to adapt it to your needs.</p><p>As you can see, we generally need to use the “Flatten” layer to be able to merge neurons outputs and commonly continue the network.</p><p>And one more time, Keras helps a lot to not have to make shape deduction by our self. The model writing is natural, readable, easy to understand and very instinctive.</p><p>Writing that kind of neural network by hand can be very complicated and potentially difficult to debug. To make proof of concept, Keras is a rare framework that allows making tests on that kind of neural network without wasting our time to check what and how to connect.</p><blockquote>💡 The power of Time Distributed layer is that, wherever it is placed, before or after LSTM, each temporal data will undergo the same treatment.</blockquote><p>So wherever the situation of the data in time, it will receive the same transformation.</p><h3>Transfer Learning in Time Distributed block, this is possible?</h3><p>Strangely, I never saw something telling about the fact that we can add a complete model inside a second model with Keras. I mean that I generally see examples where the base model output is connected to our model inputs. But, Keras can ease that construction by using a model as a layer.</p><p>Let me explain. I was using a pre-trained model to do transfer learning that way:</p><pre># use pre-trained VGG16<br>vgg = VGG16(...)</pre><pre># add our own layers<br>x = vgg.output<br>x = Dense(64)(x)<br>...</pre><pre># prepare our output<br>pred = Dense(3, ...)(x)</pre><pre>model = Model(inputs=vgg.inputs, outputs=pred)</pre><p>But, what I didn’t know is that we can use model.add() method to inject… a model. As we do it with “Layers”.</p><p>So, that’s how I can make transfer learning with a pretty nicer syntax (it’s a truncated example, of course, you need to manage input shape, activations…):</p><pre>vgg = VGG16(...)<br>model = Sequential()</pre><pre># add vgg model to our own model<br>model.add(vgg, input_shape=(...))</pre><pre># and add our layers<br>model.add(Dense(64))</pre><pre># finally 3 outputs<br>model.add(Dense(3))</pre><p>I don’t know what you think, but I prefer that syntax. Easier to read and write.</p><blockquote>⚠ Appending a model as a Layer, and connecting base model outputs to model inputs isn’t the same. The first method generates a heavier model with scopes, while the second is a bit lighter and readable if you preview the graph as a chart. Adding model as a Layer should be, IMHO, avoided ! But it’s easy for prototyping and tests.</blockquote><p>What about Time Distributed? Well, that’s the same.</p><p>I wanted to use transfer learning of VGG16 with <em>imagenet</em> pre-trained weights, but with LSTM and Time Distributed.</p><p>Following the previous syntax, we can now write :</p><pre>import keras<br>from keras.layers import Dense, LSTM, \<br>    Flatten, TimeDistributed, Conv2D, Dropout<br>from keras import Sequential<br>from keras.applications.vgg16 import VGG16</pre><pre># create a VGG16 &quot;model&quot;, we will use<br># image with shape (224, 224, 3)<br>vgg = VGG16(<br>    include_top=False,<br>    weights=&#39;imagenet&#39;,<br>    input_shape=(224, 224, 3)<br>)</pre><pre># do not train first layers, I want to only train<br># the 4 last layers (my own choice, up to you)<br>for layer in vgg.layers[:-4]:<br>    layer.trainable = False</pre><pre># create a Sequential model<br>model = Sequential()</pre><pre># add vgg model for 5 input images (keeping the right shape<br>model.add(<br>    TimeDistributed(vgg, input_shape=(5, 224, 224, 3))<br>)</pre><pre># now, flatten on each output to send 5 <br># outputs with one dimension to LSTM<br>model.add(<br>    TimeDistributed(<br>        Flatten()<br>    )<br>)</pre><pre>model.add(LSTM(256, activation=&#39;relu&#39;, return_sequences=False))</pre><pre># finalize with standard Dense, Dropout...<br>model.add(Dense(64, activation=&#39;relu&#39;))<br>model.add(Dropout(.5))<br>model.add(Dense(3, activation=&#39;softmax&#39;))</pre><pre>model.compile(&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;)</pre><p>That gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*b2q_b4q5sHNPkNREKuk86A.png" /></figure><p>Just take a little time to notice what the diagram is showing:</p><ul><li>the input take 5 images with shape (224, 224, 3)</li><li>we reduce shape to 5 outputs with shape (25088)</li><li>LSTM receives that 5 inputs</li></ul><p>So that means that LSTM receives 5 chronological processed and flatten images as input. That’s exactly what we want!</p><h3>Last words</h3><p>TimeDistributed layer is very useful to work with time series data or video frames. It allows to use a layer for each input. That means that instead of having several input “models”, we can use “one model” applied to each input. Then GRU or LSTM can help to manage the data in “time”.</p><p>For sure, when the model is proven to work, it is generally advised to try to make the neural network by hand with your tensors and a lower level framework to try to have better performance. But, using Keras for <em>Time Distributed </em>layers is not a bad idea. We used it to make movement prediction and recognition, and that was (trust me) very “easy” to do.</p><p>The next article will show you a nice example that can guess which is the action that happens in a video, with a simple video frame generator.</p><p><a href="https://medium.com/smileinnovation/training-neural-network-with-image-sequence-an-example-with-video-as-input-c3407f7a0b0f">Training neural network with image sequence, an example with video as input</a></p><h3>That’s all folks!</h3><p>Did you enjoy it? If so don’t hesitate to 👏 our article or <a href="https://mailchi.mp/c414f1508567/techwatch">subscribe to our Innovation watch newsletter</a>!<br>You can follow Smile on <a href="https://www.facebook.com/smileopensource">Facebook</a>, <a href="https://www.twitter.com/GroupeSmile">Twitter</a> &amp; <a href="http://www.youtube.com/user/SmileOpenSource">Youtube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b39aa4ce00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/how-to-work-with-time-distributed-data-in-a-neural-network-b8b39aa4ce00">How to work with Time Distributed data in a neural network</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Imannotate - easy image annotation for all]]></title>
            <link>https://medium.com/smileinnovation/imannotate-easy-image-annotation-for-all-3b2c776fd05c?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b2c776fd05c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[image-annotation]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 10:01:02 GMT</pubDate>
            <atom:updated>2018-10-16T16:10:56.636Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXya139n_002QetAWFv-NQ.png" /></figure><h3>Imannotate, opensource collaborative image annotation for machine learning</h3><h4>We made a tool to annotate images with teammates, easy to install and extensible. And obviously, it’s open source!</h4><p>In the machine learning and deep learning world, one of the most wanted features is to be able to recognize several objects on one image. To be able to do that, you will need to train a model with <em>annotated images</em>. Immanotate is a tool we built to create that annotation data set. Let’s see why it could be the tool that you need over others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrN5xxJTP5e58rMKK3DtRQ.png" /><figcaption>Imannotate is a tool to annotate image, export as data that can be used in model training</figcaption></figure><h3>What is “image annotation”?</h3><p>You certainly already have learned that image recognition is the new Eldorado, especially for the machine learning activity. And you should know that there are two main approaches:</p><ul><li>CNN that is very common, and can recognize one object in an image</li><li>R-CNN that is “Recurrent”, and can recognize several objects in an image, and where they are placed</li></ul><p>CNN is pretty “simple”: you need a set of images and you train your model with classification outputs. That’s not complicated at all (really, that’s not) and you may create your own CNN with a tiny number of hidden layers. You only need to classify training images in directories or with a simple data file (or database) where each image and corresponding label reside. It’s very easy to make that work.</p><blockquote>CNN = One image corresponds to one label. Nothing more.</blockquote><p>But as soon as you want to train your model to recognize where are these objects, how many and where they are in images… the training phase is a bit harder. Let’s take an example, if we need to find dogs and cats in several images, you can see that an image can have several of them. To train that kind of model, you’ll need to have more information.</p><blockquote>R-CNN = One image has got several labels localized in several regions (coordinates)</blockquote><p>R-CNN will extract regions with several convolutions and each feature may be sent to other model layers to make the recognition. But at the training phase, you’ll need to help the model to find the objects. So, I repeat, you need to annotate enough of images to give it coordinates where resides the objects you want to find later.</p><blockquote>Annotation = Image + coordinates around objects + one label per object</blockquote><p>Unfortunately, you’ll need to annotate them by hand… and it’s probably the worst pastime I practised on Sunday.</p><p>So you need to store more information:</p><ul><li>the image path</li><li>bounding boxes coordinates</li><li>label for that coordinates</li></ul><p>That way, you may have <em>N</em> labels for one image, and that’s very different!</p><p>Then you’ll need a special model architecture to be able to send images and labels with coordinates. Even if it’s not the subject of that article, we successfully used Retinanet model for Keras that is very efficient and fast.</p><h3>Why build our own tool?</h3><p>Now you know what you need, so you realize that the task is absolutely huge. For a large number of images, you’ll need to annotate each object getting coordinates and save it somewhere to be treated later. There is a few software made for that work, and all of them are working (more or less). But whatever the tool we tried, there was a little point that avoids us to use it. Mainly: collaboration, storage, image provider. . .</p><p>We need to use S3 storage where we can put images, or API to get them from a search engine.</p><p>And we wanted to be able to annotate images with a large team. So we needed authentication and project management.</p><p>We tried some tools and services. A lot were very nice but each time there was something that was not expected. Once there was no collaborative option, another didn’t have S3 or API entry point, and others were so complicated for the user that we abandoned the idea.</p><p>We decided to build our own. Here:</p><p><a href="https://github.com/smileinnovation/imannotate">smileinnovation/imannotate</a></p><h3>How works Immanotate?</h3><p>Imannotate is a package, a REST API, and a web user interface. The package and the REST API are built in Golang while the user interface is made in Angular 6.x</p><p>Why not Rust, Ruby, React, Vue…? They are very useful and working great, but we had to make choices. Golang is very efficient for the API service (with the gin-tonic framework) and Angular is a good choice in our opinion. Others could work and be very efficient too. The choice is mainly made following author preferences. (Yes, it’s me 😸)</p><p>We mainly focused on making the tool “modular” and collaborative. So we take time to implement “interfaces” for the entire management (project, user, authentication, image providers, and so on) — that means that you may create your own image provider for your own constraints, your own authentication for your business, and (not for now, but it will be possible soon) you will be able to mix them.</p><blockquote>Wait: that’s the goal, but for now there are still things to fix to make it clean. Keep that in mind if you want to read sources and give a hand.</blockquote><p>We provide a full-Mongo implementation to use authentication, project, user management… And later we will provide LDAP authentication.</p><p>Also, we provide 2 image providers:</p><ul><li>Qwant API (while it’s freely available 😌)</li><li>S3 (and probably Minio later)</li></ul><p>In progress: Filesystem storage. That may be surprising to not have built filesystem storage at first, but how a user may put millions of images in the server that serves Imannotate? So, it’s preferable to use distant storage and image API for now.</p><p>As soon as you created an annotation project, you may choose which provider to use, and you may share the project with other users.</p><p>Immanotate will fetch images and distribute them one by one to users in the annotation view. Also, <strong>it avoids double annotation</strong> (image is only shown to one user) — if the user didn’t annotate an image (if the user “passes”, or leaves the application without to save current image) so the image is kept being resented to another user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*ut7gcUw3IPOwPx16a9zmXA.gif" /><figcaption>Image provider distributes images from a “channel” to not let users annotate the same image twice</figcaption></figure><p>That’s all, it seems to be easy for users — but that was not so easy to develop. We had to find good ways to avoid doubles, to manage users, project, and shares, and to let others ability to change drivers for “all”.</p><p>But now, Immanotate can be installed on servers, we propose it as an open source project and you may use <strong>Docker</strong> to launch it.</p><h3>Start it, try it!</h3><p>The easiest way to make Imannotate working is to use our Docker implementation. You may use the development version that is working a bit slower than the “production” mode.</p><p>For both, you’ll need Docker and Docker-Compose, our GitHub README file explain how you may launch Imannotate outside Docker.</p><p>Get GitHub project:</p><pre>git clone <a href="https://github.com/smileinnovation/imannotate.git">https://github.com/smileinnovation/imannotate.git</a><br>cd imannotate</pre><h4>Production version</h4><p>Now to make it serve as “production”, use that command line:</p><pre>make run</pre><p>That starts a MongoDB Docker container and the main Imannotate server in a second Docker container that is listening port 8000. Then visit <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> . For that version, the software is delivering API and static files (for the built Angular interface) as it runs in “stand alone”.</p><h4>Development Version</h4><p>If you want to use “development” server, that is useful to make Golang and Angular fixes or enhancements, and instantaneously see the changes:</p><pre>make dev</pre><p>This time, it starts:</p><ul><li>Angular “ng serve” container to serve UI on port 4200</li><li>Gin service listening on port 3000 that is a proxy to Imannotate service listening on port 8000. Gin allows rebuilding Golang server when source code is touched.</li><li>A MongoDB container</li><li>Nginx container that exposes port 8080 that is used as a reverse proxy to Angular UI and Golang API, which helps not to have CORS problems and to unify URLs.</li></ul><p>URL is now <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080</a></p><p>You are now able to log in or create a user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*5z1kb0RcFFf1NmO34SJNAg.png" /></figure><h3>Annotation Project</h3><p>It’s now time to create an annotation project. Name it, add a description and propose some “tags” those are the usable “classes” or “labels” that user will be able to use on the image.</p><p>When the project is created, you may propose to share to project with other users. Note that the project can only be edited by the owner (you), other users will only be able to annotate images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*xMX3JJwdJxbPjuK4XdE0sg.png" /><figcaption>Create a project, choose image provider, and save it.</figcaption></figure><p>Then, back to the dashboard, the project is now ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qxY7b14_-ABo5WkEbeDTQ.png" /></figure><p>You can now click on “annotate” button to start your annotation job.</p><p>That’s easy. If you want to pass an image because you’re not sure, or you don’t know how to annotate this one, click on “pass” button. The image will be back later for you or your contributors. If there is no cat or dog, so press “nothing” button. The annotation will be exported with no bounding box (some machine learning model can use it to enhance the raining phase with images where no labeled object is found).</p><p>“Next” button saves the annotation in the database, so you can now get the export data.</p><h3>Get Data</h3><p>After having annotated your set, you may return in dashboard and press “export” button. It will download CSV file containing one line per label. Each row contains</p><ul><li>URL to the image</li><li>Label name</li><li>Bounding box information (from 0 to 1)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUirERKDlYVJt27RO2-t4w.png" /></figure><p>You may now manipulate this file to download images, and load your data to train your model.</p><h3>Next improvements</h3><p>At this time, Imannotate is able to use providers that we have built inside API packages and UI. We need to make it easier to create your own image provider.</p><p>We are making Imannotate able to hit “helper” API and “train API” to make it possible to:</p><ul><li>pre-calculate annotations to help workers to annotate an image</li><li>launch and train while users are annotating images</li></ul><p>Also, we want to provide those options:</p><ul><li>Provides different exports formats</li><li>provides different annotation method (circles, polygons, …)</li><li>an option to provide images in an export archive</li><li>and many more options than you may imagine</li></ul><p>We want to improve user experience and make the annotator component a bit easier to use. Imannotate works on mobile devices (with a touch screen), but it is not so natural to work on. We will make efforts to enhance that.</p><h3>Help Wanted and Appreciated</h3><p>At Smile, we love Opensource solutions, we are using them and we’re proud to be the first open-source software integration in Europe. Our solutions are commonly proposed to the community as with open source licence. That means that you can use Imannotate for your own job, and make fixes, enhancements and so on… and you can propose them to us. We will be happy to integrate your corrections and ideas to the solution to grow the fantastic solution that can be.</p><p>One last note: we are aware that some parts of the code are not yet well implemented, but we make sure to correct and improve sources and features.</p><p>Thanks for reading ! If you want more informations about Imannotate, don’t hesitate to heads to <a href="http://smile.eu/">smile.eu</a> . We also publish a fortnightly technology watch newsletter, you can <a href="https://www.getrevue.co/profile/smileinnovation">take a look at it online</a> &amp; subscribe !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b2c776fd05c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/imannotate-easy-image-annotation-for-all-3b2c776fd05c">Imannotate - easy image annotation for all</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SageMaker : Bring your own Algorithms]]></title>
            <link>https://medium.com/smileinnovation/sagemaker-bring-your-own-algorithms-719dd539607d?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/719dd539607d</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 12:24:28 GMT</pubDate>
            <atom:updated>2018-06-13T12:26:15.319Z</atom:updated>
            <content:encoded><![CDATA[<h4>With the help of Docker, you will be able to customize training and infering models using other frameworks that those provided by SageMaker</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ETsqASs_Q-MBcDv9" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You may already know what Amazon SageMaker is. We can name it as “Machine Learning as a Service” providing <a href="https://jupyter.org/">Jupyter notebook</a>, Python API to launch model training on huge servers with CPU or GPU, then store model and data on S3. Finally <em>deploy and serve</em> that model with a REST API. In order to help you, SageMaker provides several built-in models and frameworks like MXNet, Tensorflow, …</p><p>To play fair, you may be able to train models with built-in for many cases. But one day, like me, you will face some dead end. In my case, that was the use of Keras with a generator, using some Python packages and wanted to tweak my service. But don’t panic, Amazon takes care of you and allows you to create your own environment.</p><blockquote>And thanks to SageMaker using Docker!</blockquote><p>Yes, Docker one more time! Really, SageMaker starts Docker container on an instance to have a working environment suitable for your needs. If you use the built-in frameworks, SageMaker provides the right Docker image without the need to specify it. But when you want your own, it’s easy to build, push and use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*AAcRTH4SoYreT-j2E78QLg.png" /><figcaption>SageMaker train, deploy and use</figcaption></figure><h3><strong>Create Docker image</strong></h3><p>You may want to go taking a look at SageMaker’s “examples” Github page. In the “advanced” section, there are several “bring_you_own” directories where Docker is used. That’s a good start to grab informations.</p><p><a href="https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality">awslabs/amazon-sagemaker-examples</a></p><p>We will prepare our environment by creating that directory structure.</p><pre>sage<br>├── Dockerfile<br>├── local_test<br>│  ├── predict.sh<br>│  ├── train.sh<br>│  ├── serve.sh<br>│  └── test_dir =&gt; /opt/ml in container<br>│      ├── input<br>│      │   ├── config<br>│      │   └── data<br>│      │       └── training<br>│      ├── model<br>│      └── output<br>└── program<br>    ├── (some scripts...)<br>    ├── train<br>    └── serve</pre><p>The Dockerfile can be built from any base image, but if you plan to use your own GPU and AWS “p2” instances, I strongly advise to use:</p><pre>FROM nvidia/cuda:9.0-base-ubuntu16.04</pre><p><em>Note: </em>you will need to manage CPU and GPU usage and if you want to use Nvidia GPU on your own computer you will need <em>nvidia-docker</em> (<a href="https://github.com/NVIDIA/nvidia-docker">https://github.com/NVIDIA/nvidia-docker</a>)</p><p>Not to mention, it’s a bit difficult to switch from CPU to GPU while you will use the same image to train and serve. When you’re testing, you will probably use “tensorflow-gpu” package and need a “p2” instance that has GPU. But, when you will deploy the image on an “m4” instance, there will be no GPU and the package will raise an error (because it cannot find any GPU). You must use the “tensorflow” package instead. So, what I did is to detect if the “import” of tensorflow raises an exception. If it does, I uninstall “tensorflow-gpu” and install “tensorflow” at the Docker container startup. It results in a few more seconds to start up the instance, but this “hack” is working perfectly fine in this scenario. I’m pretty sure there are other ways to do it, feel free to comment if you have one in your mind.</p><p>Then, install all necessary packages to use CUDA from the Dockerfile:</p><ul><li>cuda-command-line-tools-9–0</li><li>cuda-cublas-dev-9–0</li><li>cuda-cudart-dev-9–0</li><li>cuda-cufft-dev-9–0</li><li>cuda-curand-dev-9–0</li><li>cuda-cusolver-dev-9–0</li><li>cuda-cusparse-dev-9–0</li><li>libcudnn7=7.0.5.15–1+cuda9.0</li><li>libcudnn7-dev=7.0.5.15–1+cuda9.0</li></ul><p>Afterwards, you may install other packages like Python, wget, zip and so on. Then you may use “pip” to install Python packages as Keras, Tensorflow-gpu, numpy, and so on…</p><p>You should <strong>not </strong>give CMD command in your Dockerfile, but you should set PATH environment to the directory where you copied program directory inside the image. In that directory resides train and serve scripts <strong>that are launched by SageMaker when you “train” the model, and when you want to “deploy” it.</strong></p><p>So, do that:</p><pre>ENV PATH=/program:${PATH}<br>ADD program /program<br>RUN chmod +x /program/train /program/serve</pre><p>Our serve script launches Flask server, you need to create HTTP routes to /ping and /invocations, the last one is used to infer (reads predict). Moreover, /ping should check if the model is loaded and respond “200 OK” if everything is working fine. Keep in mind that AWS will ping each second this endpoint, so we need to load the model in memory one time for all.</p><p>To get a better picture on how it works, you can refer to <a href="https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/scikit_bring_your_own/container/decision_trees/serve">https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/scikit_bring_your_own/container/decision_trees/serve</a> that is a good starting point to create WSGI application (see <em>wsgi.py</em> and <em>predictor.py</em>) — you will be able to change “predictor.py” script to adapt on your own needs.</p><p>Because I’m using Keras with TensorFlow, I needed to manage the fact that one model is served on several processes:</p><pre>class ScoringService(object):<br>    model = None # Where we keep the model when it&#39;s loaded<br>    graph = None</pre><pre>    @classmethod<br>    def get_model(cls):<br>        if cls.model is None:<br>            cls.model = load_model(<br>                  os.path.join(model_path, &#39;model.h5&#39;))<br>            cls.model._make_predict_function()<br>            cls.graph = K.get_session().graph<br>        return cls.model</pre><pre>    @classmethod<br>    def predict(cls, input):<br>        clf = cls.get_model()<br>        with cls.graph.as_default():<br>            return clf.predict(input)</pre><p>So, now, I can build the Docker image</p><pre>docker build -t sagemaker-test .</pre><h3><strong>Prepare Docker image and test your code on your computer</strong></h3><p>We need to prepare the Docker image and also test it prior using it on SageMaker. It would be sad to waste time starting a training that will not succeed, and it would be difficult to find the problem on remote instances. Docker has the advantage of allowing to use an almost identical functional environment on your development computer than on production, so let’s take advantage of it.</p><p>The goal here: train a little subset of data to check if model compiles, we will try to serve API on the next section.</p><p>When using an AWS instances, some directories are mounted from S3 where we have uploaded our “train data”, to /opt/mlon the instance.</p><p>Locally, we’ll need to mount our own directory to /opt/ml. Inside our directory structure, we’ve created test_dir and we need to pay attention that :</p><ul><li>/opt/ml/input/training is where your training data resides</li><li>/opt/ml/input/config is where <em>hyperparameters.json</em> resides — on a local instance we’ll need to create it ourself, but with SageMaker “estimator” we’ll pass that parameter as dict. SageMaker will write it for us.</li><li>/opt/ml/model is where the model is written, on SageMaker that model will be archived as <em>tar.gz</em> file and uploaded on your S3 bucket</li><li>/opt/ml/output can be use to write output (error, info…)</li></ul><p>Note that training is in fact the name of the “channel” used when we’ll launch training step from SageMaker, we may add test and validation channels, and so we need to create that directories and use them. But for now, let’s keep it simple.</p><p>So, I duplicate my training data inside local_test/test_dir/input/training and the following command to launch Docker container (you may save that in local_test/train.sh):</p><pre>docker run --rm -v $(pwd)/test_dir:/opt/ml sagemaker-test train</pre><p>You can notice the “train” command passed to Docker container, it will call /program/train inside the container.</p><p>Our “train” python script can now use /opt/ml/input/data/training to read data, and train the model. Then write the model file in /opt/ml/model/model.h5. And voilà !</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F4MxMvzhTEuqty%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F4MxMvzhTEuqty%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F4MxMvzhTEuqty%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/228c4c9c811552b59694effbe0921111/href">https://medium.com/media/228c4c9c811552b59694effbe0921111/href</a></iframe><h3><strong>Now that the image is ready, let’s test it locally</strong></h3><p>Starting by creating whatever we want to respond to /ping and /invocations endpoints via HTTP, we need to check content type, data size, … but we only need those endpoints. In order to get a lazy loading of our model, we test in the “ping” call if it exist, and load it if necessary. By doing so we also implementing a smart health-check for SageMaker (cf. previous ❡)</p><p>Again, I advise to take a look to the <a href="https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container/decision_trees">examples given by SageMaker</a> to find how to customize to your own needs.</p><p>Ok, now it’s time to try (by save the following CLI in local_test/serve.sh)</p><pre>docker run --rm -v $(pwd)/test_dir:/opt/ml -p 8080:8080 sagemaker-test serve</pre><p>It will mount local directories exactly the same way as in the “train” stage, but now using “serve” (which is the /program/serve script). <br>Indeed, you can use whatever ports mapping, it’s up to you 😉.</p><h4>And now, make a test!</h4><p>We can use the <em>requests</em> package from a python script, or simple <em>curl</em> call to ping <em>http://127.0.0.1:8080/ping</em> and call <em>http://127.0.0.1:8080/invocations</em> (<em>POST</em> call).</p><h3><strong>Now, let’s push it to AWS SageMaker</strong></h3><p>We’re now ready to train much more data, build the model, save it on S3 and serve our API from AWS instance. The only thing we need to do this, is to push your image on ECR and our training data on S3.</p><p>The following build_and_push.sh script can work for all projects:</p><p><a href="https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/scikit_bring_your_own/container/build_and_push.sh">awslabs/amazon-sagemaker-examples</a></p><p>You put this script in your project, then call it by passing the image name as parameter :</p><pre>./build_and_push.sh sagemaker-test</pre><p>It will push something like $<em>{account}.dkr.ecr.${region}.amazonaws.com/sagemaker-test:latest </em>on Amazon Docker image repository. That image can now be instantiated to build the model and serve API.</p><p>In order to use a specific version of the image, I edit the script to remove the “latest” tag.</p><p>On SageMaker you can now create a Jupyter notebook and start a new estimator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a8081278d4ba48d52c24f910a96661/href">https://medium.com/media/a0a8081278d4ba48d52c24f910a96661/href</a></iframe><p>After training is done, the model is archived in the S3 location you provided. You can now deploy it:</p><pre>predictor = tree.deploy(initial_instance_count=1,<br>    instance_type=&#39;ml.m4.xlarge&#39;)</pre><p>That will create the following items (you can check them on the SageMaker dashboard and tweak them if necessary):</p><ul><li>a configuration endpoint — this configuration refers to the image you are using, and the model location to load (in /opt/ml...)</li><li>an endpoint that uses the configuration to starts an instance that launches your Docker image as a container and run the “serve” script.</li></ul><p>If the /ping endpoint returns an error (model is not loaded, a problem with port binding, …) the instance is killed and you can check errors in Jupyter notebook or through the CloudWatch interface.</p><p>Ok, now, let’s make a test. Try to predict something:</p><pre>res = predictor.predict(some_data)<br>print(res)</pre><p>That should:</p><ul><li>use any serializer if you needed one to send data to API</li><li>call the /invocations endpoint on your instance</li><li>return the prediction</li></ul><h3>Using our API outside the notebook</h3><p>This is pretty simple, the only thing we need is to create an “Estimator”, and we can do it inside or outside SageMaker interface (on Raspberry Pi, on our laptop…):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/200bb4cd75bf5b08bf16b609fdbc5b49/href">https://medium.com/media/200bb4cd75bf5b08bf16b609fdbc5b49/href</a></iframe><p>Of course, that API is <strong>not </strong>public<strong> </strong>so you need to be authenticated to AWS with a correct user (or in a group). This snippet works in Jupyter and in a distant computer as soon as you setup AWS configuration (install awscliand useaws configure to create ~/.aws/config file)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOe8qcXHfgRGMNeYaEPQlw.png" /><figcaption>Burger and Salad recognition</figcaption></figure><h3>Winding up</h3><p>So, what we can reflect on? Amazon SageMaker got several good points:</p><ul><li>it has efficient built-ins to create a model and train it on a huge server with or without GPU</li><li>it provides Jupyter notebook to launch train, services and test the model</li><li>it also provides a really useful “sagemaker” python package with many classes and function to ease the work</li><li>we can use our own Docker image to customize the environment, training phase, API service, or using other frameworks, … as far as we follow the “train” and “serve” requirements. We can use OpenCV HAAR detection and make our own “train” script that saves XML model, use OpenCV to load that model and responds to clients, and, why not, use another language like Go or PHP to serve our API, <strong>awesome !</strong></li><li>We can also get models from your S3 bucket and use them outside SageMaker, so that means that we could use SageMaker to only train your model.</li></ul><h4>Downsides</h4><ul><li>We need to manage CPU and GPU separately if we want to use the same image to train and serve on different instances (or locally with or without GPU), and that means that we’ll need to “hack” something to remove “tensorflow-gpu” and install “tensorflow”. There are others ways to do it I didn’t explored, like using tagged images and change the termination endpoint configuration. I didn’t checked how SageMaker standard images manage this, but if anyone of you did, please tell us in comments 😉.</li><li>On paper, <em>you don’t need to create your own Docker image for Keras</em>, but I didn’t successfully found a way to install our specific configuration of OpenCV . That’s OK in Jupyter designing phase, but not on training and inference instances. Keep in mind that our Jupyter notebook is not the “train” script that is launched on the training instance.</li><li>I didn’t find other way to change the entry point with <em>Estimator </em>as we can do with built-ins models. SageMaker built-ins allow to code a bundled script that is used to train and serve the model, but with our own Docker image, this is two scripts (trainand serve) we need to insert in image, and we didn’t found how to make it tweakable from Jupyter— that means each image is built for a certain kind of environment, and you only can try to tweak it with hyperparameters. Maybe I’m doing something wrong. I’ll check that point later.</li></ul><p>At <a href="https://smile.eu/">Smile</a> we using SageMaker for many large CNN to build and train and we appreciate fact that Amazon allows Docker usage to setup environment. If you have interest in computer vision, for projects or to work with, feel free to reach us at <a href="/service/mailto:dir-innovation@smile.eu">dir-innovation@smile.eu</a>.</p><p>Did you enjoyed it ? If so don’t hesitate to 👏 our article or <a href="https://www.getrevue.co/profile/smileinnovation">subscribe to our Innovation watch newsletter</a> !<br>You can follow Smile on <a href="https://www.facebook.com/smileopensource">Facebook</a>, <a href="https://www.twitter.com/GroupeSmile">Twitter</a> &amp; <a href="http://www.youtube.com/user/SmileOpenSource">Youtube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719dd539607d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/sagemaker-bring-your-own-algorithms-719dd539607d">SageMaker : Bring your own Algorithms</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magento as a Service]]></title>
            <link>https://medium.com/smileinnovation/magento-as-a-service-e788b6f90ed2?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e788b6f90ed2</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[magento]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 20:22:22 GMT</pubDate>
            <atom:updated>2018-04-05T20:34:10.648Z</atom:updated>
            <content:encoded><![CDATA[<p>How-to build an e-store factory</p><p><em>Co-written with </em><a href="https://medium.com/u/f367539e3d4"><em>Romain Ruaud</em></a><em>, teammate at Smile, Magento expert</em>.</p><p>Thanks to a great <a href="https://www.smile.eu/en/technologies/magento">Magento expertise and partnership</a>, Smile is renowned for its <a href="https://www.smile.eu/en/offers/digital">e-store offer</a>.</p><p>As part of our continuous improvement, we are always looking for innovation to deliver the best to our clients. And one particular interesting topic we had in mind for e-store projects was the ability of delivering a new store as a full fledge service : an e-store as a service.</p><p>And to deliver on-demand a new store, indeed some changes are required in the way we organised the work but also to adapt our tooling. In today’s words we can speak about <strong>DevOps </strong>and<strong> PaaS</strong>.</p><h3>A traditional Magento dev environment</h3><p>For a long time, we used Magento with virtual machines, then we had implemented a developer skeleton for LXC. Both worked. VMs were heavy to share and deploy, and we had complexity to make them near of the hosting platform. LXC was a revolution, more lightweight, very closed to the OpenVZ platform on the hosting side, that was a big enhancement for us.</p><p>At Smile we build complex Magento applications since the appearance of the solution, which led us to acquire a lot of experience on this product, especially about how to deploy, host and interface huge E-Commerce websites.</p><blockquote>We have been four-times Europe Partner of the the Year (2010–2014), two-times Spirit of Excellence (2015–2016) and Global Elite Partner (2017) awarded by Magento, which is putting Smile to the world top 5 Magento integration partners.</blockquote><p>Several years ago we decided to industrialize our deployment system with the following pattern :</p><ul><li>Production/Staging environment : <a href="https://openvz.org/Main_Page">OpenVZ</a> instances provisioned by Ansible</li><li>Developers environment : <a href="https://en.wikipedia.org/wiki/LXC">LXC containers</a> provisioned by the same <a href="https://www.ansible.com/">Ansible</a> recipes.</li></ul><h4>Benefits</h4><p>This was the first step in order to obtain a versioned and replicable project skeleton across all the different environments of an application. This allowed us to start a new Magento project from scratch quickly, by provisioning a new monolithic LXC container.</p><p>Developers are able to override the Ansible recipes of a given project to reflect their changes on the OpenVZ production platform.</p><h4>Disadvantages</h4><p>However, there were still many drawbacks to this approach that were hard to cover :</p><ul><li>Ansible recipes remains tightened to Linux distribution used on the final environment target.</li><li>Software versions (PHP, Elasticsearch… ) are not easy to change/upgrade because they may also be dependant of the distribution.</li><li>We had a working CI with Jenkins / Gitlab Runner but building a CD pipeline was complicated.</li><li>This does not allow us to have a proper “bookshelf” where we could find inheritable boilerplate components when starting a new project.</li><li>Not easy to scale up or down since it requires adding a new OpenVZ container and provisioning it with the recipes.</li><li>We were also unable to start sandboxes or ephemeral environments for parallized testing of different features.</li></ul><p>For the developer side, LXC was a real step forward, but to be honest it’s not so easy to tweak, and we can’t deploy them as is. We still need to have deployment environments (staging, production, …) that will be different from the developer computer.</p><p>This is of course challenging for our goal : to support a Magento a service, creating new instance must be easy as few clicks. And as consequence the execution environment specifications must be the same from developer’s computer to highly-available production servers</p><h3>DevOps to the rescue</h3><p>There is many different definitions of what means DevOps. Some of them focus on the tooling, or focus on a methodology, others that this is a philosophy…</p><p>Here is how at Smile we are thinking DevOps:</p><ul><li>The goal is to make Dev (developers) and Ops (operators, system admin) <strong>communicate</strong> smoothly and using the same tooling</li><li>A way to accelerate and facilitate automation of every task that can be automated</li><li>A software deployment impact must be predictable, and can be achieved by a developer or any person with the access right to the target environment</li><li>Ops can provide segmented, controlled and monitored environments and support developers in their activities</li></ul><p>We can resume that DevOps is combination of cultural philosophies, practices, and tools that increases an organisation’s ability to deliver applications and services at high velocity.</p><blockquote>To create a unique channel where Dev and Ops can communicate and work, we just need to have methods, tools and <strong>determination</strong>.</blockquote><p>Usually, the first tool that enter in DevOps conversation is a <strong>CI platform</strong>, Jenkins is a well-known one but you can also use GitLab-CI (with “runners”). We’ve got both at Smile, following project constraints we can choose either the first or the second, but sometimes we use both for one project.</p><p>Then you need to deploy your project in a testing and staging environment. Until now, we pushed the code on the server and we passed scripts to make migrations. Ok, nice but not efficient in time, in comprehension, and when it won’t work that’s hard for a developer to locally reproduce the bad behavior.</p><p>But with Docker and a container platform, it changes the situation.</p><h4>Dock me up !</h4><p>Some of the concepts that come with the DevOps approach like immutability and idempotence are important for what we are trying to do :</p><ul><li>Immutability : to ensure that each software or infrastructure components are replaced for every deployment rather than being updated in-place</li><li>Idempotence : to ensure that a change applied several times will always give the same result</li></ul><p>And containers are made to support these concepts.</p><p>Today, <strong>Docker</strong> is the king of containers solution. The war is won. With the ease of <em>Docker-Compose</em> mixed with <em>Dockerfiles</em>, everything is more flawless, adaptable and easy to extend. Docker come also with a rich ecosystem.</p><p>Docker Containers allow us to change Linux distribution, to change version of an application (database, cache server, Nginx or Apache ?), to override and test many possibilities. Docker is not as famous just for marketing reasons, it is really the most suitable tool for this kind of work.</p><blockquote>Docker is the right one to use, but what about development, tests and deployment processes ?</blockquote><p>I’m sure you’re already heard about Docker… And since several months, you couldn’t have missed articles and demo about <strong>PaaS</strong> as <strong>Kubernetes</strong>, <strong>OpenShift</strong>, or <strong>Rancher</strong>. We are already using OpenShift for a long list of services, so why not to use it for our Magento 2 developer teams ?</p><p>We have CI platforms (Gitlab CI and/or Jenkins) so the testing part will not be a problem. What we have changed are:</p><ul><li><strong>developer</strong> environment that is now using Docker</li><li><strong>deployment</strong> environment is now on OpenShift</li></ul><p>Now, let’s see what we need to create to help developers.</p><h4>Strong productivity using a PaaS + CI/CD</h4><p>PaaS (Platform as a Service) is not <em>really</em> a deployment tool, it is a platform that yields and setup environment for projects. That’s the purpose of Rancher, OpenShift or Kubernetes: you create projects (or namespaces) then you can spawn environment inside.</p><p>As Rancher and Kubernetes, OpenShift orchestrate a set of Docker containers according to some rules you have to define. Actually, Rancher and OpenShift integrates Kubernetes. OpenShift add the abilities to have its own private container registry and to build new container images on-demand.</p><p>Each deployed containers can have volumes and all of them are encapsulated in a <em>Pod</em>. To access a <em>Pod</em>, you need <em>Services</em> that makes port forwarding and load balancing. And the whole needs are automated and simple to use.</p><h4>Why to use a container PaaS to develop ?</h4><p>At first sight, the difference between VM, LXC and the use of containers is not so evident.</p><p>As I said earlier, OpenShift has got a registry and can build images. That means that Ops can prepare images, push them on the registry, and developers will use them to develop. Ok, developer pull images, then mount source in a container, and then…</p><p>What happens when developer need to push sources ?</p><p>That’s the power of <em>BuildConfig</em> and <em>DeploymentConfig</em> which are provided by OpenShift that gives advantages. Let’s check what I mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*XlppZAstcxT6vl-68BQzzQ.png" /></figure><p>The “builder” takes sources from the right branch or tag (following the given <em>BuildConfig</em> in OpenShift), then it uses initialisation scripts, build and compile translation, templates and so on… Image is pushed in <em>ImageStream</em> and then deployed as container following the “deployment configuration” (aka <em>DeploymentConfig</em> in OpenShift) taking the right image in the internal registry. What is very important to understand now is that <strong>the base image used to build an Application Image on OpenShift is the same one used by developpers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESVn123PDX0l_fHMmZPqcg.png" /><figcaption>CI-CD with Gitlab, OpenShift Containers Platform and how Developer is implied</figcaption></figure><p>Everything is automated. Developers and Administrators can check build logs, get images, and can monitor deployment logs. All that is almost without a hitch.</p><p>But Magento 2 needs more that PHP and MySQL… so let’s speak about its containerization.</p><h3>Magento 2 containerization</h3><p>We are going to speak about Magento 2 : we need it to be containerized and to be able to have high availability on the PaaS.</p><h4>Magento 2 with full services</h4><p>Actually, we need to have High Availability for <strong>the whole services list</strong>. That means : database, cache, http server, file-system… And of course everything has to be resilient and scalable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtEkWRE3MkK5MX1m-MYXDQ.png" /><figcaption>Magento2 Stack on our OpenShift containers platform</figcaption></figure><p>Quickly, that’s what we can list:</p><ul><li>MySQL — let’s use MySQL Galera to make it HA</li><li>Redis — let’s use Redis Sentinels</li><li>Http Server — we will use NGinx and PHP-FPM</li></ul><p>For the storage, Openshift provides storage volumes from different distributed FS as far as you’ve installed one. On our testing platform we are using GlusterFS, but Amazon S3 and ESB can be used, you may also use Ceph and many others.</p><p>As part of many Magento deployment and proudly develop at Smile, we also need to include <a href="http://magento-elastic-suite.io/en/">ElasticSuite</a>, which depends on Elastic Search.</p><p>On PHP container, we love to have monitors, so we added <a href="https://blackfire.io/">BlackFire</a> and <a href="https://newrelic.com/">NewRelic</a>.</p><p>Ok, do you remember that I said that developer side we will have <em>more or less </em>the same architecture ? So, you are saying to yourself:</p><blockquote>“He’s mad, so many services on a developer laptop…”</blockquote><p>And you’re right ! We decided to reduce container number to only what the developer will work, that means that we only propose to developer to get php and nginx images <strong>from our OpenShift registry</strong>. The others containers are only the monolithic version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*kypxw3_hn9wfQfuoUzsiBQ.png" /><figcaption>Container stack on developer computer</figcaption></figure><h4>Magento2 as a ready-to-use image on a bookshelf</h4><p>Since Openshift is providing us Image Streams, we are able to generate ready-to-use images.</p><p>As we have seen previously, our Magento2 container is basically a PHP-FPM container populated with the application sources.</p><p>But we needed to go further, because we wanted to have a Magento image that we are able to start <strong>in a couple of seconds</strong>, to achieve dynamic scaling in near-real time. For those who are familiar with Magento 2, you already know that on a production context, the Magento application cannot start immediately from the PHP sources and will need some mandatory steps to be processed before starting.</p><p>To do this, we decided to proceed most of the Magento prerequisites during the image building :</p><ul><li>Dependencies are installed with Magento composer.</li><li>Environment configuration is injected into the app/etc/env.php.</li><li>Production mode is enabled.</li><li>Code compilation is proceeded.</li><li>Static content is published.</li></ul><p>At this step, this means that we have a <strong>ready-to-start and fully configured Docker image for our Magento container</strong>, in which php-fpm can start immediately listening to incoming connections.</p><p>We are now able to start as many containers as we need with this image, to obtain a running pool of identical Magento application ready to handle our numerous user’s requests.</p><p>Back on the developer computer !</p><p>Our skeleton is a bit “more complex” to be fully presented. But to resume, developers can locally see this:</p><ul><li>a Makefile</li><li>a docker-compose.ymlfile</li><li>a .openshift directory with scripts and Dockerfiles</li></ul><p>To initialise the project, developers can take this skeleton, tweak Docker images (actually it’s only an override to not make it able to use another image than the provided one from our registry) and adapt scripts if needed. That all. Running “make” command will prepare environment (get images from OpenShift, call composer, install database…) with Docker.</p><p>To make it really easier and faster, we take advantage of <em>source to image</em> tool from Red Hat.</p><h4>The s2i power</h4><p>Build image can be a big effort and a very long task. That’s why Red Hat creates and gives to the community a nice tool that make things a bit lighter. Its name: <strong>Source to Image</strong></p><p><a href="https://github.com/openshift/source-to-image">openshift/source-to-image</a></p><p>That tool allows to prepare environment at the “build time” (image creation) and then at “startup time” (container start). That is a big help to let developers to integrates their own tweaks.</p><p>So, what we did is pretty simple. We created a list of scripts that should be launched at certain condition (is Magento already deployed ? Are we on OpenShift ?). Locally, we detect if Magento sources are already present, if not we call “composer” to install requirements. Then the script continues and install Magento 2 with given parameters (name of the site, admin password, …)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*-me-MnZmKosjppFfYx8lJg.png" /><figcaption>The full process of image building and deployment</figcaption></figure><p>After a couple of seconds we can see a local website that is ok to work.</p><p>Then, if the project is pushed on GitLab, the team can prepare a Magento 2 environment on OpenShift. The only needed task is to use the provided “application template” that displays a form to fill. Here, the values specific to the environment have to be specified (name of the site, number of MySQL nodes, password for admin, …) and this is <strong>now that the Gitlab project address is given</strong>. After form validation, image builder will take the given branch, build, push, and so on… Application is deployed and the init-scripts are launched. Everything that the developer saw on his computer will be executed the same way in OpenShift. Adaptations are only done to respect OpenShift conditions.</p><p>That’s all ? No… we had some problems to resolve.</p><h3>Tech problems and solutions</h3><p>First, Magento 2 initialisation is not able to use Redis Sentinels — we opened issues to explain the problem and what they answer was that we can “install Magento 2 with one redis, then change configuration afterward”</p><p>The problem is that we can’t do that on OpenShift as easily as they say. The Redis masters and sentinels are started “as is”. We can’t change Pod topology afterward, we need to make deployment in “one shot”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*PDeNAnehX08_X22n.png" /></figure><p>To fix that little problem, we decided to build a little “proxy” that makes the job. As soon as Magento 2 is able to let us work with Redis Sentinels at startup so we will remove that part. Magento 2 connect to that proxy as if it is Redis. The proxy find master and sentinels and knows if an election was made. That’s <strong>fast and scaled</strong>.</p><p>We named this project “Ellison” as from the TV show “The sentinel” where the main character name is “Jim Ellison”, you can find it here: <a href="https://github.com/metal3d/redis-ellison">https://github.com/metal3d/redis-ellison</a></p><p>Finally, we proposes Docker images to easily deploy it on OpenShift and Kubernetes from our “Redis HA” repository:</p><p><a href="https://github.com/Smile-SA/redis-ha">Smile-SA/redis-ha</a></p><h3>Conclusion</h3><p>Working with Docker and OpenShift offers a higher productivity and help a lot to avoid deployment failures. Using Docker images that are built on our platform prevent developers to have differences between their environment and the production one.</p><p>We now have a high available solution to host that solution, which is compatible with self-hosted, Amazon AWS, Google GCE, Digital Ocean, and many other machine providers. Also, <strong>a large base of our work can be deployed on Kubernetes</strong> as Openshift is running over it. But in this case we loose a part that is automated by OpenShift, that is the “Image build”. You can of course do it yourself on Jenkins/Gitlab-CI or whatever the CI platform you’re using.</p><p>We now have continuous integration platform fully integrated in the process, I mean that Gitlab-CI is not only a “testing platform”, it is now part of the deployment by communicating between GitLab and OpenShift.</p><p>Also, developers need to trained to understand new environment and processes. That’s not so complicated but we need time to teach them how they should now work.</p><p>Last… We will work on a problem that everybody here should mention: what about database migration ? Should we set website in maintenance mode while we’re doing changes ? How to insure that the deployment properly makes that step ? what about migration problem and rollbacks ? That’s the questions we’re working on !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e788b6f90ed2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/magento-as-a-service-e788b6f90ed2">Magento as a Service</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capturing your dinner, a deep learning story]]></title>
            <link>https://medium.com/smileinnovation/capturing-your-dinner-a-deep-learning-story-bf8f8b65f26f?source=rss-63647e779dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8f8b65f26f</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Patrice Ferlet]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 17:03:45 GMT</pubDate>
            <atom:updated>2018-09-27T14:43:32.074Z</atom:updated>
            <content:encoded><![CDATA[<h4>A naive approach to features extraction and R-CNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3jepQ3TqoQ3rNBnpO3wxA.jpeg" /><figcaption>“Overlay of neatly organized dragon fruit, flowers, and tropical fruit” by <a href="https://unsplash.com/@brookelark?utm_source=medium&amp;utm_medium=referral">Brooke Lark</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Working for <a href="https://medium.com/smileinnovation">Smile innovation</a> can lead to funny pre-sales research. Few weeks ago I was involved in a discussion to find out if it could be possible to recognise (and so to bill) plates and all others food items on a lunch tray.</p><p>Well, that was a challenging idea. But with the right approach and tooling I achieved to something very interesting. Let’s have a look!</p><h3>Food is so complicated</h3><p>Nowadays, capturing objects from images or videos is a very common task as many examples of images recognition explain how to find cars, cats, dogs, human… Google, Amazon, and many others provide API, libraries and models, and many researchers continue to give better and better algorithms, mathematical progress and ideas to enhance that activity.</p><p>So, checking if a given image is about food is easy.</p><p>But what if you have to guess what the food sitting on the table <strong>actually</strong> <strong>is </strong>? And what about finding every dishes, desserts, entries, bread and drink that is on the table?</p><p>In this article, you’ll see that in this particular case, this type of recognition is not so easy, why, and how I finally got to make a computer recognizing food plates.</p><p>Of course, I will speak about machine learning, convolutions, CNN, R-CNN… and OpenCV</p><h4>Detecting objects is really easy, yes really</h4><p>Since CNN became very accessible and easy to learn thanks to libraries as TensorFlow, Theano, Pytorch or Keras, we are able to read, study and make tests from a lot of tutorials, articles and videos. There are a lot of pre-trained models to ease the process, and I can now say that machine learning and convolutional neural networks are accessible for all.</p><p>Also, the first object recognition I’ve used was<em> </em><a href="https://en.wikipedia.org/wiki/Haar-like_feature"><em>HAAR like detection</em></a> from the famous <a href="https://opencv.org/">OpenCV</a> library. And if you wonder if it’s deep learning, the answer is “yes it is”. <em>HAAR like detection</em> uses a kind of wavelets convolution process to keep cascade file of object. The training is essentially the same as we can do with <a href="https://www.tensorflow.org/">TensorFlow</a>: give it a lot of example, let it learn, and try to detect.</p><p>OK, it’s easy. But is it working for any object… and food ?</p><h4>But food is complex we said</h4><p>As soon as I decided to detect plates, glasses, bottles, everything was OK. But the problems began when we started to learn what is a risotto to the model. Whatever the number of images we gave, the training tool stopped, complaining that there were not enough features. And yes, that’s right for a <em>HAAR like detection</em> model: we need good features.</p><p>Mainly, <em>HAAR like detection</em> is fast, really efficient and easy to prepare. Detection can be done in real time even on a poor CPU (see <a href="http://www.merl.com/publications/docs/TR2004-043.pdf">this paper</a> for more information). But as soon as we wanted to train a cascade to detect salads, the result was very bad.</p><p>The fact is that <em>HAAR Like detection</em> is really efficient to detect shapes (human, cat, dog, tables, chairs…) — OpenCV provides models to find, for example, faces and eyes with real-time computation. This is very easy to use, and the train phase is not so complicated. You can achieve that with a simple photo, or via your webcam with real-time display.</p><p>But as soon as the data is very heterogeneous (as pizzas ingredients, spaghetti in a plate, meat in sauce…) the efficience falls down. We spent several hours trying to find a way to adapt our capture, but nothing was really working.</p><p>And that’s what CNN (Convolutional neural network) are able to learn without any problem as far as you are using photo where the desired detected object is the main object of the scene. And that’s not always the case. Let’s talk about “features extraction”.</p><h4>The features extraction</h4><p>“Basic” CNN are able to say “ok, that’s a cat” if you give an image with a cat as main object of the scene. But when you give it an image with several objects in a complexe scene containing cats, dogs, plants, and so on in a garden, so the CNN will say “ok… 3% of cat in the image, 10% dogs, maybe a pizza there (0.3%)”. Have I said there is no pizza in the garden?</p><p>You understood the problem: CNN hasn’t checked regions of the image, it watched the entire image and tried to evaluate the scene. Actually, it is right, there is actually 3% of cat in the entire image.</p><blockquote>As the cat were not the main object, the result is not very efficient.</blockquote><p>This is why I need a process that is named “features extraction” to find regions of interest in the image, and to be able to say “OK, there is a cat in the image, but also there is 3 dogs, 2 plants and it seems that Homer Simpson is here too but I’m not sure (0.2%)”.</p><p>To successfully accomplish that task, I had several possible techniques:</p><ul><li>using R-CNN that are able to make recursion, extract features and give the list of detection with bounding boxes</li><li>extract features before to send them to a CNN, that is to say make what a R-CNN does, but our side.</li></ul><p>What’s best, what is worst?</p><p>Hard choice.</p><p>Why not try both approches, (fast and faster) R-CNN and extracting feature before sending them to a simple CNN?</p><h3>Naive approach with OpenCV: we are able to make that extraction</h3><h4>Capture simple objects and afine results</h4><p>At first, let’s make a reminder of what is a CNN.</p><p>Convolutional Neural Network is a Neural Network that have several layers, the input is a matrix of <em>[N,M]</em> shape that will be flatten and introduce in the first layer. The first hidden layers makes some convolutions, that means that they apply some little matrices as a blur or <a href="http://www.ics.uci.edu/~majumder/DIP/classes/EdgeDetect.pdf">Sobel/Laplacian</a> transformations can do. We can use several hidden convolutional layers and then send the resulting “images” (that are matrices) to the fully connected hidden layers that are “perceptrons”.</p><p>As we are making a classifier, the outputs represent categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KcG2GEe5zNOWqHHt.png" /><figcaption>Typical CNN architecture (source: wikipedia)</figcaption></figure><p>That’s pretty simple to make that CNN from scratch with <a href="https://keras.io/">Keras</a>. But as you can see, that kind of network is only efficient for <strong>one object</strong> in the image.</p><p>Looking at our food tray, the extraction should be like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*p8Trd-eBxg66teTDLhAaIw.png" /><figcaption>Feature extraction to features map</figcaption></figure><p>So, I tried to extract regions myself using OpenCV functions, and planned to use some R-CNN to suggest regions to be extracted.</p><h4>Features extraction before the CNN marshals our images</h4><p>Later in this article, you will see that R-CNN can make that work inside the neural network. But, for now, it’s very interesting to see that we can make features extraction to be able to tune and tweak.</p><blockquote>Remember: I am in a mastered environment to capture images. Light and space should be the same and we only need to extract “foods” that is on the tray.</blockquote><p>There are many ways to prepare image to get edges, shapes, and so on. The following extraction works for our environment. But it may be changed, adapted and entirely revisited.</p><p>The rules of thumb when you are in a project that has to manage data: <strong>analyze your data</strong>. There, we are working with images.</p><p>Take a look at the following sample image of a tray with foods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*KmAF-a5cDEtfpoIooi0Qfg.png" /><figcaption>Foodplate taken from <a href="http://www.lycee-freyssinet.fr/1-60-Restauration.php">http://www.lycee-freyssinet.fr/1-60-Restauration.php</a></figcaption></figure><p>The question is: how <strong>you</strong>, I mean, <strong>your brain</strong>, is able to detect where is the food even if you don’t know what “food” means ? You should notice that you are making two distinct extractions: shapes, and colors.</p><p>For the shapes, a “rounded” object is not enough, because a plate and a tangerine are both circular in a two dimensions view. But mushrooms, tangerines, and what lies in the plate are generally colorized. It’s a good track isn’t it ? And even in gray scale, the contrast helps to determine where is the food and objects, and what is not the tray or the table itself. Let’s try to use these specificity to extract “regions of interest”. To compute that regions, I will make “image pre-processing”.</p><h4>Image pre-processing</h4><p>Image pre-processing is a suite of functions you can use to enhance quality, but also to add effects as color adjustments and extraction, shape modification, and so on.</p><p>Here, I will manipulate colors, contrast, threshold, and detect borders to have a mask of needed shapes.</p><p>Before beginning, working on Jupyter, I created some helpers function to speed up the work, for example:</p><pre># return RGB and Grayscale image from a source<br>def get_image(src=&quot;./medium/test.jpg&quot;):<br>    im = cv2.imread(src)<br>    im = cv2.resize(im, (800,600))<br>    return cv2.cvtColor(im, cv2.COLOR_BGR2RGB),<br>           cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)</pre><p>RGB colorspace is not the best format to adjust saturation and colors, so we will use HSV colorspace. Making use of powerful tools such as OpenCV and the almighty Python NumPy library, that is fortunately not so complicated:</p><pre>import cv2<br>im = cv2.cvtConvert(im, cv2.COLOR_RGB2HSV)</pre><pre># # im[:, :, N] where N is the channel you need<br># 0=H, 1=S, V=2<br># let&#39;s try to make saturation + 80<br>im[:, :, 1] += 80</pre><pre># reconvert before display<br>plt.imshow(cv2.cvtConvert(im, cv2.COLOR_HSV2RGB))<br>plt.show()</pre><p>Here is a function I’m using and that works:</p><pre>def augmentation(im, fact=.0):<br>    if fact &gt; 1:<br>        fact = 1.0<br>    # get HSV<br>    hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV)<br>    <br>    # set it to numpy array<br>    hsv = np.array(hsv)<br>    h = hsv[:,:,0]<br>    s = hsv[:,:,1]<br>    v = hsv[:,:,2]<br>    <br>    # fact * channel<br>    hsv[:,:,0] = np.where(h*fact &lt;= 255, fact*h, h)<br>    hsv[:,:,1] = np.where(s*fact &lt;= 255, fact*s, s)<br>    hsv[:,:,2] = np.where(v*fact &lt;= 255, fact*v, v)<br>    <br>    # return hsv and rgb<br>    return hsv, cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)</pre><p>That function is very helpful, for example here is an image where we changed HSV channels with a factor of 1, without changing image to RGB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*GaaKoEwnfwGNP3_q8rM9iA.png" /><figcaption>HSV image — channels values increased by 10%</figcaption></figure><p>As you can see, food is already well augmented. As we are displaying HSV in RGB, the green channel corresponds to the saturation, and so you can see that, in my case, I can help food region extraction using saturation (and some other image processing I will do later).</p><p>I’m now able to find contours 🎉.</p><h4>Finding Contours</h4><p>Now the image can be “augmented”, I am able to extract the right features.</p><p>I tried several approaches:</p><ul><li>blob detection — kind of concave and/or convex shapes — that was not very efficient</li><li>convolutions — that’s what does R-CNN and that’s a good approach</li><li>structure detection — that may help a lot convolutions or contour search.</li></ul><p>Structure detection was the best option for my tests. Let me explain what I did:</p><ul><li>create structuring element as ellipsis (that is a smooth shape to detect)</li><li>use threshold to make a pure black and white extraction</li><li>dialte and erode the result to smooth edges and shape — that helps a lot the contour detection</li><li>contour detection</li></ul><p>Some code is sometimes worth a thousand words and so here is the function:</p><pre>def extract_features(im,<br>                     threshold=144,<br>                     ellsize=16,<br>                     augmentation=0.,<br>                     erosion=8,<br>                     dilatation=4):<br>    <br>    hsv, im = augmentation(im, augmentation)<br>    gray = cv2.cvtColor(hsv, cv2.COLOR_RGB2GRAY)<br>    <br>    # make 2 blurs<br>    mask = cv2.GaussianBlur(gray, (15,15), 0)<br>    mask = cv2.GaussianBlur(mask, (3,3), 0)<br>    <br>    # create structure element<br>    ellipses = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,<br>                                           (ellsize, ellsize))<br>    <br>    # get 2 masks, one closed to the edges, other makes a<br>    # kind of dilatation of the first one<br>    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, ellipses)<br>    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, ellipses)<br>    <br>    # binarize that !<br>    _, contour = cv2.threshold(mask,<br>                               threshold,<br>                               255,<br>                               cv2.THRESH_BINARY)<br>    <br>    <br>    # erode and dilate to get contours<br>    erode   = cv2.erode(contour, None, iterations=erosion)<br>    contour = cv2.dilate(erode, None, iterations=dilatation)<br>    <br>    # return the ellipsis and contour image<br>    # - ellipsis mask is returned <br>    # only to visualize what&#39;s happend<br>    return mask, contour</pre><p>Note that I also tried to make threshold before eroding and dilating the map, but in most cases I generally had not much difference between the results. But you can do it as an exercise to test your own filter sequence.</p><p>An example of output using Jupyter with widgets to find nice parameters, keep in mind that we will tweak parameters afterwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lbwm5kK4iKC3PYD0YrHZ7w.png" /><figcaption>Jupyter widget that allows us to find good values to extract a features map</figcaption></figure><p>On the left, there is the structure ellipsis result that helps creating some “blobs”. Merged together, those blobs yield bigger and simpler shapes. On the right, you can see that erosion and dilatation with threshold can split regions. I will now use that features map to get bounding boxes. Of course, we will change some values to fine tune element separation. But we now have Region of Interest (or RoI for short) and we will be able to make contour detection with OpenCV that natively proposes functions for that kind of operation.</p><p>The code below draws boxes around features.</p><pre>import imutils<br># extract features, that parameters were good enough to<br># make some tests<br>_, mask = extract_features(im, 116, 16, 141, 2, 6)</pre><pre>out = img.copy()</pre><pre># we need to invert mask<br>mask = cv2.bitwise_not(mask)</pre><pre># note that RETR_CHAIN is also usable<br>contours = cv2.findContours(mask,<br>                            cv2.RETR_LIST,<br>                            cv2.CHAIN_APPROX_SIMPLE)</pre><pre>contours = contours[0] if imutils.is_cv2() else contours[1]<br>contours = contours.sort_contours(contours)[0]<br># loop over the contours<br>MINWH = 100<br>for (i, c) in enumerate(contours):<br>    ((x, y), (w, h), _) = cv2.minAreaRect(c)</pre><pre>    # remove too small regions<br>    if w &gt; 40 and h &gt; 40:<br>        x = int(x-w//2)<br>        y = int(y-h//2)<br>        w = int(x+w)<br>        h = int(y+h)</pre><pre>        # draw a box<br>        out = cv2.rectangle(out, (x, y), (w, h), color, 2)</pre><p>One more time, Jupyter and widgets were used to check results, and we can now see a result close to the expected one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*_9MIzeo0s_xzubqdjw_SmQ.png" /><figcaption>Extracted content from our own convolution</figcaption></figure><p>So, because it’s a mastered environment, I could refine filters values to get better regions. After a while, I found good values that works with several shots. One more time Jupyter helps a lot to make tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*ehR5GtsHdwIWlM8BCd4xQA.gif" /><figcaption>Tweaked values to get nice bounding boxes</figcaption></figure><p>The function is very fast. OpenCV computes matrices and region calculation in 5-10ms.</p><p>Instead of drawing regions, you will be able to crop images to get RoI and send them one by one (or in parallel with multiprocessing) to the CNN to check which categories are detected. I only kept the best results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*mX_3LOgYaWR5I_vk7Nfdag.png" /><figcaption>OpenCV detection on 2 classes</figcaption></figure><p>On the left, I sent 2 boxes to the CNN that learned what are tangerines and gnocchi — and as expected, it found the right class for each of that boxes.</p><p>In addition, I am able to use detection with multiprocessing to reduce the time of detection. That image needed 100ms to get detected classes on NVidia 1060.</p><p>Please keep in mind, we hereby only get boxes around food and that’s very interesting, but in the real world it could be better to have more extracted regions, even if there is no food in it. The neural network will say that these regions are something else and we can deal with it. Actually, the R-CNN approach does that, it proposes regions to the detection even if the object is not what we are searching. But, you also need to not have too much regions because the number of detection process will dramatically increase and make your code working slower.</p><p>What I’ve made was a simple ConvNet with 4 layers and I trained the model with images of food. I didn’t need to have “annotated images” as our images were only one piece of food per image. Passing the image in my filter, then cropped regions are sent to my model — the precision was impressive for a simple proof of concept, <strong>near 90% of accuracy</strong>.</p><blockquote>The precision was impressive for a simple proof of concept, <strong>near 90% of accuracy</strong></blockquote><p>Conclusion for OpenCV feature extraction approach: if you really don’t want to hit R-CNN, and build a little CNN with 3 or 4 hidden layers to categorize a restricted list of objects, that method is sufficient.</p><p><strong>Pros</strong></p><ul><li>This is easy to get your own values in a mastered environment</li><li>You really understand what you do</li><li>You can adapt and add more filters to change the entire extraction without to retrain the model</li><li>You are able to create several extraction to get special regions to detect in a CNN model</li></ul><p><strong>Cons</strong></p><ul><li>There is a strong sensibility of the environment (point of view, lights, colors)</li><li>Hard to share that to others projects</li><li><strong>You manually do what a R-CNN does</strong></li></ul><p><strong>Note the last point: You manually do what a R-CNN does.</strong></p><p>The method is absolutely not bad, really. That can be very useful to separate the feature extraction and the detection in CNN when you’re environment lends itself. For example, if you want to detect each red objects in a scene, trees, or big objects, a feature extraction upstream a CNN is very useful. It may help and ease the work.</p><p>But as soon as the objects have many colors, shapes and if light moves, that kind of work is probably a waste of time. Because R-CNN will learn to extract regions for you. That is the following part.</p><h3>Use R-CNN, YOLO, Fast and Faster R-CNN, and so on</h3><p>R-CNN are “Recurrent Convultional Neuron Network” and that kind of model is very efficient. Take the time to read this article to understand how that works.</p><p><a href="https://medium.com/@smallfishbigsea/faster-r-cnn-explained-864d4fb7e3f8">Faster R-CNN Explained</a></p><p>As a reminder, R-CNN, either simple, fast or faster, are neural networks that makes back links from layer to upper layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCldOYv45Cdlaw3CryEzZg.png" /><figcaption>Backward links to send output to previous neurons</figcaption></figure><p>That way, Neural Network can propagate values to be retreated and get higher accuracy about extracted features that comes from the convolutional layers. Also, layers are not all fully connected but locally connected. The extraction region is connected to some neurons, other regions to other neurons, and so on.</p><p>So R-CNN can now propose “region proposals” that allows multiple features extractions in a “features map” that will be treated to classify multiple objects.</p><p>That’s what does that well-known R-CNN:</p><ul><li><a href="https://github.com/pjreddie/darknet">YOLO</a> — You Only Look Once</li><li><a href="https://github.com/fizyr/keras-retinanet">Retinanet</a> — that is a Faster R-CNN implementation</li><li>and many others…</li></ul><p>If you are interested to check what are the CNN/R-CNN differences, I encourage you to have a look on this article that gives a non-exhaustive list of famous models architectures:</p><p><a href="https://medium.com/@siddharthdas_32104/cnns-architectures-lenet-alexnet-vgg-googlenet-resnet-and-more-666091488df5">CNN Architectures: LeNet, AlexNet, VGG, GoogLeNet, ResNet and more …</a></p><p>There were two majors upgrades for the R-CNN: Fast R-CNN and Faster-R-CNN. While the first was an big improvement of accuracy and speed detection time, the last one is very impressive. Faster R-CNN makes use of several treatments as getting multiple scales, pyramid image and features map, and anchor boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EldjWaOp2U-k6AHlSKZbBQ.png" /><figcaption>Different schemes for addressing multiple scales and sizes. ( a ) Pyramids of images and feature maps are built, and the classifier is run at all scales. ( b ) Pyramids of filters with multiple scales/sizes are run on the feature map. ( c ) We use pyramids of reference boxes in the regression functions. Source: <a href="https://arxiv.org/pdf/1506.01497.pdf">https://arxiv.org/pdf/1506.01497.pdf</a> — Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun</figcaption></figure><p>The result proposed in the paper shows how it can be efficient and accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_Ia0sKguiQceA6YoeX_Fw.png" /><figcaption>Detected objects and precision from 0 (low) to 1.0 (high) (source <a href="https://arxiv.org/pdf/1506.01497.pdf">https://arxiv.org/pdf/1506.01497.pdf</a>)</figcaption></figure><p>The counterpart is that you’ll need a very dense image set to train the model which is not only to separate images per categories. You’ll need to get bounding boxes in a file for each object and categories. But, by the way, you can use a transfer learning implementation to use pre-trained models adding you own categories. That’s what I did with Retinanet implementation with ResNet model.</p><h4>Fast R-CNN with Retinanet and Keras</h4><p>Retinanet is R-CNN using <a href="https://arxiv.org/pdf/1708.02002.pdf">Focal Loss for Dense Object Detection</a> that aims to use ResNet model and adapt a better loss function to detect objects.</p><p>You can get RetinaNet models and package on the following github page:</p><p><a href="https://github.com/fizyr/keras-retinanet">fizyr/keras-retinanet</a></p><p>For the test, I used 5 kinds of food: tangerine, risotto, beans, bread and salad.</p><p>I needed to classify images. Retinanet proposes to use several annotation formats ad Pascal COV or MS COCO — I decided to use a simple format that is CSV. So, I had to create two files, one for the classes, and another that references the bounding boxes for images with the corresponding class.</p><p>The first one, classes.csv, contained:</p><pre>risotto,1<br>salad,2<br>little-bread,3<br>tangerine,4<br>beans,5</pre><p>And the second file, annotation.csv, described bounding boxes for each images:</p><pre>pic-037.jpg,80,20,500,120,risotto<br>pic-025.jpg,520,250,1152,953,risotto<br>pic-with-nothing.jpg,,,,,<br>pic-004.jpg,0,0,1600,1113,beans<br>...</pre><p>Of course, one image may appear several times if there is several foods on that image. We only have to record several lines describing bounding boxes for each visible food. That process was really long to do. Yes we could have uses ImageNet sets but we didn’t find enough images of food that is on our tray images. So I needed to make that myself. The web platform “Supervisely” (<a href="https://supervise.ly/">https://supervise.ly/</a>) could have been a good tool to achieve that, but I finally used “opencv_annotation” tool and made scripts to transform the resulting files to CSV files.</p><p>With my NVidia 1060 (3Go RAM), the training script provided by the project crashed frequently. So I created that python script to make it possible to work:</p><pre>import keras<br>from keras.preprocessing.image import ImageDataGenerator<br>from keras_retinanet.preprocessing import csv_generator<br>from keras_retinanet.models.resnet import resnet50_retinanet<br>from keras.optimizers import SGD, adam<br>from keras.callbacks import ReduceLROnPlateau<br>import keras_retinanet.losses</pre><pre># ... skip train generator<br># ... skip some works</pre><pre># then:<br>ts = train_gen.samples  // batch_size<br>vs = validation.samples // batch_size<br>epochs = 500</pre><pre># +1 because classes 0 doesn&#39;t exist, that will be the<br># classification to get &quot;others&quot; thing than food <br>model = resnet50_retinanet(len(train_gen.classes)+1)<br>model.compile(<br>    loss={<br>        &#39;regression&#39;    : keras_retinanet.losses.smooth_l1(),<br>        &#39;classification&#39;: keras_retinanet.losses.focal()<br>    },<br>    optimizer=SGD(lr=1e-5, momentum=.9)<br>)</pre><pre><br>lr_scheduler = ReduceLROnPlateau(verbose=1,<br>                                 factor=.5, <br>                                 monitor=&quot;val_regression_loss&quot;, <br>                                 min_lr=1e-7,<br>                                 patience=10)</pre><pre>model.fit_generator(train_gen,<br>                    validation_data=validation,<br>                    validation_steps=vs,<br>                    epochs=epochs,<br>                    callbacks=[lr_scheduler],<br>                    verbose=1,<br>                    steps_per_epoch=ts)</pre><blockquote>Note that the documentation advises to use Adam optimizer with a learning rate to 10⁻⁵ but we notice that stochastic gradient descent (SGD) with a momentum to 0.9 and learning rate to 10⁻⁵ was better with our model. As seen in the search paper “<a href="https://arxiv.org/pdf/1609.04747.pdf">An overview of gradient descent optimization algorithms</a>” page 4, the momentum in usually set to 0.9.</blockquote><p>And after a while (several hours), we finally get a model that works. Because of the lack of train data, results were not so impressive but the boxes were well placed and categorization was promising.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IIVvw1j3-dw9mmC5DcQzQg.png" /><figcaption>Keras RetinaNet result on 2 classes</figcaption></figure><p><strong>Please, take the given result image with caution</strong>: we needed to tweak the results to get proper bounding boxes as we didn’t have enough images to train, and so the result was not as reliable as the image may let you believe. Keep in mind that we needed to fix returned detection matrices and filter some that were not what we wanted. Taking all this into account, the precision we ended up with for tangerine was ~88% and salad ~65% which confirms the lack of training data and surely that we didn’t made enough learning epochs (I used 500 epochs for this test).</p><p>Actually, I didn’t train the model to learn desserts, gnocchi or bread for example. I was thus only able to detect tangerines and salads that we have annotated. Also, I really needed a bit more epochs to enhance the model detection, some of our tests were failing even if the image was containing a known food.</p><p><strong>Pros</strong></p><ul><li>Trainable features extraction, the model finds the best convolution to extract features</li><li>Adapted for many environment, your train set can have images with different lights, exposition, colors,…</li></ul><p><strong>Cons</strong></p><ul><li>Complex to tweak, the neural network is way too complex and need a large knowledge to be able to enhance or adapt it</li><li>Cannot be adapted for certain environment, especially when you haven’t enough of image to train the model</li><li>Train phase is long due to the fact that you need a lot of images (more than 500 per class) and should be manually annotated</li></ul><h3>Conclusion</h3><p>Even if the State of the Art on image detection is now R-CNN, it is not meaningless to consider a features extraction by yourself. Combining several approaches can make sense when you need to arrange and tweak your data. Data scientists sometimes adapt the inputs to have best accuracy while they’re working on Machine Learning, so why not do the same with Deep Learning on Convolutional Neural Network.</p><p>That being said, region extraction that are proposed by R-CNN are generally very good and, as I’ve said, that’s the State of the Art. It’s efficient, doesn’t need tweak and code, the only prerequisite is to have a well trained model, that means: a large image set to train the model to classify.</p><p>Keras RetinaNet seems to be a very good library to get a working model from ResNet pre-trained model, and it’s also possible to use MobileNet model that is a bit faster at the detection phase.</p><p>But to come back to the reason we did this :</p><ul><li>even with a naive approach we have been able to prove our ability to recognise the food items on the lunch tray with enough trust to bill them (&gt;80% of success)</li><li>we know that improvements will come from much more training data</li><li>we also know that this is a lab experiment and we would need to collect data from the real world (client environment) to ensure a continuous enhancement of training data</li><li>R-CNN will have to be used if the real conditions constrains (point of view, lights, colours) are too complex to fix</li></ul><h3>References</h3><h4>Papers</h4><ul><li>Rapid Object Detection Using a Boosted Cascade of Simple Features, Viola, P. and Jones, M. <br>— <a href="http://www.merl.com/publications/docs/TR2004-043.pdf">http://www.merl.com/publications/docs/TR2004-043.pdf</a></li><li>Edge Detection, Cornelia Fermüller and Marc Pollefeys <br>— <a href="http://www.ics.uci.edu/~majumder/DIP/classes/EdgeDetect.pdf">http://www.ics.uci.edu/~majumder/DIP/classes/EdgeDetect.pdf</a></li><li>Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks, Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun <br>— <a href="https://arxiv.org/pdf/1506.01497.pdf">https://arxiv.org/pdf/1506.01497.pdf</a></li><li>Focal Loss for Dense Object Detection, Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He and Piotr Dollar<br>— <a href="https://arxiv.org/pdf/1708.02002.pdf">https://arxiv.org/pdf/1708.02002.pdf</a></li><li>An overview of gradient descent optimization algorithms, Sebastian Ruder<br>— <a href="https://arxiv.org/pdf/1609.04747.pdf">https://arxiv.org/pdf/1609.04747.pdf</a></li></ul><h4>Libraries</h4><ul><li>OpenCV — <a href="http://www.opencv.org/">http://www.opencv.org</a></li><li>TensorFlow — <a href="http://www.tensorflow.org/">http://www.tensorflow.org</a></li><li>YOLO — <a href="https://github.com/pjreddie/darknet">https://github.com/pjreddie/darknet</a></li><li>Keras RetinaNet — <a href="https://github.com/fizyr/keras-retinanet">https://github.com/fizyr/keras-retinanet</a></li><li>Supervisely — <a href="https://supervise.ly/">https://supervise.ly/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8f8b65f26f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smileinnovation/capturing-your-dinner-a-deep-learning-story-bf8f8b65f26f">Capturing your dinner, a deep learning story</a> was originally published in <a href="https://medium.com/smileinnovation">Smile Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>