<?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 Yan Gobeil on Medium]]></title>
        <description><![CDATA[Stories by Yan Gobeil on Medium]]></description>
        <link>https://medium.com/@yan-gobeil?source=rss-904ad8530778------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*CC1154t-drmyu8ZlsNE-Ew.jpeg</url>
            <title>Stories by Yan Gobeil on Medium</title>
            <link>https://medium.com/@yan-gobeil?source=rss-904ad8530778------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:58:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yan-gobeil/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[Python best practices even data scientists should know]]></title>
            <link>https://medium.com/geekculture/python-best-practices-even-data-scientists-should-know-b86b925b8d6b?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/b86b925b8d6b</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Fri, 27 May 2022 20:02:01 GMT</pubDate>
            <atom:updated>2022-05-27T20:02:01.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*c0au8N71529IFCV9.png" /><figcaption>Python logo from the official <a href="https://www.python.org/community/logos/">python website</a>.</figcaption></figure><h4>How to make your code as clean and readable as possible</h4><p>During my almost 3 years as a data scientist at Décathlon Canada my coding skills have improved a lot. This improvement has however been very gradual so it can sometimes be hard for me to assess what I learned up until now.</p><p>One moment when I realize how much I have learned is when I review code written by new interns or team members, who are not used to writing python code in industry. There are simple best practices that are almost always unknown to new people and this is what I want to share in this article. These are certainly useful when you write training code in a jupyter notebook, but even more when you write scripts to include your models in full projects.</p><h3>Docstrings</h3><p>The first comment I have for people is in general about the documentation of their code. It is very important to describe what each of your functions is doing, what arguments it expects and what it returns. This can be done two ways, the first of which is docstrings.</p><p>A docstring is a string that you use to describe your function. It is helpful for anyone who reads your code but also for people who use your code since the docstrings can be displayed easily by IDEs or jupyter notebooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrvsovIX4e0VXpXoUZKIKQ.png" /><figcaption>Example of docstring displayed in a colab notebook</figcaption></figure><p>Here is an example of docstring for a very simple function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce0f81bd57c2d0ed44dc79fe210cec0f/href">https://medium.com/media/ce0f81bd57c2d0ed44dc79fe210cec0f/href</a></iframe><p>You see that the string contains all the elements that were mentioned above and other people don’t have to dive into the code to know how to use the function. There are many styles that can be used but all of them include the same required information.</p><p>Docstrings can also become very useful when you want to write a full documentation for your codebase. Packages like <a href="https://eikonomega.medium.com/getting-started-with-sphinx-autodoc-part-1-2cebbbca5365">sphinx</a> allow you to automatically generate a documentation from the docstrings so you can save a lot of time.</p><h3>Type hinting</h3><p>A second way to document your functions is with type hinting, which should in general be combined with docstrings for optimal clarify. The idea here is to include the type of each argument when you define a function, and the type of the return. Here is an example for our earlier function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df70bd4e6508bbf54d103c07d0a75f39/href">https://medium.com/media/df70bd4e6508bbf54d103c07d0a75f39/href</a></iframe><p>There are various basic types, like float , int , str and bool , but it’s also possible to use type hinting with more complicated types by importing them from the Typing module. Specifying when your function doesn’t return anything is a good practice as well. Here is a more complicated example that illustrates most of the ideas of type hinting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f763178a6b405d3e65357c35f8a397b/href">https://medium.com/media/0f763178a6b405d3e65357c35f8a397b/href</a></iframe><p>In addition to being useful for people who read your code, many IDEs (like pycharm) use your type hints to help you avoid typing errors. Note however that your code will run fine even if you don’t respect perfectly your type hints. Python is not a typed language like C for example so you can only get warning messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Km42F1fygO0fbskNhzSnww.png" /><figcaption>Example of typing errors reported by pycharm</figcaption></figure><p>You can get more examples of type hinting <a href="https://medium.com/depurr/python-type-hinting-a7afe4a5637e">here</a>.</p><h3>README</h3><p>Whenever you do a Pull Request on github to push your code in production there should always be an update of the README that explains the new features that you added. Don’t write too much because it will discourage people from reading it, but make sure that everything that is needed to use your code is explained. Make sure that the general idea of your code is clear as well. The best thing to do to make sure your README is ok is to imagine yourself as a new comer to the project. What information would you need to start working with the code as quickly as possible?</p><p>On the flip side, when you start working on a new project, <strong>read the README</strong>. It is called like that for a reason. People have come to me so many times with questions that were already answered in the README that I wrote months before.</p><h3>PEP8</h3><p>This is the styling convention that is preferred for python code. It contains a lot of various rules that can be found <a href="https://peps.python.org/pep-0008/">here</a>. These are there to insure that all python code has the same style and is visually similar, no matter where it is.</p><p>It’s best to keep the rules in mind while coding but there are tools that can help you clean up your code as well. IDEs like pycharm can tell you where you should change something. Tools like autopep8 can also format your code automatically, but be careful because sometimes it can reformat your code too much and make it less readable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uW8LFIkkJ7474AvBcy_cJg.png" /><figcaption>Example where pycharm reports a PEP8 error</figcaption></figure><p>Next are a few of my favorite rules to follow.</p><h4>Imports</h4><p>This rule seems a bit annoying and not super useful at first but when you get used to it you realise that it is useful. The idea is to follow a simple organization principle for your imports. Group them in 3 blocks:</p><ol><li>Standard packages that come with python</li><li>Third party packages, that you install using pip</li><li>Local files and modules</li></ol><p>Then in each block you order the imports alphabetically. This way of writing your imports is useful for a few reasons, on top of the fact that it standardizes all your code. The third party section is where you will get the information needed to write your requirements.txt file, mentionned below. The local imports section helps you see the interdependence between your different files. Here is an example of what it should look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0a2ca759960404ea41bef36275e8cc/href">https://medium.com/media/7a0a2ca759960404ea41bef36275e8cc/href</a></iframe><p>To know if a package is native to python or not, you can just google to find its documentation. If you find the information in <a href="http://docs.python.org/">docs.python.org</a> then it is native. If the documentation is hosted somewhere else or if you can find the package on <a href="http://pypi.org/">pypi.org</a> it’s an external package.</p><h4>Spaces</h4><p>There are many rules regarding spaces that help make scripts more uniform. The idea is not that one method is better than the other. It’s just important to have a single rule that everyone follows for uniformity.</p><ul><li>Always put spaces after commas , and colons : .</li><li>Always surround mathematical operators like = , - , &gt; with spaces, except when used in keyword arguments of a function.</li><li>Don’t surround brackets like () , {} and [] with spaces.</li><li>Separate functions with two blank lines.</li><li>Avoid any trailing spaces and empty lines with spaces.</li></ul><p>Here is an example that shows many of the rules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a7818cce2cb85590d891d2ce42f36e/href">https://medium.com/media/90a7818cce2cb85590d891d2ce42f36e/href</a></iframe><h4>Naming conventions</h4><p>Python functions and variables use snake case, which is of the form my_function .There should not be any capital letters in these names and they should not start with numbers. Global variables however should be written in full caps to distinguish them from local variables. The only exception to this convention is for class names, which should use the camel case form myClass .</p><h3>Requirements</h3><p>The first important recommendation in this section is to always use a separate virtual environment when you start a new project. This can be managed with venv , conda or any other method that you want. The idea here is to start with an empty environment for your project so you can install only the packages that you need. This avoids conflicts between different versions of a package and helps you keep track of what version was used.</p><p>In addition to virtual environments you should <strong>always</strong> include a requirements.txt file in your project. This is where you record the python packages that are necessary to install to run the code, along with the versions used. If you use a virtual environment and organise your imports correctly, this list should be simple to make. Here is an example of file, where the list is ordered alphabetically for convenience.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aec778c1e601988a285b3033c2a5db7/href">https://medium.com/media/4aec778c1e601988a285b3033c2a5db7/href</a></iframe><p>There are multiple ways to specify the version that you want for a package. You can ask for the exact version with == , but keep in mind that this could cause problems when another package tries to install a different version. For example <em>tensorflow</em> requires some version of <em>numpy</em>, which could be different from the one you require. To avoid this you should use ~= to allow for a bit of variation in the package version. You can finally specify a minimum with &gt;= (or maximum version with &lt;=) if a breaking change is present in the different versions of the package.</p><p>This requirements file is essential if you want anyone else to be able to execute your code. If they use the wrong versions they may get weird errors and not be able to use your project. It is even more important when you want to deploy your code in production because the installation will be done automatically instead of manually. To install the packages using the file you just have to do</p><pre>pip install -e requirements.txt</pre><h3>Clear names</h3><p>Even if you use the correct PEP8 conventions for your variable and function names it does not mean that your code will be easy to understand. It is also very important to give them meaningful names so people can keep track of what the variables contain or what the functions do. It can be sometimes useful to specify the variable type as well in the names. Let’s look at a few examples so you can see for yourself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26c6d43ee8c3d614559798380c63efa8/href">https://medium.com/media/26c6d43ee8c3d614559798380c63efa8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96426353f81add744cec9db8881a78d2/href">https://medium.com/media/96426353f81add744cec9db8881a78d2/href</a></iframe><h3>List comprehension</h3><p>This one is a bit more advanced but it helps making your code more compact and avoid having to define many intermediate variables to do a single task. A single example of converting a loop to a list comprehension is not too impressive but when there are many of these loops in a single function you can save a lot of space by doing the conversion. Here is a simple example to show how list comprehensions work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e5aaa15459ffc969c34ca19448da1ee/href">https://medium.com/media/1e5aaa15459ffc969c34ca19448da1ee/href</a></iframe><p>It is important to be careful not to overuse list comprehensions. The end result should still be easy to read so avoid using this method for complicated calculations. Note that comprehension can also be done with dictionaries.</p><p>There are still many habits and tricks that I like to use to improve my code but this is a good sample of best practices to keep in mind when writing your code. This should become natural and you should do it automatically while you code, not after everything is done or when you get comments in a PR.</p><p>If you have other examples of important best practices pleae share them in the comments :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b86b925b8d6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/python-best-practices-even-data-scientists-should-know-b86b925b8d6b">Python best practices even data scientists should know</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How can engineering interns contribute to a data science team?]]></title>
            <link>https://medium.com/decathlondigital/how-can-engineering-interns-contribute-to-a-data-science-team-9c730aff042d?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c730aff042d</guid>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[students]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Wed, 18 May 2022 19:23:30 GMT</pubDate>
            <atom:updated>2022-05-19T15:09:13.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Students in class coding on their computers" src="https://cdn-images-1.medium.com/max/1024/0*WHDo71ZY63QVcGx0.jpg" /></figure><h4>Why data science teams should hire interns and what they should work on</h4><p>At any given time, at least 25% of the Artificial Intelligence team at Decathlon Canada is composed of interns. These interns come from various places and work on various projects but they are all very important to the team. Interestingly a large proportion of these interns are not data science students but they are instead engineering students. I will explain in this post why/how we recruit them and how they contribute to our work.</p><h3>Reasons to hire interns</h3><p>Not all companies find value in hiring interns and it is sad because there are so many good reasons to recruit students, both for the students and for the companies. Internships in data science teams in particular are so rare that they are very competitive and often end up being filled by overqualified people. Here are a few general reasons why data science teams should consider taking in more interns with a good variety of backgrounds.</p><ul><li>The first obvious reason is that interns provide big <strong>return on investment</strong>. What they lack in experience, they make up for it with enthusiasm and thirst for learning. Considering their entry-level salary and, in some cases, the availability of governmental programs to support interns integration, you get a lot of value at a reasonable cost.</li><li>Interns can work on a variety of projects. They can of course work on the team’s <strong>short term priorities</strong>, but they can also be considered like additional employees to test out <strong>long-term and risky projects</strong>. That way, you keep all your full time employees’ focus on current needs to make sure you meet expectations, while your interns do the exploratory work required to decide what challenges your team should tackle next.</li><li>An often overlooked reason why interns are useful to a team is that they can help many team members gain <strong>management experience</strong>. Indeed having different team members put in charge of some interns takes weight off of a manager’s shoulders and helps the team members become more independent and develop their leadership skills. Team members can even participate in the recruitment process if they want to gain more experience.</li><li>Interns keep your data scientists and developers <strong>sharp</strong>. A lot of them know the latest trends in data and development through their school projects and help your team not get stuck working with tools that were deprecated a few years ago.</li><li>Since internships are normally relatively short, they are <strong>not much of a commitment</strong> for the team compared to hiring a new employee. Interns who don’t meet the expectations go their separate ways after the internship. On the other hand, you often have first dip when it comes to hiring interns who performed well once they graduate. This is an important option to consider given how much work recruiting good employees is.</li><li>You get to be an integral part of their <strong>professional development</strong>. They learn the core technical skills required for the job at their school. But it’s often through internships that they discover the tasks they like, the environments they are comfortable in and the job they want to apply for after graduation. They also develop their soft skills in a few short months — it’s been incredible seeing the improvements in confidence, communication and teamwork that some interns have shown with us over a few short months.</li><li>A final reason why hiring interns is a good idea is that they can bring a <strong>fresh look</strong> to the team’s projects and work methods. Since they come and go, they get to see many different work environments and can bring the good from each to share best practices with to their new team. This is even more true for interns with varied backgrounds, who can contribute to different things.</li></ul><h3>Two types of interns</h3><p>In our team, we have interns coming from mainly two different programs who work on two different types of projects.</p><h4>COOP program</h4><p>Most of our interns come from the COOP program of the Faculty of Engineering at Sherbrooke University. This means that we post internship opportunities every semester and students apply. We then interview our favorite ones and choose which ones we want to work with. These students have to do multiple internships during their undergrad studies so most of the applicants already have some experience in tech roles. In the past, we have had interns from many different programs: computer science, computer engineering, software engineering, electrical engineering, robotics engineering, etc.</p><p>We work with Sherbrooke University because we have contacts there, but most engineering schools have similar programs where interns can be recruited. It is also possible to recruit graduate students via similar programs, as we did a few times.</p><h4>Mitacs program</h4><p>The second program that we get the most interns from is called <a href="https://discover.mitacs.ca/innovationgoals/?gclid=Cj0KCQjwg_iTBhDrARIsAD3Ib5j236gY6uj2PUJI9cAP5fKuGTiQwUmiALZRjJ7mEi8lpVD5xwDsSycaAhAHEALw_wcB">Mitacs</a>. This is a program in Canada that helps bridge the gap between academia and industry. It helps pay for up to 50% of a graduate student’s salary to allow them to work on a research project in association with a company and a university professor. The internships can vary in length so short or long term projects can be done and multiple students can even work on the same project, at the same time or one after the other.</p><h3>What do our interns work on?</h3><p>Obviously interns from our two main hiring sources work on very different types of projects but they all end up contributing to the team in their own ways.</p><h4>COOP program</h4><p>Most of our undergraduate interns are not familiar with data science. However training models and analysing datasets are not the only tasks that need to be done in a data science team. As long as the interns know python (our main working language) they can help us build and label <strong>datasets</strong>, write <strong>APIs</strong> to expose our trained models and even combine pretrained models into a working <strong>prediction pipeline</strong>.</p><p>The engineering students are also often more knowledgeable in some areas of programming than many of our team members. The best example of this is <strong>frontend development</strong>. Indeed many of our interns have worked on building web apps that allow users to use our models or get access to some of the company’s data. Many of our team members even learned a lot about frontend development by working with the interns and this has helped our team grow a lot.</p><p>Sometimes we are lucky enough to hire interns who have some experience in data science. We then make them work alongside a team member on an AI project. They can contribute by <strong>testing different model architectures</strong> or <strong>optimizing the training pipeline</strong> for example.</p><h4>Mitacs program</h4><p>Students hired via the Mitacs program are far more knowledgeable in AI since they come from academia. This is why they work with us on more <strong>long term projects</strong> where we explore cutting edge methods to understand if they can be useful to us. Their goal is to pick a current hot research topic and apply it to our company to determine if we could use it in the years to come.</p><p>Another aim of these projects is to do research that can be <strong>published</strong> in a journal or a conference. This way we increase our team and the company’s notoriety with other researchers and help our team members grow their research skills.</p><h3>Our success stories</h3><p>Everything that was mentioned so far looks good on paper but how does it work in practice? Let me share stories about our interns from the past.</p><ul><li>Our intern from Sherbrooke University <em>Nadir</em> worked on multiple projects with us. He made it his mission to work with every member of the team. He notably contributed by creating our <a href="https://medium.com/decathlontechnology/smile-detection-for-image-moderation-9b06b695f642">smile detection</a> algorithm and helping creating our <a href="https://medium.com/decathlontechnology/building-a-web-app-to-capture-sports-trends-on-instagram-a517e4c1e6cd">social listening</a> platform, which other interns contributed to afterwards.</li><li>Our <a href="https://medium.com/decathlontechnology/introducing-decavision-to-train-image-classifiers-with-googles-free-tpus-8d216db8ad53">DecaVision</a> python package was built by multiple people in the team and a few of them were interns.</li><li>Many of the AI models available in our <a href="https://medium.com/decathlontechnology/identifying-the-sport-in-an-image-using-the-sport-vision-api-2ff4d8582ee2">Sport Vision API</a> were developped by or with engineering interns. Examples are the sport vs non-sport model and the image search algorithm.</li><li>One of our Mitacs interns <em>Hasib</em> has worked on using unlabelled data to improve our image classification models. This technique is called semi-supervised learning and <em>Hasib</em> discussed it in a <a href="https://medium.com/decathlontechnology/improving-performance-of-image-classification-models-using-pretraining-and-a-combination-of-e271c96808d2">blog post</a>. We also published a <a href="https://arxiv.org/abs/2108.08362">paper</a> in an AI in sports conference.</li><li>Another Mitacs intern <em>Jeremi</em> worked on testing Graph Neural Networks to improve our <a href="https://medium.com/decathlontechnology/personalization-strategy-and-recommendation-systems-at-d%C3%A9cathlon-canada-d9cb3d37f675">recommendation systems</a>. <a href="https://medium.com/decathlontechnology/building-a-recommender-system-using-graph-neural-networks-2ee5fc4e706d">Here</a> is what he had to say about the project.</li><li>If you have doubts about whether the interns like working on the projects that we give them note that two of them have returned to do a second internship with us and another one decided to come work with us when he finished his studies.</li></ul><p><em>And you? Are you hiring interns? If not, why? If yes, what do they work on? Let us know your opinion about the place of engineering interns in a data science team.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c730aff042d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decathlondigital/how-can-engineering-interns-contribute-to-a-data-science-team-9c730aff042d">How can engineering interns contribute to a data science team?</a> was originally published in <a href="https://medium.com/decathlondigital">Decathlon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the best input pipeline to train image classification models with tf.keras?]]></title>
            <link>https://medium.com/data-science/what-is-the-best-input-pipeline-to-train-image-classification-models-with-tf-keras-eb3fe26d3cc5?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb3fe26d3cc5</guid>
            <category><![CDATA[tfrecord]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 15:05:57 GMT</pubDate>
            <atom:updated>2021-02-04T14:34:09.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWbZUXNY2IwgTHaxdd8W5g.jpeg" /><figcaption>Image taken from <a href="https://www.pexels.com/fr-fr/photo/gros-plan-de-photos-imprimees-1226721/">Pexels</a></figcaption></figure><h3>What Is the Best Input Pipeline to Train Image Classification Models with tf.keras?</h3><h4>A comparison between Keras’ ImageDataGenerator, TensorFlow’s image_dataset_from_directory and various tf.data.Dataset pipelines</h4><p>When we start learning how to build deep neural networks with Keras, the first method we use to input data is simply loading it into NumPy arrays. At some point, especially when working with images, the data is too large to fit in memory so we need an alternative to arrays. From my experience, the go-to solution to that problem is to use the tool built into Keras called <em>ImageDataGenerator</em>. This creates a Python generator that feeds the data gradually to the neural network without keeping it into memory. Additionally, it includes data augmentation features that make it a very useful tool.</p><p>This could be the end of the story, but after working on image classification for some time now, I found out about new methods to create image input pipelines that are claimed to be more efficient. The goal of this article is to run a few experiments to figure out the best method out there. The main contestants will be:</p><ul><li>tf.keras.preprocessing.image.ImageDataGenerator</li><li>tf.keras.preprocessing.image_dataset_from_directory</li><li>tf.data.Dataset with image files</li><li>tf.data.Dataset with TFRecords</li></ul><p>The code for all the experiments can be found in this <a href="https://colab.research.google.com/drive/1AYAtGuAQaE23zVg5-nHcG-L6FPPUJAJG?usp=sharing">Colab notebook</a>.</p><h3>Experimental setup</h3><p>To have a fair comparison of the pipelines, they will be used to perform exactly the same task: fine tune an <em>EfficienNetB3</em> model to classify images in two different datasets. Before describing the datasets, here is the training pipeline that is used, strongly inspired by this <a href="https://keras.io/examples/vision/image_classification_efficientnet_fine_tuning/">tutorial</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/117d2f10a7e6a733cfb4b451c05d9b91/href">https://medium.com/media/117d2f10a7e6a733cfb4b451c05d9b91/href</a></iframe><p>This code simply takes a pretrained <em>EfficientNetB3</em> and adds a classification layer on top of it with the right number of neurons. This model is then trained for 5 epochs with a batch size of 32 with each tested method. The experiments are done on Google Colab, with the hardware available with Colab Pro. The version of TensorFlow used is 2.4.1.</p><p>The first dataset used to test the pipelines is a subset of the <a href="https://storage.googleapis.com/openimages/web/index.html">Open Images Dataset</a> [1] consisting only of fruit images. The second one is the <a href="http://vision.stanford.edu/aditya86/ImageNetDogs/">Stanford Dogs Dataset</a> [2–3] with images of various dog breeds. Here is a summary of the two datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*JOR0TuzYdNfaqIGooLAs6Q.png" /><figcaption>Description of the two datasets used in the tests</figcaption></figure><p>The datasets are pretty different since one has a small number of classes with less images that are larger in size. Code to download and prepare these datasets is presented in the colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*61Hitg-9EmGniXEVgovMuQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*tMIkzWpziEAw02haWnZPgA.jpeg" /><figcaption>Examples of dog images in the Stanford Dogs Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Wfm7Hf3amJih9Xa_4WrbA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbLB3I-1nyzD_ezmN5JZvQ.jpeg" /><figcaption>Examples of fruit images in the Open Images Dataset</figcaption></figure><h3>Conclusions</h3><p>Since the rest of this article spends a good amount of time explaining the different input pipelines and some people may only care about the conclusions, here is a summary of all the experiments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*_Qs5j9GbBrL-eGflY2AKFQ.png" /><figcaption>Results obtained with the fruits dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*EzgrQmFcsG5GARjEESY69w.png" /><figcaption>Results obtained with the dogs dataset</figcaption></figure><p>The numbers clearly show that the go-to solution <em>ImageDataGenerator</em> is <strong>far from being optimal</strong> in terms of speed. The only reason to keep using it could be because of how simple data augmentation is with this method. It is however not that hard to do with the other methods, and could be worth it given the big improvement in speed.</p><p>In my opinion, <em>image_dataset_from_directory</em> should be the <strong>new go-to</strong> because it is not more complicated that the old method and is clearly faster.</p><p>Building our own input pipeline using <em>tf.data.Dataset</em> improves speed a bit but is also a bit more complicated so to use it or not is a personal choice.</p><p>Concerning TFRecords, it seems that if one is not working with TPUs they are not necessary since working directly with the image files makes no difference in performance.</p><p>The <strong>optimal solution</strong> seems to be using TFRecords with a TPU and given the increase in speed it is worth the extra trouble. The drop in accuracy comes simply from the fact that different hyperparameter combinations are efficient with the TPUs but the tests used the same as the GPU. Using the right hyperparameters lead to similar accuracies than with the other methods.</p><h3>ImageDataGenerator</h3><p>Let’s now jump into the details of each method, starting with a review of the reigning champion, which is very simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16ffec7f82a5fd606e98b86a952b0568/href">https://medium.com/media/16ffec7f82a5fd606e98b86a952b0568/href</a></iframe><p>The Keras method takes the data stored into a folder, with each subfolder corresponding to an individual class. In this example, it resizes the images and creates batches automatically. The labels are generated from the subfolder names. The ‘sparse’ format is used to have labels of the form 0,1,2,3,... because the sparse metrics are used in the model building.</p><p>The main advantages of this method are its extreme simplicity and the fact that data augmentation can be done simply by specifying the transformations (rotation, flip, zoom, etc) in the arguments.</p><h3>image_dataset_from_directory</h3><p>The next option is also pretty simple and is included in Keras as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c4afd6f94dcbe6dbfe299230fa16359/href">https://medium.com/media/9c4afd6f94dcbe6dbfe299230fa16359/href</a></iframe><p>The format of the data is the same as for the first method, the images are again resized and batched, and the labels are generated automatically. There are however no options to do data augmentation on the fly.</p><p>The main difference in this method is that the output is not a python generator but a tf.data.Dataset object. This allows it to fit nicely with the rest of the pipelining tools discussed below. For example, a prefetch of the data is done here to help make the calculations faster. Any form of data augmentation done with TensorFlow can be done on this kind of dataset. It is a bit less simple but much more customizable.</p><h3>tf.data.Dataset</h3><p>TensorFlow recommends using tf.data when working with the library to achieve optimal performance. This is a set of tools to create a dataset made of tensors, apply transformations to the data and iterate over the dataset to train neural networks. It works with any type of data, like tables, images or text. The data can be imported in multiple ways. The most common ones are NumPy arrays, python generators, CSVs, TFRecords and strings. Much more detail can be found on <a href="https://www.tensorflow.org/guide/data">Tensorflow’s website</a>.</p><p>Let’s start by showing the code used for this specific case of image classification, and then explain how it works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdae13159a34ecd07b41114843c0f7d9/href">https://medium.com/media/fdae13159a34ecd07b41114843c0f7d9/href</a></iframe><p>The first step that is done here is to format the data needed correctly before feeding it to TensorFlow. The format that is used here is a<strong> filepath</strong> and an <strong>integer label</strong> for each image. This processing is done in lines 19–22. It is <em>extremely</em> important to not forget to shuffle the list of images because the performance of the model would be greatly affected. <em>Trust me…</em></p><p><strong>Note:</strong> An alternate method is to directly get the list of files using tf.data.Dataset.list_files . The problem with this is that the labels must be extracted using TensorFlow operations, which is very inefficient. This slows down the pipeline by a lot so it is preferred to get the labels with pure python code.</p><p>The labels part is simple because the list of labels is converted to a dataset using the method from_tensor_slices , which converts any tensor-like object (numpy array, list, dictionary). The list of filenames is also converted to a dataset using the same method.</p><p>The next step is to apply the parse_image function to the filenames dataset using the map method, which applies a <em>TensorFlow function</em> to all the elements of a dataset. This particular function <strong>loads</strong> the image from the file,<em> </em><strong>converts </strong>is to RGB format if necessary and<em> </em><strong>resizes</strong> it. The num_parallel_calls argument is set to be fixed automatically by Tensorflow to increase speed as much as possible.</p><p>Once the two parts of the dataset are finished, they are <strong>combined </strong>using the zip method, which is similar to the python function with the same name.</p><p>The final step is to make sure the dataset can be iterated over correctly to train a neural network. This is done with the configure_for_performance function, which is applied directly to the whole dataset, so no need to use map . The first part of the function does a <strong>shuffle</strong>. The goal of this one is to take the next X images, where X is the buffer size, and mix them every time we pass over the dataset, This ensures that the data is shuffled differently at every epoch of the training, but since the buffer size has to be small for performance sake, it does not replace the original shuffling of the full dataset. The data is then <strong>separated</strong> in batches and then <strong>repeated</strong> forever. The last step is to <strong>prefetch</strong> some data, which preloads the data to be used in the future, to help with performance.</p><p>The output of this whole pipeline is a dataset made of tensors. To help visualizing it, we can iterate over it with the following method:</p><pre>for image, label in ds.take(1):<br>    print(image.numpy())<br>    print(label.numpy())</pre><p>The data is in tensor form so it has to be converted to usual arrays for simplicity. It is important to understand that even if <strong>one</strong> element is taken from the dataset, there are 32 images loaded because an element in this case corresponds to a <strong>batch</strong>.</p><p>This dataset can be used directly to train a neural network, as was done with the other methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdf94fb610c003ee910954df16a015e8/href">https://medium.com/media/cdf94fb610c003ee910954df16a015e8/href</a></iframe><p>The only new (and very important) thing is the steps_per_epoch argument. Since the dataset was made to repeat indefinitely, TensorFlow needs to know how many steps correspond to one epoch. This is basically the total number of images divided by the batch size, rounded up since the last batch is typically not complete.</p><h4>Going further</h4><p>As mentioned above, doing<strong> data augmentation</strong> is not hard with tf.data . The only extra step is to apply a new TensorFlow function, like tf.image.flip_left_right , to the resulting dataset. This can be customized at will, as discussed <a href="https://www.tensorflow.org/tutorials/images/data_augmentation">here</a>.</p><p>With a small enough dataset, the cache method makes the training extra fast because the data is saved in memory after the first epoch. For larger datasets, it may be possible to cache the data to a file, or use something called a snapshot, but I didn’t explore any of those.</p><h3>TFRecords</h3><p>The final complexity jump in this chain of input pipelines involves saving the images into TensorFlow Record format. This is a file format that plays especially well with TensorFlow and, since it stores the objects in binary format, training a model goes faster, especially for large datasets. This section will describe the specifics for image classification, but the <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord">TensorFlow page</a> is clear about how TFRecords work in general.</p><h4>Writing TFRecords</h4><p>Here is the code used to transform an image dataset into TFRecords.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87e591037d00dd64757bd6ec83abd2ce/href">https://medium.com/media/87e591037d00dd64757bd6ec83abd2ce/href</a></iframe><p>The majority of the make_tfrecords function is very similar to the data preparation step used before. The data consisting of filepaths and <strong>integer labels</strong>, randomized, is found using simple python code. The only difference is that the <strong>full image</strong> is loaded to be saved in the TFRecords. The TFRecordWriter method is used to write the files.</p><p>The only major addition needed to create TFRecords is in the serialize_example function. Each data point has to be transformed into <strong>Features</strong>, stored in a dictionary (lines 7–10), which are then transformed into an <strong>Example</strong> (line 12), that is finally written into a <strong>String</strong> (line 13). This is what the TFRecord files contain. The process seems complicated at first, but is actually pretty much the same for all possible cases.</p><p>The advantages of this way of working are numerous. All this processing has to be <strong>done only once</strong> and the data is ready for any training in the future. It is also easier to share, with <strong>fewer files of smaller sizes</strong>. <strong>Transformations</strong> like resizing can be done before and saved for later training, which can increase the speed. For larger datasets, the TFRecords can be split into multiple smaller files, called <strong>shards</strong>, to make the training even faster.</p><h4>Reading TFRecords</h4><p>Once the tf.data.Dataset section above is understood, reading TFRecords is easy to understand. Indeed the process is almost exactly the same. The data is loaded from TFRecords files instead of from image files, but the subsequent processing is the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c3b60b63ed8da71ec6c0d354eccd716/href">https://medium.com/media/1c3b60b63ed8da71ec6c0d354eccd716/href</a></iframe><p>The dataset is first initialized in read_dataset by reading the TFRecords file(s) with the method TFRecordDataset . The _parse_image_funtion is then applied to convert the content of the TFRecords back to images and labels. This is done in lines 2–7, where the dictionary used to create the TFRecords is used to tell TensorFlow what the contents are supposed to correspond to. The rest of the steps is the exact same processing as before.</p><p>A small detail that is introduced here because it is necessary for the next section appears in the <strong>batching</strong> step. The extra argument drop_remainder is used to drop the last batch if it is not full. This means that there is in general one less step to do in order to finish an epoch, which has to be changed in the steps_per_epoch argument of the training part.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf3496e5211cc7ce667148955e8db84c/href">https://medium.com/media/bf3496e5211cc7ce667148955e8db84c/href</a></iframe><h3>How to use TPUs</h3><p>In my opinion, the main reason why it’s worth getting familiar with TFRecords is to be able to use Colab’s<strong> free TPUs</strong>. These are made to be much faster than GPUs but are more complicated to use. It is not as simple as switching the runtime so I describe here how to do it. It is not necessary to use TFRecords, but is highly recommended.</p><p>The first roadblock is that when running on a TPU, TensorFlow 2 cannot read local files. This problem is fixed by saving the data in <strong>Google Cloud Storage</strong>. Every Google account can store a good amount of data on there for free, so it’s not much of a problem. It is also surprisingly simple to save data on GCS when using Colab and TensorFlow. The only special step needed is to authenticate your Google account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64a2912a6a9a96660a0c9ffd4c2cbada/href">https://medium.com/media/64a2912a6a9a96660a0c9ffd4c2cbada/href</a></iframe><p>If your account is authenticated, using the exact same function as before to make the TFRecords but with a <strong>GCS bucket link </strong>(of the form <em>gs://bucket-name/path</em>) does the trick. TensorFlow is smart enough to recognize that the path is from GCS and knows how to read and save the data there. One caveat is that saving the data cannot be done on the TPU since local files are necessary. Saving the data has to be done with a CPU/GPU and then it’s time to switch to a TPU for training.</p><p>Apart from the data storage, the only major difference when training with a TPU is that a small bit of code needs to be added to the pipeline (lines 10–15).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934dbef62a6b2f936c2a91581eb75d6e/href">https://medium.com/media/934dbef62a6b2f936c2a91581eb75d6e/href</a></iframe><p>For some reason, the batches have to be full to use a TPU so this is why the drop_remainder argument was used above. It is also noteworthy that much <strong>larger batch sizes</strong> are recommended when working with a TPU. These large batch sizes would make a GPU crash, but actually improve the performance of TPUs. A similar thing can be said about other hyperparameters. TPUs are different beasts, so different combinations of hyperparameters to the ones used with CPU/GPU are normally optimal.</p><h3>Final comments</h3><p>The conclusions of the experiments are already discussed at the top so before finishing I want to emphasize a few things that I learned during the whole process. The first one is the <a href="https://blog.tensorflow.org/2020/04/introducing-new-tensorflow-profiler.html"><strong>profiler</strong></a><strong> </strong>that is now part of Tensorboard. This is a very interesting tool that helps find the bottlenecks in a training pipeline. This is how I figured out that I was doing something wrong when I tried to convert the image labels using TensorFlow functions. This specific step in the data pipeline was taking 73% of the total training time, which is incredibly high, so I found a way to fix it. The training time dropped from above 200 seconds per epoch to just 45 for the dogs dataset. Without the profiler, I would have had no idea where the problem was.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyuR5CBIYllR377j5oayxQ.png" /><figcaption>example of bad input pipeline, as presented by the profiler</figcaption></figure><p>Another detail that seemed to make a good difference, especially when working with a TPU, is to <strong>parallelize</strong> the map method. Comparing with other possible improvements, this was by far the most efficient one.</p><p>Next, as mentioned above, <strong>shuffling</strong> the data is extremely important. This is related more to the math behind neural network training than with data pipelines, but I saw an increase of 10 accuracy points just by shuffling the data correctly.</p><p>Finally, one detail not mentioned anywhere in the article concerns the <strong>normalization</strong> of the data. Indeed it is common to divide an image’s pixels by 255 to only have values between 0 and 1 when training. In this case, it however looks like the normalization step is included in the EfficientNetB3 model itself, so the input must be raw pixels. As I saw before realizing this, this small detail makes a huge difference in performance!</p><h3>References</h3><p>[1] Kuznetsova, A., Rom, H., Alldrin, N. <em>et al.</em> The Open Images Dataset V4. <em>Int J Comput Vis</em><strong> </strong>128<strong>, </strong>1956–1981 (2020). <a href="https://doi.org/10.1007/s11263-020-01316-z">https://doi.org/10.1007/s11263-020-01316-z</a></p><p>[2] Aditya Khosla, Nityananda Jayadevaprakash, Bangpeng Yao and Li Fei-Fei.<strong> Novel dataset for Fine-Grained Image Categorization. </strong><em>First Workshop on Fine-Grained Visual Categorization (FGVC), IEEE Conference on Computer Vision and Pattern Recognition (CVPR)</em>, 2011.</p><p>[3] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li and L. Fei-Fei, ImageNet: A Large-Scale Hierarchical Image Database. IEEE Computer Vision and Pattern Recognition (CVPR), 2009.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb3fe26d3cc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-the-best-input-pipeline-to-train-image-classification-models-with-tf-keras-eb3fe26d3cc5">What is the best input pipeline to train image classification models with tf.keras?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Simple Is It to Build an End-to-End Item-Based Recommender System?]]></title>
            <link>https://medium.com/swlh/how-simple-is-it-to-build-an-end-to-end-item-based-recommender-system-90f6d959e7c2?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/90f6d959e7c2</guid>
            <category><![CDATA[books]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[text-embedding]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 18:50:05 GMT</pubDate>
            <atom:updated>2021-01-23T23:17:08.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*kP8ish1cyGA7WN7O.jpg" /><figcaption>A librarian’s job is pretty hard so I am trying to use AI to simplify it! Source: <a href="https://pixabay.com/fr/illustrations/livre-femme-la-biblioth%C3%A8que-4192307/">pixabay</a></figcaption></figure><h4>Collect data, train a model and deploy it using popular data science libraries</h4><p>Many websites nowadays use at least some kind of recommendation system to guide their customers towards interesting products and make them buy more. The most advanced ones (like the ones used by <em>Amazon</em>, <em>Netflix</em> or <em>Youtube</em>) can be very complicated, but it is surprisingly simple to make a decent recommendation engine from start to finish for small scale applications. This is what I want to show in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ngetvxoipkwfxfihrohs8w.png" /><figcaption>Example of two different recommendation systems used on Amazon.</figcaption></figure><p>The motivation for this project comes from my fiancée, who works in a library. It is impressive how far behind they can be regarding technology for a place promoting learning and information. The best example is the fact that they prefer calling people to tell them that their books are ready for pickup instead of sending automatic emails. Recommendation systems are obviously far in their priority list, even though they spend a large amount of time trying to find books that specific people would like to read.</p><p>With that in mind, I decided to make a POC (proof of concept) book recommendation API just to show how simple it can be to build and to use for anyone. This is an example of why no one should pass on the opportunity to improve their online services. Pretty much the whole procedure that I describe can be applied to almost any other topic, not just for books. Here is a summary of the steps that I will explain:</p><ul><li><strong>Collect</strong> the data by scraping the web using <em>beautifulsoup</em></li><li><strong>Encode</strong> the data using <em>tensorflow-hub</em></li><li>Build a <strong>nearest neighbor</strong> model using<em> scikit-learn</em></li><li>Make a <em>flask</em> <strong>web app</strong> to see recommendations</li><li>Make a <strong>REST API</strong> using <em>flask</em> to get recommendations</li><li><strong>Deploy</strong> flask app on <em>Heroku</em></li><li><strong>Publish</strong> API on <em>RapidAPI</em></li></ul><p>All of this project is done using python 3.7 and the code can be found on my <a href="https://github.com/yangobeil/book-recommendation">github</a>. The web app is available <a href="https://recommending-books.herokuapp.com/">here</a> and the app is presented on <a href="https://rapidapi.com/yangobeil/api/recommending-books">RapidAPI</a>.</p><h3>Collecting the data</h3><p>Usually the best recommender systems leverage <strong>user’s data</strong> to get good results. For example, if you really liked to watch the Lord of the Rings movies, Netflix will recommend you movies liked by other people who liked LOTR too. Another method is to recommend movies that are <strong>similar in content</strong> to the movies that you liked. The second method turns out to be less performant but is a better fit to my project for a few reasons. First, I want the API to be universal so I don’t want to focus on user data from a specific platform, which I don’t have anyway. Second, user based recommendations need to be updated often to account for the new interactions, which is too much work for a simple POC. Finally, libraries often insist on not using user data for questions of privacy so I want to show that AI is still powerful without neglecting privacy.</p><p>One thing to mention about web scraping is that not every website allows it. Be sure to read the <em>Terms and conditions</em> for the site that you want to get data from to see to what extent web scraping is allowed. If you insist on scraping a website that doesn’t allow it make sure that you don’t overload the servers (by using timeouts in your code to immitate human users for example) and that you don’t use the data commercially.</p><p>Given the goal of the project, the data that I need is a list of books with varied information about each of them. I want to focus on novels written in French and I found out that <a href="https://www.leslibraires.ca/">leslibraires.com</a> has everything I need. In addition to that, the source code is very simple so it makes it easy to scrape. This is an important criteria because some websites are built using complicated javascript that makes it very hard to extract information programmatically.</p><p>There are already many good tutorials about web scraping with beautifulsoup (for example <a href="https://realpython.com/beautiful-soup-web-scraper-python/">this one</a>) so I don’t want to detail all of my process. In general, my strategy is to go through the <a href="https://www.leslibraires.ca/categorie/litterature-LIT/?tri=plus-populaires&amp;ic=25&amp;p=1">search pages</a> for the most popular literature books to gather the webpages for as many books as possible. Then for each of these books I collect the desired data from the html code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*SDwCJzrF9QrCysIjvnpMHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*XQkVxcM0Ix7sqtovkNSUPQ.png" /><figcaption>Results from book search on leslibraires.com and example of book page.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6b253b308060275b83b2914a5b1912/href">https://medium.com/media/4e6b253b308060275b83b2914a5b1912/href</a></iframe><p>Here is an example of one of the 15k books that I collected using this script:</p><pre>{&#39;title&#39;: &#39;Kukum&#39;,<br> &#39;author&#39;: &#39;Michel Jean&#39;,<br> &#39;ISBN&#39;: &#39;9782764813447&#39;,<br> &#39;summary&#39;: &quot;Ce roman retrace le parcours d&#39;Almanda Siméon, une orpheline qui va partager sa vie avec les Innus de Pekuakami. Amoureuse d&#39;un jeune Innu, elle réussira à se faire accepter. Elle apprendra l&#39;existence nomade et la langue, et brisera les barrières imposées aux femmes autochtones. Almanda et sa famille seront confrontées à la perte de leurs terres et subiront l&#39;enfermement des réserves et la violence des pensionnats. Racontée sur un ton intimiste, l&#39;histoire de cette femme, qui se déroule sur un siècle, exprime l&#39;attachement aux valeurs ancestrales des Innus et au besoin de liberté qu&#39;éprouvent les peuples nomades, encore aujourd&#39;hui.&quot;}</pre><h3>Encoding the data</h3><p>With the biggest part of the project done, the next step is to figure out how to determine which books are similar to each other. This could be done with hand made criteria, based on the author, the genre, the number of pages and/or the year of publication for example. I however decided to use a more generic approach based on <strong>deep learning</strong>. The goal is to convert each book into a vector with fixed length to have a more mathematical way of calculating similarity. The question is now: how to generate these vectors? The answer to this question is the main difference between recommendation systems for different topics. The rest of the procedure is exactly the same once the vectors are found.</p><p>In my opinion, the piece of data that I extracted that contains the most information about the books is the <strong>summary</strong>. Fortunately for me, there are many different methods to convert text into vectors, which are called embeddings in this context. Using recent advances in deep learning, people at <em>Google</em> have trained a language model called <a href="https://tfhub.dev/google/universal-sentence-encoder/4">Universal Sentence Encoder </a>that does exactly what I want: it converts any text into vectors of length 512 that encode the meaning of the text. There is even a <a href="https://tfhub.dev/google/universal-sentence-encoder-multilingual/3">multilingual</a> version of the model, which is important to me because my summaries are in French.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBLomt7la5i2yREwVH9_kw.png" /><figcaption>Example of similarity computed using the Universal Sentence Encoder (from <a href="https://tfhub.dev/google/universal-sentence-encoder/4">TFHub</a>)</figcaption></figure><p>Using this model is as simple as can be since it was made available on <a href="https://www.tensorflow.org/hub">tensorflow hub</a>, <em>“a repository of trained machine learning models ready for fine-tuning and deployable anywhere”</em>. The following code shows how to calculate the vector embedding for each of the books in the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d93cb70e97feea303a3a2bb16cdb6c/href">https://medium.com/media/c0d93cb70e97feea303a3a2bb16cdb6c/href</a></iframe><h3>Calculating similarities</h3><p>With a vector in hand for each book, there are a few different metrics that can be used to calculate similarities. Since it is not at first obvious which one performs the best for a given dataset and encoding model, I wanted to try two of the most common ones. The first one is the <strong>Euclidean distance</strong>, which calculates the <em>distance</em> between the points represented by the vectors. Its efficiency depends highly on if the scale of the vectors is meaningful. The second metric is <strong>cosine similarity</strong>, which essentially calculates the <em>angle</em> between the vectors, neglecting their lengths. See <a href="https://www.baeldung.com/cs/euclidean-distance-vs-cosine-similarity">this article</a> for a more detailed comparison of the two metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*FuzucChbP6wnwq_zFGCqZg.png" /><figcaption>Example of the two different metrics. Here <strong>d</strong> is Euclidean distance and <strong>θ</strong> is the angle whose cosine is taken for cosine similarity. Image made by <a href="https://cmry.github.io/notes/euclidean-v-cosine">cmry</a>.</figcaption></figure><p>Using scikit-learn, the metrics can easily be calculated and a list of the most similar books can be found for each book. This process takes a few seconds and the time scales up with the number of books so it’s preferable to do all the calculations once and save the results for later use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3308e7eec299742d9f071f8fed246296/href">https://medium.com/media/3308e7eec299742d9f071f8fed246296/href</a></iframe><h3>Visualizing the recommendations</h3><p>At this point the recommendation system is finished. For each book we are able to get a list of books that are similar to it. Of course searching manually in a dictionary with 15k entries is not super efficient so building a web interface to visualize the recommendations is essential. This can be done easily with flask and some knowledge of web development. I actually explained how to do this in my <a href="https://medium.com/towards-artificial-intelligence/deploying-a-keras-model-as-an-api-using-flask-177583300073">previous article</a> about flask. Keep in mind that this strategy works for very simple applications. For more complex needs, one should switch to the usual frontend-backend setup used in web development, using for example a javascript framework for the frontend.</p><p>The idea is to make a webpage template with some html/css that contains variables which are linked to a python script. Let’s first see what my template looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab86af5ff65898d7ff21712b41a4c79d/href">https://medium.com/media/ab86af5ff65898d7ff21712b41a4c79d/href</a></iframe><p>There are a few things to explain here. First, I don’t want to bother myself with any css so I am using <strong>bootstrap</strong>. This is a web dev library containing a list of premade css classes. Using it is as simple as loading the library in the head of the html file and adding classes to the html tags. If you don’t know how it works and want a quick intro, <em>w3school</em> has a nice <a href="https://www.w3schools.com/bootstrap/">tutorial</a>. Otherwise don’t be intimidated, pure html can also do the job.</p><p>The next important thing used in the template is <strong>jinja</strong> logic. This is enclosed in curly brackets {} and is where the data from the python script is used. Three different types of logic are used in this project:</p><ul><li>Using the value of a <strong>variable</strong> in the html code with double curly braces {{ variable }} .</li><li>Looping over the elements of a list with a <strong>for loop</strong> and accessing the elements’ values</li></ul><pre>{% for element in list %}<br>  &lt;p&gt;{{ element }}&lt;/p&gt;<br>{% endfor %}</pre><ul><li>Checking if a variable is defined with an <strong>if statement</strong> and display a part of the page only if it defined</li></ul><pre>{% if variable is defined %}<br>  &lt;p&gt;This shows only if variable is defined&lt;/p&gt;<br>{% endif %&gt;</pre><p>Once the template is ready, a flask app must be made to interact with it and feed it data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bcf2ba007d5ec7da8b04105190acc96/href">https://medium.com/media/5bcf2ba007d5ec7da8b04105190acc96/href</a></iframe><p>The interaction happens in a few stages. First, a bit of python code is run (to get the list of books) and the result is sent to the template to display. Then when someone clicks on the button in the web app, some data is sent back to python (selected book) and the code in the <strong>POST</strong> section is run to compute the recommendations. The info is finally sent back to the web app, which displays the recommendations. You can explore this web app <a href="https://recommending-books.herokuapp.com/">here</a>.</p><p>To launch the app locally, just use the following code in the command line</p><pre>python app.py</pre><p>and the app can be accessed at <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a> in any web browser.</p><p>With this in hand, we can compare the quality of the recommendations with the two different metrics. An example that I like to try is <em>The Silmarillion</em> by J.R.R. Tolkien, author of the <em>Lord of the Rings</em>. Comparing the recommendations, it is pretty clear that the cosine similarity recommendations are more relevant than the euclidean distance onces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkxOw4Vhr7drQtgXLE_yCQ.png" /><figcaption>Recommendations for The Silmarillion using euclidean distance. The books don’t seem too related.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zS3bQwuC6mzYgJENp5KIdw.png" /><figcaption>Recommendations for The Silmarillion using cosine similarity. The results seem to be good since most of the suggestions are from the same author.</figcaption></figure><h3>Structuring the data into a REST API</h3><p>A web app is very useful for users who want one or two recommendations, but is not very efficient for people who want to use the engine in their own app. This is where a <strong>REST API</strong> becomes useful. It makes the data available programmatically so a script can access it at will. This can be done using the same setup in flask as the web app.</p><p>It is important to have a simple unique identifier for each book to remove any ambiguity when calling the API and interpreting the returns. Fortunately such a thing exists: the <em>ISBN</em> number. The goal is then to have an endpoint where someone requests recommendations for a given <em>ISBN</em> and receives a list of similar <em>ISBN</em>s in return. Here is the code added to the above flask app for the new endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a6f5f375ef0be593de86ec4442e0ee/href">https://medium.com/media/48a6f5f375ef0be593de86ec4442e0ee/href</a></iframe><p>There are four possible arguments available when making a call:</p><ul><li><em>ISBN</em> of the book requested. This is the only one that is required.</li><li><em>Number of recommendations</em> wanted. Defaults to 5.</li><li><em>Distance metric</em> to use. Defaults to cosine similarity.</li><li><em>Field</em> to display in the return. Defaults to ISBN.</li></ul><p>A series of conditions are checked to make sure that the arguments are in the right format. For example, the metric can either be ‘cosine’ or ‘euclidean’ and nothing else. If any of these conditions is violated, the API returns a <strong>400</strong> error with a description of the error. If everything is correct, the API returns a list of recommendations with status code <strong>200</strong>. Finally, if some other problem occurs, the python error is returned with a <strong>500</strong> error.</p><p>Let’s see an example of recommendations for the same Tolkien book as before. The distance metric is not specified so the one used is cosine similarity by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*VQAflaIflBHhDcNyU_WVDw.png" /></figure><h3>Making the recommendations available via heroku</h3><p>Having a beautiful web app and a functionnal API is nice, but if no one can use them why bother? This is where <strong>heroku</strong> comes in. Deploying your code on heroku makes it available to everyone on the internet. All you need is a free account, which can be created <a href="https://signup.heroku.com/login">here</a>. Deploying your flask app on heroku is surprisingly simple. In my opinion, the best way of doing it is via <strong>github</strong>. You put your code in a github repository and link this repo to a heroku app. You can even enable automatic deployments to keep your app up to date whenever you push modifications to github.</p><p>The only addition to the code that has to be done is adding a file called Procfile that contains the following code:</p><pre>web: gunicorn app:app</pre><p>This assumes that the flask app is located in app.py . You also have to make sure to include a requirements.txt file with all the libraries used in your flask code, including gunicorn. Then once the code is pushed to github, go to the <a href="https://dashboard.heroku.com/apps">heroku dashboard</a> and create a new app. The app name will be used in the URL so make sure that you like it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxSlFUQQd_kvfP4c8UNUSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*08gFlsCYOGIBUWeuwL7Clg.png" /><figcaption>Steps to create a new app on heroku. First click on new app and then choose a name for your app.</figcaption></figure><p>By default the app will be created with free resources. It will perform without any problem for basic apps. The only thing is that the app will go to sleep after some time so the first time someone uses it after a while it will take a few extra seconds to load. Next we connect the app to your github repository and deploy the code located there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*lkgujZaQFlB5d0_YlCBxOg.png" /><figcaption>In the deploy tab, link the github repository where the code is stored.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojo6f4hvy0vYHSvntxUmog.png" /><figcaption>In the same tab, deploy the code in a specific branch.</figcaption></figure><p>Once the code is deployed successfully, the app can be accessed the same way as before, but the URL is now based on the app’s name. For example, in my case, the full link is <a href="https://recommending-books.herokuapp.com/">recommending-books.herokuapp.com</a>.</p><h3>Publish the API on RapidAPI</h3><p>At this point, the project is pretty much done, except for maybe writing a small documentation for the API. However it might be worth sharing the API on a platform to get people to use it. One interesting platform that can be used for that is <a href="https://rapidapi.com/marketplace">RapidAPI</a>. It is a marketplace where you can find a bunch of APIs and get access keys to use them, for free or for a small fee. There are many APIs in the marketplace that can be worth discovering.</p><p>I don’t want to describe the process of adding an API to the platform since it is pretty simple. I just want to emphasize the advantages of doing so. With your API on a platform like RapidAPI, you have access to stats about how people use your product. There is also an extra layer of security added by the platform, with authentication and tests, to make sure nothing bad happens to your API. Finally, it is very simple to write a small documentation for your endpoints and users can make sample calls directly on the platform. A bonus advantage that can arrise if your API becomes popular is that you can start to ask people to pay to make calls.</p><p>The book recommendation API is available <a href="https://rapidapi.com/yangobeil/api/recommending-books">here</a> for people who want to take a look and try the RapidAPI platform.</p><p>That was a long post and I hope I didn’t lose too many people. My goal was to show you the main steps in a simple end-to-end machine learning project without detailing everything. Let me know if you enjoyed and if you want more content like this. Don’t hesitate to contact me with any question or comment :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90f6d959e7c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-simple-is-it-to-build-an-end-to-end-item-based-recommender-system-90f6d959e7c2">How Simple Is It to Build an End-to-End Item-Based Recommender System?</a> was originally published in <a href="https://medium.com/swlh">The Startup</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 Win Your NHL Pool Without Even Trying]]></title>
            <link>https://pub.towardsai.net/how-to-win-your-nhl-pool-without-even-trying-42bc03b9659?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bc03b9659</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nhl]]></category>
            <category><![CDATA[hockey]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 20:22:26 GMT</pubDate>
            <atom:updated>2021-05-28T20:16:37.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*D5-plgdDQ-vtqemV6N687Q.png" /><figcaption>I am taking part in the NHL pool organized by the Canadian Blind Hockey Association.</figcaption></figure><h4><a href="https://towardsai.net/p/category/machine-learning">Machine Learning</a></h4><h4>How I used machine learning to predict the number of points that a hockey player will score this year</h4><p>UPDATE: If you are curious, the season is now over and I finished 9th out of 119 participants, so the model performed impressively well! I will certainly try it next year too :)</p><p>With the new National Hockey League (NHL) season just around the corner, I received an unexpected invitation to participate in a pool with people from the <a href="https://canadianblindhockey.com/">blind hockey community</a>. The idea is to pick a player in each of the 24 groups of six similar players to form your team. The winner is the person whose team gets the most points during the season. After trying to choose players for a couple of minutes, I started to wonder how hard it would be to train a machine learning model that helps me in this task. In this blog post, I share how I ended up building that model and using it to make my picks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-FhUI2RWHwHsZUU24SbPg.png" /><figcaption>Example of choices that have to be made. Taken from <a href="http://officepools.com/">officepools.com</a></figcaption></figure><h3>Collecting the data</h3><p>The first step in every good machine learning project is to find some data. In my case, I had to find the player stats from a few of the previous NHL seasons. I was set in my mind that I would scrape <a href="http://nhl.com/">NHL.com</a> to get that data when I discovered that there is actually an API made by the NHL for that. It is extremely badly documented by the NHL but a random guy generously made incredible documentation with a surprising amount of detail, which can be found <a href="https://gitlab.com/dword4/nhlapi/-/blob/master/stats-api.md#people">here</a>. This is the tool that I ended up using to collect my data.</p><p>The strategy that I chose is to use data from the last 10 seasons and use the player stats from two consecutive seasons to predict the points scored in the following one. I will not detail all my code, which can be found in this <a href="https://colab.research.google.com/drive/1it07eDaWGDF8t7n3VsqW_Yua_00MBh7G?usp=sharing">colab notebook</a>, but I will describe the main steps. I first used the <em>standings </em>endpoint of the NHL API to extract the list of ids of the teams that appeared in the NHL between the 2010–2011 and 2019–2020 seasons. I then used the<em> teams</em> endpoint to obtain the rosters of each of these teams for each of the seasons of interest. This was the list of players that I would consider.</p><p>The next step was to extract as much data as possible for these players. I had to use two different endpoints for that. The <em>people</em> endpoint gave me personal information like birthday, height and weight, and the <em>stats</em> extension of the same endpoint gave me access to the hockey stats like goals, assists and games played for each of the seasons played by the player. Stats about seasons played in other leagues are actually available so I had to make sure to pick only the NHL seasons, within my range of years. Here is an example of each of the URLs that I used to collect my data:</p><pre>list of teams playing in the 2019-2020 season:<br><em>https://statsapi.web.nhl.com/api/v1/standings?season=20192020</em></pre><pre>List of players who played for the Pittsburgh Penguins (id=5) in 2019-2020:<br><em>https://statsapi.web.nhl.com/api/v1/teams/5/?expand=team.roster&amp;season=20192020</em></pre><pre>Personal information of Sidney Crosby (id=8471675):<br><em>https://statsapi.web.nhl.com/api/v1/people/8471675</em></pre><pre>Career stats of Sidney Crosby (id=8471675):<br><em>https://statsapi.web.nhl.com/api/v1/people/8471675/stats?stats=yearByYear</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oha3wqthegL_4OcyGZYGNw.png" /><figcaption>The id of the players can be found in the URL of their page on NHL.com</figcaption></figure><p>This strategy gave me stats for a total of 2115 players. Unfortunately a large number of these players have not played enough to be useful as training data so I had to reduce the list to only players who had played <em>at least 3 seasons and 100 games</em> during the decade. I also removed the goalies because they are totally different beasts from the rest of the players. This reduced the list to 1038 players.</p><p>The last step before jumping into modelling was to put the data into the format required for training, which is a list of pairs of consecutive seasons with their corresponding stats and the points scored in the following season, to be used as label. To try to make good predictions for second year players, who only have one year of history, I kept lines where one of the two seasons didn’t have any games played. This left me with 5105 lines of data.</p><h3>Data preprocessing</h3><p>I collected a lot of stats for each player and not necessarily all of them should be useful to predict the performance for next season. The data was also in a very raw format so I had to clean it up a lot. Here is the list of features that I ended up keeping and how they were processed:</p><ul><li><strong>Height</strong>, converted to inches</li><li><strong>Weight</strong> in pounds</li><li><strong>Age</strong> as of the first season of the relevant triplet</li><li><strong>Position</strong> (L, R, C, D) encoded into four indicators</li><li><strong>Goals per game</strong> played, for each of the two seasons</li><li><strong>Points per game</strong> played, for each of the two seasons</li><li><strong>Hits per game</strong> played, for each of the two seasons</li><li><strong>Shots per game</strong> played, for each of the two seasons</li><li><strong>Penalty minutes per game</strong> played, for each of the two seasons</li><li><strong>Time on ice per game</strong> played, for each of the two seasons</li><li>Fraction of 82 <strong>games played</strong> during each of the two seasons</li><li><strong>Plus/Minus</strong> total, for each of the two seasons</li></ul><p>Since the number of points is extremelly related to the number of games played, I decided to predict the number of <strong>points per game</strong> instead for the third season of the triplet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*htsFvDD0FBww1R89cjLc0w.png" /><figcaption>Summary of the data collected, after processing. This is not a direct representation of the NHL’s demography because different players appear a different number of times in these stats.</figcaption></figure><p>Even after all this data processing, there were still a few features that were not ideal. Indeed, it is known that machine learning algorithms work better when the features are small numbers between -1 and 1. This meant that I had to normalize (subtract mean and divide by standard deviation) the following features: height, weight, age, plus/minus and time on ice. It is extremelly important however to perform this normalization using the training data only to not inject information about the testing data into the model. This step was thus done after randomly splitting the full data into 85% for training and 15% for testing.</p><h3>Building a model</h3><p>Before jumping into complicated modelling, it is always a good idea to build the simplest predictor possible to use as benchmark. One idea for this setup was simply to use the points per game of the last season and <strong>assume that the player will keep the same production</strong>. Note that this is a regression task, so the losses and metrics used are not the same as when doing classification. In this case I chose <em>Mean Squared Error</em> (MSE) and <em>Root Mean Squared Error</em> (RMSE), which is simply MSE’s square root. Evaluating those metrics for the benchmark model on the test data gives:</p><pre>MSE: 0.0323<br>RMSE: 0.180</pre><p>This means that using this method, we were wrong by 0.18 points per game on average. It is not perfect for sure, but not too bad at the same time since it corresponds to 15 points on an 82-game season.</p><p>Next, the first model to always try when working on regression is <strong>Linear Regression</strong>, which I implemented using the <em>sklearn</em> library. After being fit to the training data, the model achieved the following performance on the test data:</p><pre>MSE: 0.0243<br>RMSE: 0.156</pre><p>These metrics are still not perfect, but they show a clear improvement over the simple benchmark.</p><p>Instead of playing around for hours with different sklearn models for regression, I jumped directly into <strong>Neural Networks</strong>, which I trained using the <em>autokeras</em> library for simplicity. I don’t recommend using autoML for every possible task since human expertise often beats it, but for a simple task like this one it was not worth wasting my time on manual optimization of neural network architectures and hyperparameters. To my surprise, I only got to improve the linear regression results by a tiny amount using neural networks. The best results that I achieved throughout all my tries were:</p><pre>MSE: 0.0229<br>RMSE: 0.151</pre><h3>Analyzing the model</h3><p>To summarize the model building part of the project, I ended up with two similar models that are wrong by around 12 points on average over the whole season. It is also interesting to see that predictions seem to underestimate the true values for better players and overestimate it for average players (see plot), but for my use case I only cared about comparing similar players, so this was not a huge problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*kVrKtrH66ZM2Vr-aiBfs2g.png" /><figcaption>Comparison between the predicted points per game and the true values for the test data, using the linear regression model.</figcaption></figure><p>Now that I had my final model, it was time to make predictions for the 2020–2021 season in order to win my pool! After doing the same preprocessing on the data as before and using the trained linear regression model, here are the predictions for the first set of players that I had to choose from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*fZALx5bdViKO196zHUFkRA.png" /><figcaption>Predictions for the 2020–2021 season for the first choice</figcaption></figure><p>This means that I had to pick Connor Mcdavid, who was my choice anyway! For the curious readers, here is what the model predicted for the top 5 players of the season: Mcdavid, Draisaitl, Mackinnon, Pastrnak, Kucherov.</p><p>It is interesting to see that an unknown player like Morgan Geekie enterred the top 15, but this can be explained simply by the fact that he only has 2 games of experience in the NHL, so the model must have randomly guessed his future performance.</p><h4>Improving the model?</h4><p>I am somehow satisfied with the model that I built, but there is of course still plenty of room for improvement. There are many other factors that influence a player’s performance, like his teammates and linemates. It could also be useful to consider more than two seasons in the past and to collect more data overall. Perhaps more advanced stats could also be important in understanding a player’s potential as well.</p><p>Since I was in a rush (the season starts tonight…) I didn’t focus on improving the model as much as possible. I am still curious to see how the model will perform so I will post an update later in the season for those fo you who care :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bc03b9659" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-to-win-your-nhl-pool-without-even-trying-42bc03b9659">How To Win Your NHL Pool Without Even Trying</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing DecaVision to train image classifiers with Google’s free TPUs]]></title>
            <link>https://medium.com/decathlondigital/introducing-decavision-to-train-image-classifiers-with-googles-free-tpus-8d216db8ad53?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d216db8ad53</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[decathlon]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 09:53:08 GMT</pubDate>
            <atom:updated>2020-12-11T09:53:08.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eOq2PRn4_QrJQOdElPDTQ.png" /><figcaption>Based on images found on <a href="https://pixabay.com/vectors/">pixabay</a></figcaption></figure><h4>Train your own computer vision models in a fraction of the time with Decathlon’s python package</h4><p>At Décathlon Canada, one of the main tasks of the AI team is to extract meaningful information from images. In order to do so, we have spent a fair amount of time on building a solid pipeline to train image classification models with python, using Tensorflow. My colleague Samuel already wrote a wonderful series of articles (see parts <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-1-transfer-learning-5602d3f96e6b">1</a>, <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-2-model-training-1d8d237dfb12">2</a> and <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-3-optimizing-the-accuracy-c5b3128abc4c">3</a>) about the algorithms that are used in our pipeline. To summarize, we combine the power of data augmentation, transfer learning and hyperparameter optimization to get the best models possible.</p><p>To make this pipeline as easy to use and as accessible as possible, we deployed the whole codebase as a python package that we called <a href="https://pypi.org/project/decavision/"><em>DecaVision</em></a>. We also wrote a clean <a href="https://decavision-doc.herokuapp.com/">documentation</a> that describes all the details of the library, with links to the <a href="https://github.com/Decathlon/decavision">github repository</a> and a <a href="https://colab.research.google.com/drive/1s9pnNotdPoHI4n_7OZl4zwEP9rccJ3f-?usp=sharing%2F">colab notebook</a> with examples. The objective of this article is to explain how easy it is to train a model from scratch using our package by detailing an example that we recently built: a yoga pose classifier. The trained model is deployed and is available for free on the <a href="https://developers.decathlon.com/products/sport-vision/docs">sport vision API</a>.</p><p>The idea behind the yoga pose classifier came from a request made by the communication leader of the yoga vision at Decathlon. She discovered our social listening tool (see this <a href="https://medium.com/decathlondevelopers/building-a-web-app-to-capture-sports-trends-on-instagram-a517e4c1e6cd">post</a> for more info) and found it extremely useful to find relevant images of people practicing yoga to help catch her audience’s attention. Having the possibility of identifying the specific pose on the yoga images and, as a consequence, being able to identify the most popular poses, will create a lot of value for her.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*aQebs-8Z_8mlG4a-C8r4tw.png" /><figcaption>Example of information about images in the social listening tool</figcaption></figure><h4>Why choose DecaVision?</h4><p>The main feature that sets DecaVision apart is the fact that it is optimized to work with Google colab’s free TPUs. Those are made available to democratize deep learning for people who don’t have access to heavy computing resources. They are however not easy to use at full capacity so DecaVision takes advantage of tfrecords and Tensorflow 2 to gain as much speed and performance as possible.</p><p>There are many ways to use the DecaVision package to train a model, but we describe the most efficient method, which relies on Google colab and Google Cloud Storage. You will obviously need a Google account to follow this protocole with your own data, but there is a free version of GCS if you don’t use too much storage.</p><h3>Dataset preparation</h3><p>Let’s dive directly into building our yoga classifier. The first and most important thing that we have to do is collect images of interest. There are many sources we can use to achieve that: Google images, Instagram, Kaggle, etc. This step is crucial, as there is a popular concept called GIGO (garbage in, garbage out). We suggest to go carefully through this step. Once we have at least 100 images per category, we organise them into the following folder structure on our computer:</p><pre>image_dataset/<br>  train/<br>    category_1/<br>      image_1.jpg<br>      image_2.jpg<br>    category_2/<br>      image_3.jpg<br>      image_4.jpg</pre><p>In our specific example, we are focusing on the following 18 categories: bridge, camel, chair, child, cobra, downward_dog, forward_bends, horizontal_handstand, lotus, plank, standing_forward_bend, tree, triangle, twists vertical_stand, warrior_1, warrior_2 and wheel. Our main sources are Google images and Instagram, with images of varying difficulty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVDNs_6fZ4FzY5sz3F7f8Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ojMd-ztgbPhov-hzeDxtYw.jpeg" /><figcaption>Examples of images for the warrior 1 pose. The one on the left, taken from Instagram, is clearly harder to identify than the one on the right, taken from Google images.</figcaption></figure><p>The next steps can be performed either in a local jupyter notebook or on colab, but we suggest doing it locally to have a fixed version of the dataset to experiment on instead of creating a new one for each experiment. We start by installing and importing DecaVision, ideally in a new virtual environment:</p><pre>!pip install decavision<br>import decavision</pre><p>Since so far we have only collected training data, we separate a part of our images to create a validation dataset. In our case we chose the fraction to be 10%.</p><pre>decavision.utils.data_utils.split_train(path=&#39;image_dataset&#39;, split=0.1)</pre><p>We now use the data augmentation functionality of DecaVision, which creates new images from the original ones by applying random transformations. Doing this step helps the model generalize better. It is important to perform data augmentation only on the training data. At testing time we do not apply data augmentation and simply evaluate our trained network on the unmodified testing data.</p><pre>augmentor = decavision.dataset_preparation.data_augmentation.DataAugmentor(path=&#39;image_dataset/train&#39;, distortion=True, flip_horizontal=True, flip_vertical=True, random_Crop=True, random_erasing=True, rotate=True, resize=True, skew=True, shear=True, brightness=True)<br>augmentor.generate_images(250)</pre><p>In this specific case, we use the following transformations: distortion, flip_horizontal, flip_vertical, random_crop, random_erasing, rotate,<br>resize, skew, shear and brightness. We ask the function to aim for around 250 images total per class, after augmentation. The last step to do on the local machine before jumping to colab is to zip the image_dataset folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*jf6godx2SoSp6KjElvZo1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*PJOzV1J6NslJ2sc7mN2T6A.png" /><figcaption>Example of what data augmentation does to images. In this case, we clearly see that only a part of the image was kept using a random crop and that a part of the image was remove using a random erasing.</figcaption></figure><p>The only remaining step in the preparation of the data is to transform the images into tfrecords. This a special data format that was created to play well with Tensorflow and it is essential to access the maximal speed improvements that TPUs can provide. Converting the data to tfecords could be done locally as well, but we would have to upload the resulting files manually to Google Storage so we prefer doing it directly on colab.</p><p>In a colab notebook, we start by installing and importing the package as we did above. Be careful not to activate the TPU for the data preparation step since Tensorflow is not able to access local files with a TPU. Next we upload our zip file to the notebook’s local storage (we could also use the function <strong>decavision.utils.colab_utils.download_dataset </strong>to load the dataset from Google Drive) and unzip it using</p><pre>!unzip image_dataset.zip</pre><p>As we just mentionned tensorflow cannot access local files when working with a TPU. This is why we have to go through Google Storage to train. It’s at this step that we have to create a bucket to store the tfrecords. The advantage is that the data will be stored there forever and will not have to be loaded every time we restart the colab notebook. To let colab access the GCS bucket, we have to authenticate our Google account:</p><pre>decavision.utils.colab_utils.authenticate_colab()</pre><p>We then simply use DecaVision to create the training and validation tfrecords and upload them directly to our bucket:</p><pre>generator = decavision.dataset_preparation.generate_tfrecords.TfrecordsGenerator()<br>generator.convert_image_folder(img_folder=&#39;image_dataset/train&#39;, output_folder=&#39;gs://myproject/image_dataset/train&#39;)<br>generator.convert_image_folder(img_folder=&#39;image_dataset/val&#39;, output_folder=&#39;gs://myproject/mage_dataset/val&#39;)</pre><p>The previous content of the bucket will be deleted to create the new files. By default, the images are split into 16 different files, but we can change the number of shards accordingly to create files of around 100mb. The images are resized to (299, 299) by default, which is the correct size for most of the pretrained models. However we always need to make sure that we use the correct size for the model we want to try.</p><h3>Training a model</h3><p>Now that all of the data processing is done, good job! We don’t need to repeat it again. We simply authenticate our Google account when we open a notebook and start training with the data saved directly on Google Storage. For optimal results, we can now activate the TPU.</p><p>When training a deep neural network, there are many hyperparameters that need to be tuned in order to obtain the best model, for example the learning rate or the number of epochs. DecaVision does all this testing for us with a single function:</p><pre>classifier = decavision.model_training.tfrecords_image_classifier.ImageClassifier(tfrecords_folder=&#39;gs://myproject/image_dataset&#39;, batch_size=256, transfer_model=&#39;B5&#39;)<br>classifier.hyperparameter_optimization(num_iterations=25, n_random_starts=10)</pre><p>This function starts by training a model 10 times with random combinations of hyperparameters. It then uses what it learned from these random combinations to find 15 better ones (hopefully). All these tests are printed with the results so we can choose our favorite combination at the end. Each step of training consists in training an extra layer added on top of a frozen pretrained model and then unfreezing the last block of that model to finetune it. To learn more about this technique, called transfer learning, refer to the article series mentionned in the introduction (in particular <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-1-transfer-learning-5602d3f96e6b">part 1</a>)!</p><p>The only options to choose when doing hyperparameter optimization with DecaVision are the batch size and the pretrained model. In this case, we are taking EfficientNet B5, but many others are available, like ResNet, Xception and EfficientNet B3.</p><p>Once the hyperparameters that generate the model with the best validation accuracy are found, we need to train the final model. The hyperparameters that are dictated by the optimization are the number of epochs, a distinct learning rate for each of the two steps of training, the dropout rate, the number of units in the extra layer and whether of not to do the finetuning step.</p><pre>classifier = decavision.model_training.tfrecords_image_classifier.ImageClassifier(tfrecords_folder=&#39;gs://myproject/image_dataset&#39;, batch_size=256, transfer_model=&#39;B5&#39;)<br>classifier.fit(<em>hyperparameters</em>)</pre><p>Here we do not show the hyperparameters that were found for the yoga poses classifier. The final step in the training portion is to save the model. This is as easy as using the following method:</p><pre>classifier.model.save(&#39;model.h5&#39;)</pre><p>If the extension .h5 is not specified, the model will be exported to a SavedModel format. This format can however only be used on a TPU if we save the model to GCS.</p><h4>TPU vs GPU vs CPU</h4><p>Before moving along, we would like to report the results of a small experiment that we did to make clear the fact that using colab’s TPUs is worth all the trouble. We trained a model with the same hyperparameters (except batch size, which has to be higher for TPUs and lower for GPUs for performance) on our yoga dataset (around 11k images) and tried the different processing units available on colab pro. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*fU7fdyBkPEdsD0kqrhLwiw.png" /></figure><p>The TPU available was the v2 and we averaged around 40 seconds per epoch on both steps of the training. The GPU that we tried was the Tesla v100 and we averaged only 55 seconds per epoch for the first step of training and 70 seconds for the fine tuning step. Finally, just for fun, the first epoch took more than 30 minutes on the available CPU…</p><h3>Evaluating the model</h3><p>Once a satisfactory model has been saved, it is important to use it a little before declaring victory. We can use DecaVision to evaluate the model with different tools. The simplest test to do is evaluating the accuracy on different datasets where the images are separated in a folder per category:</p><pre>tester = decavision.model_testing.testing.ModelTester(&#39;model.h5&#39;)<br>tester.evaluate(<em>path=&#39;image_dataset/val&#39;)</em></pre><p>The results that we got were an accuracy of 96% on the training set, 95% on the validation set and 83% on the test set. The model performs much worse on the test set because it was made only from Instagram images, which are harder than the Google images that make up a part of the other two datasets.</p><p>To see explicitely how our yoga classifier performs on new images that it has not seen we can just place them in a folder and use the following function:</p><pre>import os<br>categories = os.listdir(&#39;image_dataset/train&#39;)</pre><pre>tester.classify_images(<em>image_path=&#39;image_dataset/test&#39;</em>, <em>categories=categories</em>)</pre><p>This feature requires an ordered list of the possible categories, which we infer here from the training dataset itself. Here are a few examples of results for the yoga poses classification model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*KOEwT7eKSJ_j6ZnhR7DrXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*NgbaG4M_E_PNnlsL2fohSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*QmyAhgfYj4eOBq3IpG0llQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*69wsG78hS4mFcv4PRjTZJA.png" /><figcaption>Examples of predictions from our best model.</figcaption></figure><p>In order to determine if the model makes more mistakes repeatedly on certain categories, we can plot the confusion matrix:</p><pre>tester.confusion_matrix(<em>path=&#39;image_dataset/val&#39;</em>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*B171IoGHltlSkwDn9OUIOQ.png" /><figcaption>Confusion matrix evaluated on the validation set.</figcaption></figure><p>For the yoga classifier, we can see that the model sometimes confuses bridge with wheel and forward bend with child. As a human, this is to be expected since the poses look pretty similar. If we found something unexpected in the confusion matrix, it would be an indication to take a second look at the dataset. In any case, we can know which classes to focus on when trying to improve the model.</p><p>A final method of assessing the reliability of the model is by directly looking at images that it makes mistakes on:</p><pre>tester.plot_errors(<em>path=&#39;image_dataset/val&#39;</em>, <em>num_pictures=9</em>)</pre><p>Once we are sure that the model is satisfactory, the final step is to deploy it. We will save the story of how we did this for another time. Do not hesitate to try out the model for yourself!</p><h3>The actual process</h3><p>The steps explained above seem simple and straightforward but of course reality is not like that. The process of building a satisfactory image classification model is iterative, which means that we have to repeat the same steps many times.</p><p>In the case of classifying yoga poses, we started with only 10 easy poses and no data augmentation to assess the difficulty of the task. We ended up with a very good model surprisingly fast so we decided to add poses to reach 18. We were not satisfied with the model that we got from that data, even after a lot of hyperparameter tuning, so we decided to use data augmetation. The final model that we obtained was satisfactory enough to deploy online, but we can still see a few categories that need improvement just by looking at the confusion matrix. We will work on improving the model in the future.</p><h3>We are hiring!</h3><p>Are you interested in computer vision and the application of AI to improve sport accessibility? Luckily for you, we are hiring! Follow <a href="https://developers.decathlon.com/careers">https://developers.decathlon.com/careers</a> to see the different exciting opportunities.</p><p>Let us know if you have any comment or suggestion about the topic of this article and don’t hesitate to share it with your network if you liked it :) If you have any idea to improve the package, don’t hesitate to take a look at the github repository to see how you can contribute to the project.</p><p><em>A special thanks to the members of the AI team at </em><a href="https://decathlon.ca/"><em>Décathlon Canada</em></a><em> for the comments and review, in particular Samuel Mercier, Heri Rokotomalala and René Lanciné Doumbouya.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d216db8ad53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decathlondigital/introducing-decavision-to-train-image-classifiers-with-googles-free-tpus-8d216db8ad53">Introducing DecaVision to train image classifiers with Google’s free TPUs</a> was originally published in <a href="https://medium.com/decathlondigital">Decathlon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a web app to capture sports trends on Instagram]]></title>
            <link>https://medium.com/decathlondigital/building-a-web-app-to-capture-sports-trends-on-instagram-a517e4c1e6cd?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/a517e4c1e6cd</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[social-listening]]></category>
            <category><![CDATA[decathlon]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 17:17:29 GMT</pubDate>
            <atom:updated>2020-09-08T17:17:29.072Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Decathlon capitalizes on social listening</h4><p>One of the strengths of the Artificial Intelligence team at Decathlon Canada is extracting information from images. In the past we have spent a good amount of time building algorithms to analyse sports images (see, for example, parts <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-1-transfer-learning-5602d3f96e6b">one</a>, <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-2-model-training-1d8d237dfb12">two</a> and <a href="https://medium.com/decathlondevelopers/how-you-can-build-an-image-classifier-in-one-day-part-3-optimizing-the-accuracy-c5b3128abc4c">three</a> of our image classification story). This has lead us to release the <a href="https://developers.decathlon.com/products/sport-vision/docs">Sport Vision API</a>, which can be used to extract the following data from an image:</p><ul><li>If a sport is displayed or not</li><li>Sport practiced</li><li>Location (indoor/outdoor)</li><li>Sport equipments displayed and their color attributes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ah7NQ2McbPEYidVGehm_Xg.png" /></figure><p>Of course all this information is cool to have, but the question is: what do we do with it? In this post I will describe how we leveraged this information to build a social listening web app.</p><h3>What is social listening?</h3><p>Social media platforms like Facebook, Twitter and Instagram have become an integral part of our lives in the past years, so much so that <a href="https://datareportal.com/social-media-users">“as of July 2020, more than half of all the people on Earth use social media”</a>. The users of those platforms are highly active. As we can see from <a href="https://www.socialmediatoday.com/news/what-happens-on-the-internet-every-minute-2020-version-infographic/583340/">this source</a>, every minute, 147k images and 347k stories are uploaded to Facebook and Instagram, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loYPqr3mi-oBxYfWTQX-ig.png" /><figcaption>There are more than 950k posts on Instagram that contain #decathlon</figcaption></figure><p>Given this huge amount of content created continuously, the data that can be obtained about social media users is pretty much infinite. Obviously a large part of these users are consumers so, as a company, it is worth asking what kind of information we can collect that would be useful to us. Monitoring social media to gain insights about how you can improve your brand is known as social listening.</p><p>There are in fact many different reasons that can motivate a company to do it. In our case, we wanted to know what people think about the Decathlon brands, how customers are using our products and even find influencers to work with. We also wanted to use social media to collect statistics about sports popularity per country and language, and find images to use in marketing campaigns.</p><h3>“Listening” to Instagram images</h3><p>The most popular way of listening to social media is to look at what people are writing. Given the expertise of our team, we decided to follow another direction and look at the images that people post online. We focused our attention on the obvious media to use: Instagram.</p><p>We built a web app that effectively works as a search engine. There are various fields that can be selected which then displays images from Instagram that correspond to the chosen fields. The different possibilities are the following:</p><ul><li>Hashtag, from a list of Decathlon brands (kalenji, domyos, artengo, etc)</li><li>Sport, from a list of 152 (taken from our <a href="https://developers.decathlon.com/products/sports">Sports API</a>)</li><li>Location (indoor/outdoor)</li><li>Language of the caption</li></ul><p>The user can also decide if they want images posted in the last week or the last month. An option to have only trending media, as characterized by Instagram, is there as well. Finally, an advanced search option allows to write any sentence and the images that correspond the most to the description are displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy360Zv99cxKCIxqGwzJkg.png" /><figcaption>Menu to search images on Instagram</figcaption></figure><p>Once the request is done, the images are displayed on a grid along with links to download them or to go directly to the post to see more details and an indicator if the post is trending. Clicking on a specific image shows the information that was collected on it and that was used for the search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FaRyEjXqiYz1D-IE18pEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dv8fBIB1ks7RMsG8p4c-tw.png" /><figcaption>Example of results obtained when searching for images of kayaking with #decathlon posted in the last month.</figcaption></figure><p>An example of a direct application for this app is if the social media team of Decathlon Italy wants to promote their yoga products. They can make a search for images of yoga, with captions in Italian and focus on the trending posts. The results can then be used to find user generated content to share in their communications to the customers or even influencers to work with to promote their products.</p><h3>How we do it</h3><p>Now that you know what the app looks like and what it does, let me describe a bit more how we collect all the information and where the AI comes into play. The main tool that we use is the <a href="https://developers.facebook.com/docs/instagram-api/">Instagram API</a>. It allows us to collect daily all the images that were posted in the last 24 hours with specific hashtags. We can get some interesting data about each of these posts, like the caption (from which we can extract the hashtags), the number of likes and the date of publication. Another tool of the API gives us a list of trending posts for our desired hashtags, so we can add a trending tag to some images.</p><p>After getting the images, we feed them to the different endpoints of the Sport Vision API that give us all the information mentionned above about their contents. We also use a <a href="https://detectlanguage.com/">Language Detection API</a> to detect the languages of the captions. The final step is to compute a vector representation for the images, that is used in the advanced search. Without going into too much details, this is done using a pretrained neural network (SBERT) that takes all the words characterizing the image (sport, caption, objects, etc) and combines them. All the information is finally saved in a database.</p><p>Only the images that are labelled as sport are considered when performing a search. This search is actually performed in two steps. If a sentence is written in the advanced search, it, along with all the words in the search fields, are encoded into a vector using the neural network. The vectors in the database that are the closest to that query vector are returned and the filters are applied to get only the relevant ones. If no advanced search is done, the research is done simply based on comparing the values of the fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeldONJo4BLPP_FmCAmOWg.png" /><figcaption>Results of a search for top media with “swimsuit” in the advanced search. Returned images most likely contain a swimsuit or have mentions related to swimsuits in their captions.</figcaption></figure><p>For those interested in the technical details, the app is split into three components: the cron tasks, the backend and the frontend. All of them are hosted on Heroku. The cron tasks use the scheduler on Heroku to run a python script daily to perform all the data collection. The information is then saved in a MongoDB database in the cloud, which is called at will by the backend, also written in python. The frontend is written using vue.js (more specifically vuetify) and calls the backend for information.</p><h3>Future steps</h3><p>So far our tool looks great and is functional, but it is still at its first stages. We are working with testers to check for performance and get feedback on useful features that we could add. In the future we plan on monetizing the app to sell it to users accross the Décathlon network. This will be a big step and there will be a lot of work involved to achieve it.</p><p>An aspect of the app that I did not discuss is the statistics that we collect. Indeed we have pages displaying plots that show the number of posts per hashtag and the most popular sports for each hashtag. There are also plots with information collected from other sources. We study the popularity of sports based on the number of searches on Google and the number of tweets that mention the sport, separated by countries. We have plans to add new sources of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vE_t_BcQ97sgzn1GFzL6Ug.png" /><figcaption>Top 10 most popular sports in the images with #decathlon posted in the last month.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASViqtjd1w3yEsNusAeErQ.png" /><figcaption>Top 5 most popular sports in Canada in the last week, based on Google searches.</figcaption></figure><h3>We are hiring!</h3><p>Are you interested in computer vision and the application of AI to improve sport accessibility? Luckily for you, we are hiring! Follow <a href="https://developers.decathlon.com/careers">https://developers.decathlon.com/careers</a> to see the different exciting opportunities.</p><p>Let us now if you have any comment or suggestion about the topic of this article and don’t hesitate to share it with your network if you liked it :)</p><p><em>A special thanks to the members of the AI team at </em><a href="https://decathlon.ca/"><em>Décathlon Canada</em></a><em> for the comments and review.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a517e4c1e6cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decathlondigital/building-a-web-app-to-capture-sports-trends-on-instagram-a517e4c1e6cd">Building a web app to capture sports trends on Instagram</a> was originally published in <a href="https://medium.com/decathlondigital">Decathlon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python utility functions for computer vision]]></title>
            <link>https://medium.com/data-science/python-utility-functions-for-computer-vision-640a7302eeb0?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/640a7302eeb0</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 16:06:12 GMT</pubDate>
            <atom:updated>2020-04-20T18:54:18.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVAWlelg6JEgpGrNBFX0pg.png" /></figure><h4>How to save some time managing your images when working on image classification.</h4><p>If you spend enough time working on computer vision using deep learning, you’ll know that there are some code snippets that come back again and again when managing your images. If you are like me and you are tired of always writing python code to go through a list of images separated into categories in a dataset or building a NumPy array from your images, this post will be useful to you. I will also explain how to build a module that can be imported from any script on your machine with your most used functions.</p><h3>Adding a module to PYTHONPATH</h3><p>Before describing the functions that I think are useful when dealing with images, I want to explain how you will be able to call them from any script without having to rewrite the code. This will be done by writing all your functions in a script and adding the location of this script to your computer’s environment variables. More specifically you want to add a new variable called PYTHONPATH. The path that you specify for this variable will be included in the directories that python searches when you import a module. If you want to see a list of these directories, you can use the following code in a script or a notebook</p><pre>import sys<br>print(sys.path)</pre><p>The first step is to write all your functions and classes, including the imports, in a script. As an example, let’s call this script myutils.py. Secondly you have to add the location of this file to your environment variables. Instead of reinventing the wheel I point you towards <a href="https://bic-berkeley.github.io/psych-214-fall-2016/using_pythonpath.html">this source</a> that explains how to do it in detail, for any operating system. The last step is simply to import your newly created module from another script as you would do with any other module:</p><pre>import myutils<br>myutils.some_function()</pre><p>or</p><pre>from myutils import another_function<br>another_function()</pre><p>Note that it is very important in this context to write some documentation for your functions. You will not have access to the code when importing the module and it will be hard to remember what the function does exactly and what the arguments mean. I will not include my docs here just to avoid cluttering the code and avoid repetitions with the explanations in the text.</p><h3>Requirements</h3><p>Before diving into the functions directly it is important to list the packages that are required to be able to run these functions. All of them are standard data science packages and they should be imported at the top of the utilities script. They will not have to be imported again when you import your module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/211ffee3a8b7397e48c283c1703d4b2e/href">https://medium.com/media/211ffee3a8b7397e48c283c1703d4b2e/href</a></iframe><h3>Loading an image into a NumPy array</h3><p>The first function that I want to introduce is pretty simple but will be useful for other functions and can easily avoid a lot of repetition in your code. The code is the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdcaf56c74f64445bc8634b9653457c3/href">https://medium.com/media/cdcaf56c74f64445bc8634b9653457c3/href</a></iframe><p>This function is used to load an image and resize it using a specific interpolation method. The interpolation part doesn’t sound very useful, but it turns out that tensorflow and tf.keras don’t use the same methods by default so it can become useful to keep track of which one is used. The image is then converted to a numpy array, its pixels are normalized to be between 0 and 1 and a dimension is added. These last steps are necessary to use these images as inputs to a neural network.</p><h3>Split a dataset into training and validation sets</h3><p>The first step in all good image classification project is to get a dataset and organize it into different folder, one for each of your classes. Once this is done you will want to split this data into train and val sets to be able to assess the performance of your deep learning model. This can be done by using the train_test_split function that sklearn provides. This however only works on numpy arrays but it can be useful to have a more permanent split, done directly on your images. This is what the following function does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4da2fdcaf83baf7c3da2eb489ad9b7/href">https://medium.com/media/5a4da2fdcaf83baf7c3da2eb489ad9b7/href</a></iframe><p>This function simply takes as input the path to the images. These need to be in a directory called “train”, in which each folder represents a class. The function takes a certain fraction of the images in each class, determined by the argument “split”, and moves them to a newly created directory called “val”.</p><h3>Create numpy dataset from directory of images</h3><p>Once you have your dataset, there are generally three ways to input the images into a tf.keras neural network: as numpy arrays, using keras generators or using tfrecords. The first option can be annoying to do so the following function takes care of the necessary steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee285a5b3a1c06f8023cbb9e6149dfae/href">https://medium.com/media/ee285a5b3a1c06f8023cbb9e6149dfae/href</a></iframe><p>Again to use this function the images must be separated into folders that are each dedicated to a class. Examples of directories to use as input are the train and val that are created using the previous function “train_split”. All the images are loaded into numpy arrays using “load_image” and are combined into one big array. An array of labels is also created from the division into folders. The categories are numbered from the order that the folders are in (normally alphabetical). If the “onehot” argument is False, each label is simply the number of the category. If “onehot” is True, each label is converted to a one-hot encoded vector.</p><h3>Looking for duplicate images</h3><p>Sometimes when you make your dataset yourself you end up with many copies of the same image. If your dataset is small this can be handled manually, but if you have thousands of images it becomes a problem. This is why I built a class to find duplicates and delete them. There are already many scripts that do this online. This is definitely not the best one but one of the things that I like is that it’s ok if your data is already split. Duplicates will be found even if one image is in the train directory and the other is in the val. Also, the comparison between images is done as numpy arrays, so even if it is slower it is more accurate than using hash. Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b633f4a5bb6cf25603862a5ee1d63f3/href">https://medium.com/media/4b633f4a5bb6cf25603862a5ee1d63f3/href</a></iframe><p>The only input of this class is the directory where the images are. All the images in the directory will be checked, no matter at what level they are located. When the class is instantiated there will be a dictionary created where the images are separated according to their size. You can then use the method “find_duplicates()” to obtain the list of images that appear more than once. Once this is done the method “show_duplicates()” allows you to visualize the images that are present more than once and you can use the method “delete_duplicates()” to delete these images.</p><h3>Apply a generic function to images</h3><p>The last function that I want to discuss seems simple at first but is very generic so the strategy can become pretty powerful. The idea is again to work on images that are separated in folders according to classes. This function goes through all the images and applies a generic function to them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29971bd81b59ce2d3f2693d71fd350bb/href">https://medium.com/media/29971bd81b59ce2d3f2693d71fd350bb/href</a></iframe><p>The first argument is the path to the directory where the images are located. Again an example is train or val. The argument “do” is any function that you want that takes as first argument the path to an image. The *args part refers to any parameters that you want. Whatever you write there when using the function will be used as arguments for the function do. These must be given as unnamed parameters. If you wanted to specify named arguments, you would have to use *kwargs. The difference comes down to the difference between things like “function(2)” and “function(number=2)”.</p><p>I think an example is required here. Let’s say I want to print the filename along with a keyword. I would define a function and give it as an argument to “work_with_files” as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/993c5eb0650a16f96d46f0ad444b6a50/href">https://medium.com/media/993c5eb0650a16f96d46f0ad444b6a50/href</a></iframe><p>The output of this call would look like this:</p><pre>filename: image1.jpg<br>filename: image2.jpg<br>filename: image3.jpg<br>...</pre><p>I think these functions are simple but used often enough that it is worth sharing them with people. Hopefully, someone will benefit from the things that I learned by spending a lot of time manipulating images with python. Let me know if you have any comment or questions :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640a7302eeb0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/python-utility-functions-for-computer-vision-640a7302eeb0">Python utility functions for computer vision</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From theoretical physicist to data scientist]]></title>
            <link>https://medium.com/data-science/from-theoretical-physicist-to-data-scientist-d8b781462c9?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b781462c9</guid>
            <category><![CDATA[phd]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[jobs]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 18:05:15 GMT</pubDate>
            <atom:updated>2020-01-15T23:55:30.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yu801cU34rbQa-XX" /></figure><h4>How I became a data scientist with a PhD in theoretical physics</h4><p>There are a lot of stories out there of people who explain how they became data scientists but I found it hard when I did the transition to find one that corresponded to my profile. This is why I want to share my journey just in case it could inspire someone else going through the same thing. I decided to pursue a career in data science a little more than a year ago (during the fall of 2018) and I am now a data scientist at Décathlon Canada so I achieved my goal. I will describe my journey as an example but this is not meant to be taken as advice. I am not an expert in finding a job.</p><h4>My background</h4><p>I don’t have the typical background of people who go into data science, by which I mean a degree in computer science or some kind of engineering. I did my undergraduate studies in mathematics and physics at University of Montreal and I then went to McGill University to do a Master’s and a PhD in theoretical physics. During these degrees, I mostly learned advanced mathematics and how to solve problems using them. I mostly did theoretical work but I did a little bit of scientific programming. I also got involved quite a bit in organizing weekly talks and reading courses, visits to primary schools to do science activities with the kids and volunteering for conferences and events.</p><p>Towards the end of my PhD I started to look into what kind of jobs I could get with my degree. I have to tell you that a job directly involving theoretical physics is very hard to find. Most of them are in universities and they require at least one postdoc so I ruled them out. I thought about finding a teaching job (in a CÉGEP, for people who know what that is) but I wanted to look for a more challenging job. One topic that caught my attention was Artificial Intelligence.</p><h4>Studying AI</h4><p>Of course AI is a big trend these days and as a student living in Montreal, I heard even more about it. I spent a lot of time online trying to see what the requirements were to find a job in data science and found that EVERYONE suggested taking Andrew Ng’s <a href="https://www.coursera.org/learn/machine-learning">Machine Learning</a> course on Coursera. I followed this advice and found that the course was excellent and I learned a lot from it. However, after finishing it, I felt like I had a good understanding of the theoretical side of AI, especially since it was based on easy maths from my point of view, but I had no idea how to implement it. This is why I followed by taking the <a href="https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/">Python for Data Science and Machine Learning Bootcamp</a> on Udemy. I learned python, numpy, pandas and scikit-learn in order to actually do machine learning.</p><p>The next advice that I often read online is to focus on learning through personal projects and showcase them on Github and in your CV. This is what I did for a few months after taking the online courses. You can see my first project <a href="https://github.com/yangobeil/Pokemon-legendaries">here</a>. While doing all that I was always looking at job postings online to see what jobs were available and what skills they asked for and the most important one in my mind was deep learning. This led me to take the <a href="https://www.coursera.org/specializations/deep-learning?utm_source=gg&amp;utm_medium=sem&amp;utm_content=17-DeepLearning-ROW&amp;campaignid=6465471773&amp;adgroupid=77415260637&amp;device=c&amp;keyword=coursera%20deep%20learning%20ai&amp;matchtype=b&amp;network=g&amp;devicemodel=&amp;adpostion=1t1&amp;creativeid=379493352691&amp;hide_mobile_promo&amp;gclid=Cj0KCQiAjfvwBRCkARIsAIqSWlOMxay5aQ0LhQZ5rjKZbPVkp5K7fKBfi35l7jQlrJJUG_yj_UvwEYAaAlzsEALw_wcB">Deep Learning specialization</a> on Coursera, which I found extremely interesting and gave me multiple ideas for new personal projects.</p><h4>First round of job applications</h4><p>Of course, I want to make it clear that all this was done part-time while I was still doing my PhD. The steps mentioned above took me about 6 months in between my regular tasks as a PhD student. I actually had a little bit of extra free time since one task of researchers is to stay up to date on new research coming out to prepare for future projects but I was close to graduation so I didn’t have to do that. I also had a scholarship for an extra year so I didn’t have to hurry to find a job so I took my time.</p><p>Around the time when I finished the deep learning specialization, I started to apply for jobs and internships that mentioned the skills that I had. There were not that many but I still managed to get interviews for an internship and a couple of jobs. These were for positions that were meant for people like me with a good scientific background and some AI experience. Even if I was very excited I thought it was a bit premature and I was right because I didn’t get the positions.</p><h4>Polishing my skills</h4><p>I then decided to focus on adding skills and experience to my resume before starting to apply seriously for jobs. I was in a good situation during the summer of 2019 such that I still had funding but my thesis was almost done. I could then focus my attention on finding a job and submit my thesis only after that was done. I also considered the option of staying at McGill after my PhD to do a <a href="https://www.mitacs.ca/en/programs/accelerate">Mitacs</a> internship, which is a research project done jointly with a professor and a company.</p><p>One detail that I didn’t mention is that I talked to people. I found people around me and on linkedIn who had done what I was trying to do and I asked them advice. I talked to some of them by email and met some for coffee and I received very good advice.</p><p>Since I had more time to learn new things I read books (especially <a href="https://www.amazon.ca/Deep-Learning-Python-Francois-Chollet/dp/1617294438/ref=sr_1_1?gclid=Cj0KCQiAjfvwBRCkARIsAIqSWlNxu_TaykZQXwBNIojWZlmTY5gJGtM3mcVLktxkKuB4ObEWZKOMfskaAgbaEALw_wcB&amp;hvadid=229947126708&amp;hvdev=c&amp;hvlocphy=9000451&amp;hvnetw=g&amp;hvpos=1t2&amp;hvqmt=e&amp;hvrand=17817245616471364703&amp;hvtargid=kwd-304805565088&amp;hydadcr=16080_10268130&amp;keywords=deep+learning+with+python&amp;qid=1579109855&amp;sr=8-1">this one</a>) and watched a lot of Youtube videos (sentdex’s <a href="https://www.youtube.com/sentdex">channel </a>was very inspiring). I developped more complex projects like this <a href="https://github.com/yangobeil/language-identifier">language identifier</a> and wrote blog posts about my projects (see my <a href="https://medium.com/@yan.gobeil">profile</a>). I finally spent some time learning the more down to Earth skills needed for a data science jobs, like SQL, git, linux and flask.</p><p>After all that I felt confident about applying only for the jobs that were interesting to me. I was still interested in both research and commercial jobs so I searched for both. I looked for new postings daily and applied with personalized cover letters. A few people came back to me and I managed to get an interview at Décathlon Canada, where I work now on a mix of computer vision and data driven initiatives. I finalized my thesis before starting to work and I took a week off work a couple of months after starting to defend my thesis.</p><p>For people interested here is the CV that I used to get my current job:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2FEPYG3WxULXXBt&amp;url=https%3A%2F%2Fwww.slideshare.net%2FYanGobeil%2Fdeedy-resume-sharedjuillet2&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Fdeedyresumesharedjuillet2-200115181339-thumbnail-4.jpg%3Fcb%3D1579112074&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="640" frameborder="0" scrolling="no"><a href="https://medium.com/media/7473868b3bee1e5b9b509e50e7c9c0c7/href">https://medium.com/media/7473868b3bee1e5b9b509e50e7c9c0c7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b781462c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-theoretical-physicist-to-data-scientist-d8b781462c9">From theoretical physicist to data scientist</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making an image dataset from Youtube videos]]></title>
            <link>https://medium.com/data-science/making-an-image-dataset-from-youtube-videos-5116252d20a3?source=rss-904ad8530778------2</link>
            <guid isPermaLink="false">https://medium.com/p/5116252d20a3</guid>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Yan Gobeil]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 15:19:40 GMT</pubDate>
            <atom:updated>2021-02-15T16:05:05.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KPguexyACIS1tRhq.jpg" /></figure><h4>How to improve your deep learning dataset with realistic images.</h4><p>A deep learning model is only as good as the data you feed it. This is why it is very important to spend enough time gathering a large amount of good data. What I mean by good varies according to the problem at hand. A useful trick to determine if your data is appropriate is to think about what the users’ inputs will look like. This is an important issue, especially when working with images. Lighting, contrasts, orientation, image quality and perspective can vary so much and not taking this variation into account can create huge errors in prediction. For example, if you want to make a phone app using your model, don’t just train it on images taken by professional cameras. A good set of techniques to use to try reducing this bias towards the training data is data augmentation but I will not elaborate on that here.</p><p><strong>Edit (February 2021)</strong>: Youtube has changed the source code of their website so the get_urls function does not work anymore. The rest of the code works (latest version on my github) so the only issue is to get a list of video urls. Here are a few suggestions:</p><ul><li>Manually collect a list of urls and use it instead of the result of get_urls . This can be annoying to do but is sure to work.</li><li>Use Selenium to scrape Youtube and get some urls. This can be complicated given how the website is coded now, but should be doable.</li><li>Use the Youtube API to obtain a list of videos for a given key word. The API is very easy to use. The only step that can be complicated is setting up the credentials using a Google account.</li></ul><p>Contact me if you need help with any of these suggestions :)</p><h3>Scraping for images</h3><p>This long introduction goes to say that data collection is important, and there exist many tools and sources of data. In this post, I focus on images because I am most familiar with this topic. The first thing that comes to mind when trying to gather images on a specific subject is to scrape Google Images using libraries like Beautifulsoup and Selenium. In fact, I wrote such a scraper that you can find<a href="https://github.com/yangobeil/google-images-scraping"> here</a>. However, there is a limit to the number of images that can be found on Google and they often have a similar style, which can be a problem if this style is not the one you are interested in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*nHk87N039tWFjl6ATKrrmw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*Us-SisjvC-99_-7gvcwpNg.jpeg" /><figcaption>Amateur image of hockey players (left) vs pros (right)</figcaption></figure><p>A second source of data, that is less discussed and used, is Youtube. I was motivated to work on this topic when I found a nice dataset from people at Stanford, which can be found <a href="https://github.com/gtoderici/sports-1m-dataset/">here</a>. This is a collection of more than a million links to Youtube videos about close to 500 sports. This fell on me exactly at the right time because I was working on a sports classifier that was trained on images scraped from Google. The model had the problem mentioned above that it worked well on clean and professional images but badly on pictures of amateurs.</p><p>The idea of this post is, therefore, to describe how I collected images from Youtube videos using python. The main steps are to search Youtube for a query and collect a part of the resulting videos as links. Then the program downloads the videos (this might take a lot of time and data, depending on your internet connexion) and saves them locally. Each video is then used to extract a certain number of frames, which are saved, before deleting the videos. This technique allowed me to collect more realistic images, but there was, of course, some manual filtering to do afterwards because videos contain a lot of extra visuals. Obviously this source of data is more restricted but it should be useful for many topics.</p><h3>The code</h3><p>The code for this program is actually simple and is made of small bits that I gathered from around the internet. I, however, was not able to find a program that does what I wanted from start to finish so I had to connect the steps myself. The full code can be found and downloaded on my <a href="https://github.com/yangobeil/youtube-downloader">github</a>.</p><p>The first step is to import all the libraries needed to run the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e12072a931cd06358c06c7a7d4aba55/href">https://medium.com/media/8e12072a931cd06358c06c7a7d4aba55/href</a></iframe><p>Most of them are fairly standard and come with python. The extra ones that need to be installed can be obtained simply using pip. These are: BeautifulSoup to scrape the Youtube website and extract the links, pytube to download the videos and OpenCV to extract the images from the videos.</p><p>Once this is done the next step is to create the first function, which searches a word or phrase on Youtube and returns the urls for the videos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30bd099b53aa4c2b0d9ac97a95eb1a1e/href">https://medium.com/media/30bd099b53aa4c2b0d9ac97a95eb1a1e/href</a></iframe><p>The first step needed to build this is to transform the query word/phrase into a url, in case it contains things like spaces or accents. The Youtube search is done by including the query in a url and the html from the resulting page is extracted using urllib and BeautifulSoup. The later is again used to look for the links of the videos and add them to a list up to the maximum number requested by the function in order to return the list. For a nice intro to how BeautifulSoup works, see <a href="https://towardsdatascience.com/introduction-to-web-scraping-with-beautifulsoup-e87a06c2b857">this post</a>.</p><p>After gathering the urls for the videos, the next function downloads them to the local system. Again be aware that this can take up a lot of your download limit if you have one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85a5236c1c67fe5e288ef586abb9d824/href">https://medium.com/media/85a5236c1c67fe5e288ef586abb9d824/href</a></iframe><p>This one is a simple use of the pytube library (see the <a href="https://python-pytube.readthedocs.io/en/latest/">doc</a>). The code is made to download only videos of a certain length and only the .mp4’s. The length of the videos is hidden deep in the return so I had to dig to find it. There are methods to obtain that kind of information but they did not work for me. The videos are downloaded to the specified location or to the current working directory. Finally, all of the code is embedded inside a try statement because there are many videos that cause errors when they are requested. In this case, the script just does not download the video and prints the error message.</p><p>Once the videos are downloaded it is time to extract the images using OpenCV. This is a pretty big image processing library that can do many things but I only use it to do a very basic task. For more details about this powerful tool, I suggest this <a href="https://pythonprogramming.net/loading-images-python-opencv-tutorial/">series of tutorials</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75a1f339afb652d8676768ebbce8d772/href">https://medium.com/media/75a1f339afb652d8676768ebbce8d772/href</a></iframe><p>This takes as input the path to the mp4 file and the folder where to save the images, to be created if it does not exist already. The video is opened using OpenCV and an image is captured and saved to the right location. A test is made by trying to open the file just to make sure that the image is not corrupted, in which case it is deleted. The video is then fast-forwarded by the specified amount of time and the process continues until the maximum number of images is taken or the video ends.</p><p>The images are labelled according to the name in the input and the starting number is determined by a homemade function. This is a very simple function to find the maximum label of files named like “name_##.jpg” in order to not overwrite existing images. The code can be found on the github repo.</p><p>The final step in this program is obviously to combine everything into a single function that takes in a query word or phrase and ends up with the extracted images in a nice folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff8110008a625e77d4e3a135e2fa92f2/href">https://medium.com/media/ff8110008a625e77d4e3a135e2fa92f2/href</a></iframe><p>This function looks for the urls and downloads the videos to the current working directory. It then goes through all the .mp4 videos in the directory and extracts the right number of images from each of them. The used videos are deleted afterwards to avoid reusing them and wasting disk space. The only function that is necessary to use in order to achieve the goal of this post is extract_images_from_word.</p><figure><img alt="Amateurs playing hockey in an arena" src="https://cdn-images-1.medium.com/max/1024/1*Urk5SHXmgYgS2P1VqLylzQ.jpeg" /><figcaption>Example of image scraped from Youtube about hockey</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5116252d20a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/making-an-image-dataset-from-youtube-videos-5116252d20a3">Making an image dataset from Youtube videos</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>