<?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 Cdiscount Data Science on Medium]]></title>
        <description><![CDATA[Stories by Cdiscount Data Science on Medium]]></description>
        <link>https://medium.com/@cdiscountdatascience?source=rss-cb6044f0ca86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aUdtRkLWj_fT0-7nvpo4tw.png</url>
            <title>Stories by Cdiscount Data Science on Medium</title>
            <link>https://medium.com/@cdiscountdatascience?source=rss-cb6044f0ca86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:36:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cdiscountdatascience/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[Cdiscount image dataset for visual search and product classification]]></title>
            <link>https://medium.com/@cdiscountdatascience/cdiscount-image-dataset-for-visual-search-and-product-classification-64ce1ff533b4?source=rss-cb6044f0ca86------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ce1ff533b4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visual-search]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Cdiscount Data Science]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 13:08:52 GMT</pubDate>
            <atom:updated>2019-09-02T13:08:52.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>12M images of 7M products classified into 5K categories</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBSjC88nwClMHZz8YRBJ2w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alfonsmc10?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alfons Morales</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Images from a large e-retailer</h3><p>Recent advances in artificial intelligence and image recognition allow a whole new set of services to improve the Internet shopping experience. Among those new services, visual search is probably one of the most promising technique as it provides an effective and natural way to search through a catalog with a simple picture.</p><p>Improving visual recommendation algorithms requires access to large labeled image datasets, possibly specialized in the core business they address. Available generic image datasets include <a href="https://groups.csail.mit.edu/vision/TinyImages/"><em>TinyImage</em></a>, <a href="http://labelme.csail.mit.edu/Release3.0/browserTools/php/dataset.php"><em>LabelMe</em></a>, <a href="https://ieeexplore.ieee.org/document/5204331"><em>Lotus Hill</em></a>, Microsoft <a href="http://cocodataset.org/#home"><em>Common Objects in Context</em> (<em>COCO</em>)</a> or <a href="https://github.com/openimages/dataset"><em>OpenImages</em></a>. Of course, <a href="http://www.image-net.org/"><em>ImageNet</em></a> is the <em>de facto</em>standard to bench image classification algorithms involving extremely large numbers of labels.</p><p>Most of the public datasets that are of direct use to on-line retailers are specialized in fashion items: the <a href="http://www.tamaraberg.com/street2shop/wheretobuyit/README.txt"><em>Exact Street2Shop</em></a> dataset identifies around 40,000 clothing items worn by people on real-world street photos, and provides their exact match amongst hundreds of thousands of images from shopping websites; <a href="http://mmlab.ie.cuhk.edu.hk/projects/DeepFashion.html"><em>DeepFashion</em></a>consists of over 800,000 annotated images that contain clothes.</p><p>To the best of our knowledge, no comprehensive image dataset covering products typically sold by generalist retailers is yet available to the community. This is the reason why we are releasing a large dataset of such categorized product images. With more than 12M images of 7M products classified into 5270 categories, this dataset should help the community to leverage state-of-the-art neural network architectures in order to develop better recommendation systems.</p><p>In the following article, we present several aspects of the dataset such as the way it was build and organized or some specific features that you might want to consider before training a model on it. We also get a grasp of the approaches followed by the 3 winning teams of the Kaggle competition we organized on this dataset.</p><p>The full dataset can be downloaded from the Kaggle platform at the following address: <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge">kaggle.com/c/cdiscount-image-classification-challenge</a></p><h3>Structure of the Cdiscount dataset</h3><p>Our image dataset has been extracted from the full list of more than 40M products available at <a href="https://cdiscount.com/"><strong><em>cdiscount.com</em></strong></a> in July, 2017.</p><p>Products are coming from our own list of products or from our Market Place where independent resellers can put their products up for sell. Our own catalog being rich of approximately 200,000 products, the vast majority of the 7M products in the dataset originates from the nearly 10,000 independent resellers present on our Market Place.</p><p>The dataset is organized according to a 3-level classification tree with categories labeled in French.</p><p>The 1st level of aggregation is referred to as Cat I for Category level I and contains a diversity of products that could be compared to a physical store, like a drugstore or a wine shop. It is the most generic level of aggregation and as such is of particular interest if one wishes to focus on a particular subset of images such as CHILDCARE (PUERICULTURE), BAGS (BAGAGERIE) or INTERIOR DESIGN (DECORATION). The 49 distinct Cat I categories are listed in table 1 with the corresponding English translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*WDSt4KAWUKyieYLD9b2_yA.png" /></figure><p>The 2nd level category (Cat II) is of lesser importance. It is an intermediate step before the 3rd and most specific level which gathers identical products or objects. Examples of these 3rd level categories (Cat III) belonging to the 3 stores mentioned above would be BABY BOTTLE (BIBERON), TRAVEL BAG (SAC DE VOYAGE) and PHOTO FRAME (CADRE PHOTO).</p><p>The number of categories for each level is given in table 2. A ratio of roughly 1 to 10 is observed in the number of categories from one level to the next, leading to 5270 distinct Cat III categories. It is worth noting that there are actually 5263 distinct values taken by the 5270 Cat III categories: 7 couples of them share the same name while belonging to different Cat II categories. However, the combination Cat II &amp; Cat III is uniquely defined through the dataset. Finally, each of the 5270 Cat I &amp; Cat II &amp; Cat III category is encoded with an integer index in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*14i4CxssLqrMcWHQV83NWg.png" /></figure><p>Down to the level of products, we count between 1 and 4 180x180 pixel images that can be associated to a given product. There aren’t any specific rule to define that number as within our Market Place, a reseller is simply given the choice to insert 1, 2, 3 or 4 images with his product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*XU9RO7_hKL-Tcvh8MudbcQ.png" /></figure><p>Table 3 summarizes the distribution of products according to the number of associated images. More than half the number of products have only 1 image. Those images represent 1/3 of the total number of images in the dataset. Finally, we count precisely 12,371,293 images for 7,069,896 products.</p><h3>Labelled images of products</h3><p>The labelling of this dataset was made using textual descriptions of each product in our catalog. The process of classification is semi-automatized: a <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">K-NN</a> is applied to classify every product and if the required confidence level isn’t met for a given product, it is sent to manual classification. Finally, the overall quality of the classification is assessed by frequent sampling operations in which a trained expert is asked to visually control the classification.</p><p>The measured overall rate of bad classification based on this sampling technique is around 10 % in each category. This number gives the order of magnitude of noise associated with our image dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yT6Faea_2lby5L8IUKAqsQ.png" /></figure><p>Figure 1 shows illustrative examples of images that can be found in the dataset. Background may vary from one image to the other. A product might be presented on a white or colored background or might be shown in an illustrative situation like the wall decoration or the dresser. Images might be views of the same object with different angles like for the helmet or they might be showing a zoom on some specific detail of the product as for the couch. The product may also be represented more than once like the watch.</p><p>Finally, for some specific products, one of the images might not be showing the product at all. This is the case for the fridge as, according to the European Union regulation, electrical goods all have to carry an EU energy label.</p><h3>Unbalanced categories</h3><p>Our product catalog is highly diverse and the categorization tree we use is not aimed at balancing the number of products among the categories. It is rather aimed at gathering products with similar characteristics and purposes. This results in a highly unbalanced number of products per categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEVTixKjqkCuUrXmsq7pYg.png" /></figure><p>Figure 2 shows 3 distributions of products per category, one for each hierarchical level of category. It should be noted that the bin widths used to draw these histograms vary on a logarithmic scale to facilitate the visualization of several orders of magnitude on the same plot.</p><p>At the Cat I level, the spread is considerable. There is a small cluster of 5 categories with less than 200 products (APICULTURE, PRODUITS SURGELES, ABONNEMENTS/SERVICES, PRODUITS FRAIS, FUNERAIRE). The rest of the 44 categories gather between roughly 104 and 106 products each. The last bin alone contains 9 categories in which 4.5M products (more than half the products) are to be found in total.</p><p>At the Cat II level, the spread remains important. It varies between 10 and half a million of products in just one category named PARTS (PIECES). The mode of the distribution for this level is around 3,000 products per category as shown on figure 2.</p><p>Finally, at the Cat III level, the most populated categories are rich of more than 10,000 products each (Figure 2). The top 5 being POP ROCK MUSIC, PRINTER TONER, PRINTER CARTRIDGE, FRENCH LITTERATURE and OTHER BOOKS with nearly 70,000 items each. Most of the categories (nearly 2000 of them) count between 50 and 500 products.</p><p>Another way to look at the unbalancedness of the dataset is to consider the share of products with respect to the most populated categories. This is shown on figure 3 where the cumulative percentage of products is displayed as a function of the number of Cat III categories. The behavior is nearly exponential with 75 % of the products gathered in only 10 % of the categories. On the other end, the less populated 75 % of the categories account for only 10 % of the total number of products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*NnXGroTk_JtJNex1H0YLmA.png" /></figure><h3>Duplicated images</h3><p>The second aspect specific to our dataset might be the presence of duplicated images. Indeed, nothing prevents a reseller from using similar if not identical images to describe several of its products. Technical goods are a good example of products with distinct characteristics but identical appearance.</p><p>From an image classification point of view, the presence of duplicated images might be considered as a downside or an upside. It reduces the absolute size of the dataset but it may also help classifying a few products and making links between categories that contain identical images.</p><p>To trace back identical images, we use the <a href="https://en.wikipedia.org/wiki/MD5">MD5 hash function</a> as defined. Images with the same hash key are labeled as identical. Although the MD5 hash function suffer from weaknesses that will prevent nearly identical images to be detected, it is efficient enough in our case where there is no will to hide duplicates by tricking the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*quydsDrvvtNzVMEhE3Nr2A.png" /></figure><p>The distribution of the measured MD5 hash keys through the entire dataset is shown in Figure 4. Again, logarithmic scales have been used to account for the large range of values. Among the 12M images in total in the dataset, 6.85M images are uniquely defined and 75 % of the images appear at the most 10 times in the dataset. The image the most replicated appears 16,643 times!</p><h3>Winning the Cdiscount image classification challenge</h3><p>Our image dataset was originally created for an image classification challenge that was held on the famous Kaggle platform between September and December 2017. The challenge involved more than 600 teams from all around the world and final results were quite impressive as the best solutions were able to correctly classify almost 80 % of the images of the test set.</p><p>The evaluation metric was the accuracy of classification on a test set for which none of the categories was known. If you wishes to evaluate your categorizer on the test set, do not hesitate to contact the authors of this article. We will happily provide you with your test score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*RxrJY0i-3hmJ6JAaG33Wcg.png" /></figure><p>The name, final rank and score of the 3 winning teams is given in table 4. All 3 solutions are ensemble models that aggregate sub-models. They all rely on neural network architectures pre-trained on <a href="http://www.image-net.org/"><em>ImageNet</em></a> and they made a heavy use of GPUs to fine-tune those networks on our dataset. The neural network architectures that were used are listed below:</p><ul><li>ResNet</li><li>InceptionResNetV2</li><li>InceptionV3</li><li>ResNExt</li><li>SE blocks</li><li>Dual Path Network</li></ul><p>It is worth noting that none of the above mentioned techniques or architectures were described in the literature before 2016 for a challenge that was held in 2017! Also, all 3 solutions made use of the dropout technique to prevent overfitting and performed data augmentation via cropping, flipping and/or resizing operations.</p><p>At a more detailed level, the winning solution presents an interesting approach in which the trained neural networks are dedicated to products with a fix number of images. When more than one images are available, they are simply aggregated side by side in a larger image and fed into the dedicated model.</p><p>The 2nd solution took a similar approach for one of its sub-model by specializing neural networks for each number and rank of images. The competitor realized that both the number of images per product and the order of those images were not random and thus should be considered for classification.</p><p>Finally, a last worth mentioning originality was the use by the winning team of an OCR for products that were recognized as being books or CDs. This last trick probably made the small difference that made this solution the winning one!</p><p>Next, we hope to read from you. As already mentioned, we keep the test set labels cozy and warm for you so don’t hesitate to contact us if you want to bench your classifier!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ce1ff533b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Link Prediction In Large-Scale Networks]]></title>
            <link>https://medium.com/hackernoon/link-prediction-in-large-scale-networks-f836fcb05c88?source=rss-cb6044f0ca86------2</link>
            <guid isPermaLink="false">https://medium.com/p/f836fcb05c88</guid>
            <category><![CDATA[link-prediction]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Cdiscount Data Science]]></dc:creator>
            <pubDate>Mon, 27 Aug 2018 12:06:27 GMT</pubDate>
            <atom:updated>2019-04-23T07:23:00.544Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comparison of supervised and unsupervised approaches to infer missing links from an observed network.</h4><p><em>by </em><a href="https://www.linkedin.com/in/guillaume-le-floch-b1b632138/"><em>Guillaume Le Floch</em></a><em> (Data Scientist at </em><a href="http://cdiscount.com/"><strong><em>Cdiscount</em></strong></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GF6ozztlIUgBB7wY8OtxLA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/BW0vK-FA3eg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clint Adair</a> on <a href="https://unsplash.com/search/photos/network?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is the point of predicting new links when you already have plenty of them ?</h3><p>If you have decided to read this article, you must either be very interested in Data Science or extremely bored right now. Whether this is the first or the second option, we are delighted to have you on board and wish that you will enjoy the ride through the link prediction problem with us.</p><p>On a more serious note, the goal of this paper is to find the best option to predict accurately future connections in a graph, which you can also call a network. Not a tiny, harmless network. No, we are talking about large-scale networks. The big and horrendous ones made of billion of nodes and edges which <strong>Facebook</strong>, <strong>Google </strong>(and <strong>Cdiscount</strong>) have had to deal with on a daily basis for the last few years.</p><blockquote>What is the point of predicting new links when you already have plenty of them ?</blockquote><p>We have seen this question coming from a mile away, and we have got you covered, don’t worry. It is in the human nature (and even more in the Data Scientist one), to want more than what we already have. We don’t settle for the present, we want to know the future as well. Therefore, we need to find a way to perform predictions as accurate as possible.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F4cpqFamWB2dq0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F4cpqFamWB2dq0%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F4cpqFamWB2dq0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="238" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cbaae4bc6bb42cfd3c147c5b909b7fe/href">https://medium.com/media/0cbaae4bc6bb42cfd3c147c5b909b7fe/href</a></iframe><p>Furthermore, a network is what we can call a dynamic structure as it evolves with time. For instance, social networks such as Facebook, Twitter, LinkedIn etc. change permanently as new connections appear while some others are removed from the graph.</p><p>For this particular example, one of the biggest challenges is to make accurate recommendations to the users. They may know somebody in real life, but aren’t connected with that person on their favourite social network. Thus, the target in this case would be to predict (and recommend) this association (link in the graph), in order to fix what can be seen as a mistake.</p><p>Link prediction can help rebuild the real life, but it could actually do more than just that. What we observe isn’t always ideal. An example would be terror attacks : given relationships between terrorists, you can build a network which represents who worked with who in the past. Link prediction can help predict future associations, allowing a government to monitor suspects and prevent them from committing a terror attack together. Biology is another area where link prediction can be a key asset, as human brains aren’t enough to predict all associations between molecules, having an artificial intelligence to do the job can be a massive boost.</p><p>To put it in a nutshell, link prediction can be used for various purposes, in many different areas. In this article, we will focus mainly on the collaboration network case. We will work with the <a href="https://snap.stanford.edu/data/com-DBLP.html">DBLP dataset</a> (See [1] for more details). This is a co-authorship network where two authors are connected if they publish at least one paper together, so we will try to predict relevant future collaborations here (we would like to avoid awkward situations).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26gJzrPTPiMNHrJLO%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26gJzrPTPiMNHrJLO%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26gJzrPTPiMNHrJLO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/02cb5e70b18039c6e9b25753b04a307d/href">https://medium.com/media/02cb5e70b18039c6e9b25753b04a307d/href</a></iframe><h3>The learning context: unsupervised vs. supervised</h3><p>In this section, we will discuss the possibilities at our disposal to perform predictions in a graph. As this is a special structure, we need to clarify a few points before getting started with prediction. Let’s start with a bit of theory and notations before practising.</p><h4>A little reminder of Graph Theory</h4><p>To ensure we are all speaking about the same things, let’s use the same vocabulary about graphs. And even if you already know this, a little reminder does no harm:</p><ul><li>From a mathematical point of view, a graph can be defined as <em>G = (V, E) </em>with <em>V</em> being the set of nodes (or vertices) and <em>E</em> the set of edges.</li><li>A graph is undirected if the relationship goes both ways. Facebook is a good example of that : when someone is your friend, you automatically are his friend too. On the contrary, a graph is directed if the link goes from one node to another, but it isn’t reciprocal. Twitter illustrates this perfectly as you can follow somebody, but this individual doesn’t necessarily follow you in return.</li><li>We can define the graph’s adjacency matrix (of dimension <em>|V|</em> ×<em> |V|</em>) as <br><em>A = [</em>A_ij<em>]</em> with (<em>i,</em> <em>j) </em>∈ <em>V</em>. For an undirected and unweighted graph :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*VswuAvOD2-GVypt0g01Sdg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1M9fmo1WAFVK0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1M9fmo1WAFVK0%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcm0xOGx3aHhrbjN6bHgzZHMzOHlqNHZ0Zzd5dG5wa29wOWlkZjN3biZlcD12MV9naWZzX2dpZklkJmN0PWc%2F1M9fmo1WAFVK0%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fbfded72b6272894e1dea782e7369f9/href">https://medium.com/media/5fbfded72b6272894e1dea782e7369f9/href</a></iframe><ul><li>A sequence is a succession of consecutive edges : <em>{i_1, i_2}, {i</em>_2<em>, i_3}, …, {i_K-1, i_K}.</em></li><li>A path between nodes <em>i</em> and <em>j</em> is a sequence of edges <em>{i_1, i_2}, {i</em>_2<em>, i_3}, …, {i_K-1, i_K} </em>such as <em>i_1 = i</em> and <em>i_K= j </em>and each node in the sequence is distinct.</li><li>As we are going to heavily use the concept of <strong>neighborhood</strong>, let’s denote 𝛤(<em>u</em>) the set of nodes which are directly linked with the node <em>u</em> (they are its “neighbors”).</li><li>A distance between two nodes is given as the minimal number of edges to go from one node to another (shortest path).</li></ul><p>The <a href="https://snap.stanford.edu/data/com-DBLP.html">DBLP dataset</a> which will be used for our experiments has the following properties:</p><ul><li><strong>317,080</strong> <strong>nodes </strong>(researchers).</li><li><strong>1,049,866</strong> <strong>edges </strong>(co-autorships between researchers).</li></ul><p>Yes, you are right. This is what we can call a large-scale network, and this is ideal in order to perform learning tasks, whether they are supervised or unsupervised. This will provide us with stability and confidence in the results we will get from the experiment.</p><p>Let’s now discover the learning process in the next part(s).</p><h4>The Creation of Training, Test and Validation Sets</h4><p>The part we are entering is a tricky one, so fasten your seat belt, we don’t want to lose you now. Splitting a dataset into training/test/validation sets isn’t a difficult concept to understand in normal circumstances. When it comes to graphs, it is a bit different. How can you split a graph to achieve a learning task ? First of all it is important to remember precisely our purpose : <strong>we want to predict links (edges) between nodes</strong>.</p><p>The first capital information is the following one : the predictive algorithm will take as input node pairs and evaluate whether the nodes present the properties to be linked in the future. In this paper, we will only look at nodes which are at distance 2. What remains to be clarified now is the output : how can we create ground-truth labels from the graph ? The idea is to take a graph, hide some of its edges and monitor the results produced by the algorithm. For hidden links the label is 1, for non-existent links it is 0. Not clear enough yet ? No problem, let’s illustrate the concept with a minimal example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uL5A7BU_oBJrNpFGIR0thg.png" /></figure><p>From the left to the right we have :</p><ul><li>The “validation graph” which denotes as <em>G_valid = (V, E_valid)</em> with : <em>V = {A, B, C, D, E, F, G, H, I, J} </em>and<em> E_valid = {(A,B); (A, D); (B, C); (B, D); (B, E); (C, D); (D, E); (D, F); (D, H); (D, G); (E, F); (E, I); (F, H); (F, I); (F, J); (I, J)}.</em></li><li>The “test graph” where we have hidden two edges : <em>G_test = (V, E_test) </em>with <em>E_test = E_valid \ {(D, E); (D, H)} thus E_test </em>⊂<em> E_valid.</em></li><li>The “training graph” where we have hidden four more edges : <em>G_train = (V, E_train) </em>with <em>E_train = E_test \ {(A, D); (C, D); (E, I); (F, J)} thus E_train </em>⊂<em> E_test.</em></li></ul><p>So, as you can see it is not that deep, it is just a matter of a graph which contains a subgraph which itself contains a subgraph…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fm7yzbDgdkWbmM%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fm7yzbDgdkWbmM%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fm7yzbDgdkWbmM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f955e28407d0ca48a61296b97924ee/href">https://medium.com/media/a9f955e28407d0ca48a61296b97924ee/href</a></iframe><p>If you are still firmly with us at this point, then you have understood that our training set (with the corresponding labels) looks like the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*230lw-B4t405x6rFJk2FvQ.png" /></figure><p>Make no mistake, the edge <em>(D, H)</em> for example has the label 0 here because it doesn’t exist in the Test Graph, even though it was originally present in the Validation Graph.</p><p>As we are evaluating all the 2-hop “missing link” node pairs we can see that the edges we have hidden have label of 1 while the rest have a label of 0. Let’s remember that this is just a minimal example, although we can already see several interesting facts :</p><ul><li>The number of node pairs to evaluate is fast-growing, we will let you imagine how it is like in a large-scale network (we will see it afterwards anyway).</li><li>The problem of <strong>class imbalance</strong> appears : there are far more 0 labels, so we will have to deal with this problem later on..</li></ul><p>Let’s now discover what are the unsupervised methods we can choose to perform link prediction in a graph, digging deepeer into the notions of <strong>neighborhood </strong>and <strong>local similarity</strong> in the process.</p><h4>Unsupervised Learning : The Notion of Similarity Indices and Neighborhood</h4><p>If the nodes in the graph don’t possess properties, as is the case in our study, the only information available comes from the topological structure of the graph. By that, we mean the neighborhood of a node : how many neighbors has this node got ? How many neighbors these neighbors themselves have ? How are they organised ? As we are evaluating node pairs we can also look at how similar a node <em>u</em> can be to a node <em>v</em> by looking at their “distance” in the graph, the similarity of their local neighborhood.</p><p>All of this has led to several local similarity indices such as Common Neighbors, Jaccard Similarity, Adamic-Adar Index, Resource Allocation, etc (more can be found in [2] and [3]). These indices will return a score <em>s</em> ∈ ℝ which will be used to perform predictions. As it is explained in [3], you will also need to set a threshold value above which you assign the label 1. We sense that you may be asking which unsupervised method is the best to perform predictions. This is a tricky question as in some cases, one measure will outperform others, but in other cases it will be another one, etc.</p><p>And what if we didn’t actually have to choose ? What if we let something else combine those local similarity indices to get a score in return ? You’ve got it right, we are heading straight to the Supervised Learning universe.</p><h4>Feature Engineering for Supervised Learning</h4><p>We have already discussed how to obtain labels. Now we need features in order to perform Supervised Learning (Binary Classification). And yes, you guessed it, these features will come from the latest part we discussed. Based on <strong>Kolja Esders</strong>’s work in [3], we will use unsupervised scores as features for our predictive model. We will also use the notion of <strong>Community</strong> (further details can be found in [4]).</p><p>The following features will be included in our learning/prediction task : <em>Common Neighbors (CN)</em>, <em>Jaccard Coefficient (JC)</em>, <em>Adamic-Adar index (AA)</em>, <em>Resource Allocation (RA)</em>, <em>Preferential Attachement (PA)</em>, <em>Adjusted-Rand</em> (AR) and <em>Neighborhood Distance</em> (ND) which are all local indices to which we will add the <em>Total Neighbors</em> (<em>TN</em>), <em>Node Degree</em> (<em>UD </em>et <em>VD</em>) and <em>Same Community</em> (<em>SC</em>) features. They are defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*DugwkvsaLhIatzOAdLLSPw.png" /></figure><p>As for <em>Adjusted-Rand</em> here is a table giving the meaning of <em>a</em>, <em>b</em>, <em>c</em> and <em>d</em> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gag6JjfHYqtG42ymfDsM4w.png" /></figure><p>Before going into predictions, we just need to discuss the evaluation metric which will help us determine whether Supervised Learning is better than the Unsupervised one (Spoiler alert : from Kolja Esders and our own experience in the past, it seems that it is the case) and it happens in the very next part.</p><h4>Evaluation metric</h4><p>The evaluation metric chosen in this study is a well-known one : the AUC. As it is a binary classification problem, it is ideal and will also allow us to plot the ROC curves of the method to illustrate the comparison between algorithm results. This will also free us from having to set a threshold for the unsupervised method.</p><p>Considering two independent and identically distributed observations (<em>X1</em>; <em>Y1</em>) and (<em>X2</em>;<em> Y2</em>), the AUC of a scoring method <strong>S</strong> can be written in the following manner :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*L4_IuI2mvMX4MnNiOvs_3w.png" /></figure><p>In other words, a perfect algorithm (which would get an AUC of 1) would give higher scores to every node pairs having a label of 1 than node pairs having a label of 0. This is just a matter of score order, whichever score is used.</p><p>In the next section we will put several algorithms face to face in the arena and compare their performances :</p><ul><li><strong>Resource Allocation</strong> (Unsupervised Method)</li><li><strong>Adamic-Adar</strong> (Unsupervised Method)</li><li><strong>Jaccard Coefficient </strong>(Unsupervised Method)</li><li><strong>Common Neighbors</strong> (Unsupervised Method)</li><li><strong>Tree-based XGBoost</strong> (Supervised Method, combination of unsupervised scores with other features)</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fe37RbTLYjfc1q%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fe37RbTLYjfc1q%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fe37RbTLYjfc1q%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="345" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a84b12c5528a1ad5be40c35c7cedb6/href">https://medium.com/media/e4a84b12c5528a1ad5be40c35c7cedb6/href</a></iframe><h3>Experiments on the DBLP Dataset</h3><p>Before plotting the ROC curves and unleash the results, we will talk about data processing. As we pointed out previously, the class imbalance problem appears when dealing with huge networks. So after finding all the 2-hop missing links in our training and test graphs, we decided to randomly drop samples with labels zero in order to get a 50/50 balance for labels. This has led to these datasets :</p><ul><li>Train : 277,742 samples (node pairs).</li><li>Test : 150,348 samples (node pairs).</li></ul><p>These are huge datasets for both training and test which should help us avoid over-fitting. This will also give us confidence when it comes to the relevancy of the results.</p><p>Talking about them, you waited patiently for them, so here they are :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*W4n2pzavQ36wuElMepJ1Dw.png" /></figure><p>He has just gone and done it again, hasn’t he ? The mighty Gradient Boosting algorithm has once again outperformed all his opponents. We will admit it wasn’t a completely fair contest though. This is what we can call an “easy” graph as we reach an AUC score of <strong>0.96 </strong>with <strong>XGBoost </strong>(which is very close to perfection), but methods such as <strong>Resource Allocation</strong> and the <strong>Adamic-Adar Index</strong> also performed very well with respective AUC scores of <strong>0.93</strong> and <strong>0.92</strong>. As we can see, <strong>Common Neighbors</strong> is a bit more limited in this case with an AUC of <strong>0.78</strong>, so only counting common friends may not be the best strategy if you want to have new friends it seems !</p><p>Tree-based boosting algorithms also provide “feature importance”, and an interesting fact here is that there seems to be a correlation between the feature importance of a similarity indice and its prediction quality :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*5M3pztJV7nq_tPqFFa0LrQ.png" /></figure><p>Resource Allocation was the “most important feature” according to this graph, and also as we saw previously, the best unsupervised method. It is quite similar to the Adamic-Adar index, with the only difference being the log at the denominator. In that regard, this may make <strong>RA </strong>more discriminating than <strong>AA </strong>as it penalises more the common neighbors which have many neighbors themselves.</p><h3>Discussion and Future Work</h3><p>From what we saw there, using a supervised method which combines unsupervised methods seems to be more efficient. This goes on to confirm Kolja Esders’s conclusions as well as our own past experience when working with networks.</p><p>This was an “easy” <a href="https://hackernoon.com/tagged/network">network</a> as we got really high AUC scores, but depending on the complexity and noise in the graph you are working on, this can be more or less difficult to predict accurately future links. The gap between supervised and unsupervised scores can also widen with complex networks.</p><p>We decided to use the XGBoost algorithm but it is of course possible to use any other <a href="https://hackernoon.com/tagged/machine-learning">Machine Learning</a> algorithm, so you can try to reproduce this experiment with your favourite binary classifier ! Data processing has been realised using the Networkit library, so you will need it (find more <a href="https://networkit.iti.kit.edu/">here</a>).</p><p>As we never settle for what we possess, the aim in the future would be to perform even better predictions. Building and adding new features to the model may help improve the performance as it would add information. Scaling data before feeding the model could also slightly improve the performance.</p><p>And this is how it ends ! We hope that you enjoyed this journey with us through the link prediction problem in a large-scale network. As the code and data are available in addition to this paper, feel free to reproduce this experience and even improve it if you can ! Thank you for your attention.</p><h3>Further readings</h3><ul><li>J. Yang and J. Leskovec, (2012). <em>Defining and Evaluating Network Communities based on Ground-truth (ICDM </em>[http ://snap.stanford.edu/data/com-DBLP.html].</li><li>David Liben-Nowell and Jon Kleinberg, (2007). <em>The Link-Prediction Problem for Social Networks.</em></li><li>Kolja Esders, (2015). <em>Link Prediction in Large-scale Complex Networks</em>. Bachelor’s Thesis at the Karlsruhe Institute of Technology.</li><li>Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte and Etienne Lefebvre (2008). <em>Fast unfolding of communities in large networks</em></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f836fcb05c88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/link-prediction-in-large-scale-networks-f836fcb05c88">Link Prediction In Large-Scale Networks</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief overview of Automatic Machine Learning solutions (AutoML)]]></title>
            <link>https://medium.com/hackernoon/a-brief-overview-of-automatic-machine-learning-solutions-automl-2826c7807a2a?source=rss-cb6044f0ca86------2</link>
            <guid isPermaLink="false">https://medium.com/p/2826c7807a2a</guid>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Cdiscount Data Science]]></dc:creator>
            <pubDate>Fri, 25 May 2018 13:57:37 GMT</pubDate>
            <atom:updated>2019-04-23T07:23:56.025Z</atom:updated>
            <content:encoded><![CDATA[<h4>From mathematical formalism to a description of available solutions (+ Kaggle benchmark)</h4><p><em>by </em><a href="https://www.linkedin.com/in/julien-jouganous-647993124"><em>Julien Jouganous</em></a><em>, </em><a href="https://www.linkedin.com/in/romainsavidan/"><em>Romain Savidan</em></a><em> and </em><a href="https://www.linkedin.com/in/axelbellec/"><em>Axel Bellec</em></a><em> (Data Scientists at </em><a href="http://cdiscount.com/"><strong><em>Cdiscount</em></strong></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgHYXVXoyziBKd7Or5IliQ.jpeg" /><figcaption><strong>the hyperparameters jungle</strong> — Photo by <a href="https://unsplash.com/photos/QA2clzv9E8c?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">chuttersnap</a> on <a href="https://unsplash.com/search/photos/pipeline?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is AutoML and why do we need it?</h3><p>Auto ML is the fact of simplifying data science projects by automating the <a href="https://hackernoon.com/tagged/machine-learning">machine learning</a> tasks. The <em>figure 1</em> below presents a classical machine learning pipeline for supervised learning tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oU3LAye3LxFcHg0UePmbSA.png" /><figcaption>Figure 1: A machine learning process.</figcaption></figure><p>In the process presented above, several blocks must be tuned to extract most of the predictive power of the data:</p><p>First of all, you have to select relevant data that potentially explain the target you want to predict. Once these raw data are extracted, you generally need to process them.</p><p>A non-exhausive list of preprocessing steps is given below:</p><ul><li>text vectorization</li><li>categorical data encoding (<em>e.g.</em>, one hot)</li><li>missing values and outliers processing</li><li>rescaling (<em>e.g.</em>, normalization, standardization, min-max scaling)</li><li>variables discretization</li><li>dimensionality reduction</li></ul><p>Last but not least, you have to choose a machine learning algorithm depending on the kind of task you are facing: supervised or not, classification or regression, online or batch learning…</p><p>Most machine learning algorithms need parameterization and even if some empirical strategies can help (<a href="https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/"><em>this article</em></a> provides guidelines for <a href="http://xgboost.readthedocs.io/en/latest/"><em>XGBoost</em></a>), this optimization is complex and there is generally no deterministic way to find the optimal solution. But that is only the tip of the iceberg as the whole process involves choices and manual interventions that will impact the efficiency of the machine learning pipeline.</p><h3>Welcome to the hyperparameters jungle!</h3><p>To illustrate this, consider the classical <strong>spam detection problem</strong>: using the content of emails, you want to predict whether an email is a spam or not. To do that, we have a database with emails tagged as SPAM or NOT_SPAM so this is a supervised binary classification problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*DJO9qUEWADxCHifLRTVGug.png" /><figcaption>Figure 2: Spam detection</figcaption></figure><p>As machine learning algorithms generally deal with numerical vectors, the first step is to vectorize our emails. We can use a <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#tfidf-term-weighting">tf-idf</a> approach. But before, we have to tokenize the emails (turn sentences into lists of words). We may also want to apply more advanced text preprocessing such as lowercasing, <a href="https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html">stemming, lemmatization</a>, or spelling correction.</p><p>Now the emails are tokenized and preprocessed, we can vectorize them computing the tf-idf weights but here again the algorithm needs to be parameterized. Indeed, we generally want to specify stopwords, truncate the document frequency range (<em>i.e.</em>remove from the dictionnary rare and/or frequent words), or even include <em>n-grams</em> (sequences of <em>n</em> consecutive words) into our dictionnary.</p><p>We have a vectorized representation of our emails. We may or may not want to apply a dimensionality reduction technique such as PCA. We may also want to add other features such as the number of words in the mail, the average word length for example.</p><p>It is now time to train our machine learning model but which one will we use?</p><p>For this kind of batch supervised binary classification task, we are spoilt for choice: logistic regression, naive Bayes classifier, random forest, gradient boosting, neural nets… We probably want to try and compare some of these algorithms but here let say that we have chosen the <strong>random forest</strong>. How many decision trees do we need? What is the optimal tree depth? How do we control the leaves granularity? How many samples and features do we want to include in each tree?</p><p>Just have a look at the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">scikit learn documentation</a> to have an overview of the amount of hyperparameters you can tune.</p><p>Finally, each component of the pipeline involves choices and parameters that can impact the performances of the algorithm. Auto ML simply consists in automating all these steps and optimizing data preprocessing, algorithm choice and hyperparameters tuning.</p><h3>Hyperparameters optimization strategies</h3><h4>Mathematical formalism</h4><p>Consider 𝚨 the possible strategies space. It may sound a bit abstract but let’s just say that each element <em>A</em> ∈ 𝚨 is a parameterization of the machine learning pipeline from the data processing to the model hyperparameters tuning. The auto ML process aims at finding <em>A</em>* such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*IiAF7wA_MZhFkSwAoc5rIg.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*cO_jsAKnN4W88gYOYF5frg.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*Ah3fBz4BftZ5dHFYCIypTA.png" /></figure><p>are train and validation sets obtained via <em>K-fold</em> cross validation and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*o01jEVSggqyDmHHNCsLixg.gif" /></figure><p>is the loss for pipeline <em>A </em>trained on training dataset <em>i</em> and evaluated on validation dataset <em>i</em>.</p><h4>Random search, grid search</h4><p>The first and simplest tuning approach that may come to mind is just picking randomly several parameterizations of the pipeline and keep the best one. A variant called grid search consists in testing the nodes of a discretization grid of 𝚨. For more details, these algorithms are implemented in scikit learn, <a href="http://scikit-learn.org/stable/modules/grid_search.html">here</a> is the documentation.</p><p>These Monte-Carlo-like algorithms can be a good starting point for low dimensional problems but, as we saw before, we generally have a consequent amount of parameters to tweak so they will converge very slowly. Moreover, in the grid search case, if optimal strategies are far from the nodes you defined, you have no chance to discover them.</p><h4><strong>Metaheuristics</strong></h4><p>To overcome the poor convergence properties of random search, one may want to implement more “clever” algorithms. Metaheuristics are a class of generic optimization techniques based on the exploitation / exploration trade-off and often mimicking biological or physical phenomena. They can be efficient to solve convex and non-convex problems.</p><p>Among the tons of metaheuristics, we can mention for instance:</p><ul><li><strong>Simulated annealing</strong> is a method inspired from annealing in metallurgy that consists in alternating cooling and heating phases to minimize the material enregy modifying its micro structure and physical properties. In analogy, we explore the parameters space to try to minimize the system energy (our objective function). We also introduce the temperature of the material <em>T</em>. At each step, we test a configuration in the neighborhood of the previous one. The higher the temperature is, the more the atoms are free to move and the larger the neighborhood is. Consequently, at the beginning of the process, when <em>T</em> is high, we explore pretty much all the search space and as this temperature decreases, we focus more and more on the areas deemed promising. See <a href="http://katrinaeg.com/simulated-annealing.html">here</a> for a more detailled description.</li><li><strong>Particle swarms</strong> uses a population of candidate solutions (or particles) to explore the space 𝚨. Each particle moves in 𝚨 depending on its current location, its best known past position and the whole population’s best position. The trade-off between exploitation and exploration can be tuned by playing whith the relative importance of these different factors. <a href="http://bee22.com/resources/Poli%202007.pdf">This paper</a> gives more details about the algorithm and some variants.</li><li><strong>Evolutionary algorithms</strong> is a family of algorithms inspired by biological evolution. We consider a population of candidate solutions (or individuals) and we apply simplified evolution laws to have them optimize the objective function called <strong>fitness</strong>. At each step or generation, we select the best (meaning here the fittest) individuals. The next generation is built via the reproduction of these selected individuals. During this step we apply genetic operations: <strong>recombination</strong> (exploitation) is the process by which the parents features are combined to form children solutions, whereas <strong>mutations</strong>, introduce random (exploration) perturbations. This way, the average population’s fitness is supposed to improve from one generation to the next and the fittest individual to converge to a good solution of your optimization problem.</li></ul><h4>Bayesian approaches</h4><p>Each evaluation of the objective function we try to minimize can be very expensive as we have to train and evaluate a machine learning pipeline. Bayesian optimization provides an efficient method to explore the parameter set and converge quickly to a convenient solution. In short: it helps focus the exploration of the parameter space 𝚨 on promising areas. The <em>figure 3</em> below (<a href="http://haikufactory.com/files/bayopt.pdf">source</a>) gives a simple example in one dimension (in this case, we want to maximize the function):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*9zE2EhVEmzfFfA5eYtj7ag.png" /><figcaption>Figure 3: Bayesian optimization.</figcaption></figure><p>In this example, the objective function <em>f</em> is approximated through a <a href="http://mlg.eng.cam.ac.uk/zoubin/papers/aistats07localGP.pdf">Gaussian Process regression</a> model. This modelling technique provides a probability density function for the values of <em>f</em> based on priors (points where the value of the function is known). This density is represented by the blue area and the mean is plotted in solid line. The distribution is very peaked (small variance) close to observations whereas we are not confident (high variance) with our estimations of <em>f</em> in unsampled areas.</p><p>At each step, the new point to explore is selected as the maximum of a function called <strong>activation function</strong> (the green one). This function synthesizes the <em>a priori</em> knowledge and the uncertainty about the function to optimize. It is high where the predicted objective function is high (or low if we want to minimize <em>f</em>) and where the uncertainty is also high. In other words, it is high where there is a good chance we find better solutions for our optimization problem.</p><h3>The opposing forces</h3><p>In this section we provide a non exhaustive list of auto ML solutions currently available. We arbitrarily chose a few summary features to compare them: Is it a open source package? Which backend models implementation and hyperparameters tuning algorithms are used? How many contributors?</p><p>These features, when they where available, were gathered in the table below. Note that it is a snapshot of these libraries at the time this article was written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkkU5q9KHFAHwG_3vvkaaw.png" /><figcaption>Figure 4: AutoML solutions snapshot (05/2018)</figcaption></figure><p>We could play with a few of these auto ML solutions. Our tests are summarized in the following section.</p><h3>Benchmark</h3><h4>Protocol</h4><p>We chose four frameworks to test. The main selection criteria where the diversity and community involved (number of contributors, recency of the last commit).</p><ul><li>AWS Machine Learning (version available on 2017/12/05)</li><li>Autosklearn 0.2.0</li><li>H2O 3.16</li><li>TPOT 0.9.1</li></ul><p>These packages were benchmarked on three classical datasets available on <a href="https://www.kaggle.com/">Kaggle</a>:</p><ul><li>A <strong>binary classification</strong> problem: <a href="https://www.kaggle.com/c/titanic">Titanic survival prediction</a></li><li>A <strong>multiclass classification</strong> challenge: <a href="https://www.kaggle.com/c/digit-recognizer">Digit recognizer</a> based on the MNIST dataset</li><li>A <strong>regression</strong> problem: <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques">House prices</a></li></ul><p>This way, we can compare the results to the general leaderboards (and an army of talented data scientists) on different kinds of supervized learning problems.</p><p>We trained each solution on the training set during <strong>1 hour</strong> on <strong>32 cores — 256Go RAM</strong> server and then submitted the predictions on the test set on Kaggle. The results are provided in the figures below.</p><h4>Results</h4><p>For each challenge, we plotted the metric value depending on the ranking of the solution for the whole leaderboard and located the libraries we tested on these plots. Basic baseline solutions are also provided.</p><p><strong>Titanic challenge (binary classification):</strong></p><ul><li>metric: <em>accuracy</em> (percentage of correctly predicted labels)</li><li>number of challengers: 11164 teams (11700 competitors)</li><li>number of features: 9</li><li>number of samples: 891 in the training set, 418 in the test set</li><li>baseline: predictions based on gender (men die and women survive)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep__7E8aAJw89U8PGcNv-A.png" /><figcaption>Figure 5: Titanic challenge benchmark</figcaption></figure><p>This curve shows for instance that the top 20% solutions reached more than 80% accuracy.</p><p><strong>MNIST (multiclass classification):</strong></p><ul><li>metric: <em>accuracy</em></li><li>number of challengers: 2288 teams (2345 contributors)</li><li>number of features: 784</li><li>number of samples: 42000 in the training set, 28000 in the test set</li><li>baseline: k nearest neighbors with k=1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcri1PNZ-EQKIbLECTgbnA.png" /><figcaption>Figure 6: MNIST challenge benchmark</figcaption></figure><p><strong>House prices (regression):</strong></p><ul><li>metric: <em>root mean squared error (RMSE)</em></li><li>number of challengers: 5123 teams (5397 competitors)</li><li>number of features: 268</li><li>number of samples: 1460 in the training set, 1459 in the test set</li><li>baseline: linear regression (area, number of bedrooms, year and month of sale)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFiBQUjontR5ZsCW9CyMWw.png" /><figcaption>Figure 7: House prices challenge benchmark</figcaption></figure><h3>Conclusion</h3><p>In practice, the <a href="https://hackernoon.com/tagged/open-source">open source</a> frameworks needed some <strong>data preparation </strong>and <strong>cleaning</strong> (binarization, null values handling…). Only commercial solutions offer the complete pipeline, from features engineering to models deployment.</p><p>Moreover, hyperparameters tuning algorithms sometimes need to be <strong>parameterized</strong>. It is for instance the case for the genetic algorithm used by TPOT.</p><p>Open source Auto ML solutions <strong>does not perform better than human</strong> data scientists (top 20–80% on the leaderboard depending on the challenge) but can help get convenient levels of accuracy with a minimum effort and amount of time.</p><p>Keep in mind that <strong>feature engineering is the key:</strong></p><blockquote>“One of the holy grails of machine learning is to automate more and more of the feature engineering process” — <a href="https://bit.ly/things_to_know_ml"><strong>Pedro Domingo</strong>s, <em>A Few Useful Things to Know about Machine Learning</em></a></blockquote><p>This is where most of the effort in a machine learning project goes because it is a very time-consuming task.</p><h3>Further readings</h3><ul><li><a href="http://bee22.com/resources/Poli%202007.pdf">about particle swarms optimization</a></li><li><a href="http://katrinaeg.com/simulated-annealing.html">about simulated annealing</a></li><li><a href="http://haikufactory.com/files/bayopt.pdf">about bayesian optimization</a></li></ul><blockquote>This post was originally published on <a href="https://techblog.cdiscount.com/"><strong>Cdiscount Techblog</strong></a>.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2826c7807a2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/a-brief-overview-of-automatic-machine-learning-solutions-automl-2826c7807a2a">A brief overview of Automatic Machine Learning solutions (AutoML)</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part-of-Speech tagging tutorial with the Keras Deep Learning library]]></title>
            <link>https://becominghuman.ai/part-of-speech-tagging-tutorial-with-the-keras-deep-learning-library-d7f93fa05537?source=rss-cb6044f0ca86------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7f93fa05537</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Cdiscount Data Science]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 12:40:34 GMT</pubDate>
            <atom:updated>2018-05-29T13:41:42.447Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>In this tutorial, you will see how you can use a simple Keras model to train and evaluate an artificial neural network for multi-class classification problems.</em></h4><p><em>by </em><a href="https://www.linkedin.com/in/axelbellec"><em>Axel Bellec</em></a><em> (Data Scientist at </em><a href="http://cdiscount.com/"><strong><em>Cdiscount</em></strong></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBYBy6lReldGq1qNTasU2Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/G9_Euqxpu4k?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joao Tzanno</a> on <a href="https://unsplash.com/search/photos/stamp?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Part-of-Speech tagging is a well-known task in <a href="https://en.wikipedia.org/wiki/Natural_language_processing">Natural Language Processing</a>. It refers to the process of classifying words into their parts of speech (also known as words classes or lexical categories). This is a supervised learning approach.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl2JdWtSlp3Z68ubSM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl2JdWtSlp3Z68ubSM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl2JdWtSlp3Z68ubSM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="331" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f904f3c6fd37e0cec0acbeea93ded2/href">https://medium.com/media/42f904f3c6fd37e0cec0acbeea93ded2/href</a></iframe><p><a href="https://en.wikipedia.org/wiki/Artificial_neural_network">Artificial neural networks</a> have been applied successfully to compute POS tagging with great performance. We will focus on the Multilayer Perceptron Network, which is a very popular network architecture, considered as the state of the art on Part-of-Speech tagging problems.</p><p><strong>Let’s put it into practice!</strong></p><p>In this post you will get a quick tutorial on how to implement a simple Multilayer Perceptron in Keras and train it on an annotated corpus.</p><figure><a href="https://www.eventbrite.com/e/chatbot-conference-tickets-45884424549?utm-medium=discovery&amp;utm-campaign=social&amp;utm-content=attendeeshare&amp;aff=escb&amp;utm-source=cp&amp;utm-term=listing"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyftTzPL9qaCYc8z2EbcHg.png" /></a></figure><h3>Ensuring reproducibility</h3><p>In order to be sure that our experiences can be achieved again we need to fix the random seed for reproducibility:</p><pre>import numpy as np</pre><pre>CUSTOM_SEED = 42<br>np.random.seed(CUSTOM_SEED)</pre><h3>Getting an annotated corpus</h3><p>The <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.9.8216&amp;rep=rep1&amp;type=pdf">Penn Treebank</a> is an annotated corpus of POS tags. A sample is available in the <a href="https://github.com/nltk/nltk">NLTK</a> python library which contains a lot of corpora that can be used to train and test some NLP models.</p><p>First of all, we download the annotated corpus:</p><pre>import nltk</pre><pre>nltk.download(&#39;treebank&#39;)</pre><p>Then we load the tagged sentences…</p><pre>from nltk.corpus import treebank</pre><pre>sentences = treebank.tagged_sents(tagset=&#39;universal&#39;)</pre><p>… and visualize one:</p><pre>import random</pre><pre>print(random.choice(sentences))</pre><p>This yields a list of tuples (term, tag).</p><pre>[(&#39;Mr.&#39;, &#39;NOUN&#39;), (&#39;Otero&#39;, &#39;NOUN&#39;), (&#39;,&#39;, &#39;.&#39;), (&#39;who&#39;, &#39;PRON&#39;), (&#39;apparently&#39;, &#39;ADV&#39;), (&#39;has&#39;, &#39;VERB&#39;), (&#39;an&#39;, &#39;DET&#39;), (&#39;unpublished&#39;, &#39;ADJ&#39;), (&#39;number&#39;, &#39;NOUN&#39;), (&#39;,&#39;, &#39;.&#39;), (&#39;also&#39;, &#39;ADV&#39;), (&#39;could&#39;, &#39;VERB&#39;), (&quot;n&#39;t&quot;, &#39;ADV&#39;), (&#39;be&#39;, &#39;VERB&#39;), (&#39;reached&#39;, &#39;VERB&#39;), (&#39;.&#39;, &#39;.&#39;)]</pre><p>This is a multi-class classification problem with more than forty different classes.]</p><h3>Top 3 Most Popular Ai Articles:</h3><blockquote><a href="https://becominghuman.ai/tensorflow-object-detection-api-tutorial-training-and-evaluating-custom-object-detector-ed2594afcf73">1. TensorFlow Object Detection API tutorial</a></blockquote><blockquote><a href="https://becominghuman.ai/deep-learning-book-notes-chapter-1-b310837c76cf">2. Deep Learning Book Notes, Chapter 1</a></blockquote><blockquote><a href="https://becominghuman.ai/deep-learning-book-notes-chapter-2-linear-algebra-for-deep-learning-af776cf52506">3. Deep Learning Book Notes, Chapter 2</a></blockquote><p>POS tagging on Treebank corpus is a well-known problem and we can expect to achieve a model accuracy larger than 95%.</p><pre>tags = set([<br>    tag for sentence in treebank.tagged_sents() <br>    for _, tag in sentence<br>])<br>print(&#39;nb_tags: %sntags: %s&#39; % (len(tags), tags))</pre><p>This yields:</p><pre>46<br>{&#39;IN&#39;, &#39;VBZ&#39;, &#39;.&#39;, &#39;RP&#39;, &#39;DT&#39;, &#39;VB&#39;, &#39;RBR&#39;, &#39;CC&#39;, &#39;#&#39;, &#39;,&#39;, &#39;VBP&#39;, &#39;WP$&#39;, &#39;PRP&#39;, &#39;JJ&#39;, <br>&#39;RBS&#39;, &#39;LS&#39;, &#39;PRP$&#39;, &#39;WRB&#39;, &#39;JJS&#39;, &#39;``&#39;, &#39;EX&#39;, &#39;POS&#39;, &#39;WP&#39;, &#39;VBN&#39;, &#39;-LRB-&#39;, &#39;-RRB-&#39;, <br>&#39;FW&#39;, &#39;MD&#39;, &#39;VBG&#39;, &#39;TO&#39;, &#39;$&#39;, &#39;NNS&#39;, &#39;NNPS&#39;, &quot;&#39;&#39;&quot;, &#39;VBD&#39;, &#39;JJR&#39;, &#39;:&#39;, &#39;PDT&#39;, &#39;SYM&#39;, <br>&#39;NNP&#39;, &#39;CD&#39;, &#39;RB&#39;, &#39;WDT&#39;, &#39;UH&#39;, &#39;NN&#39;, &#39;-NONE-&#39;}</pre><h3>Datasets preprocessing for supervised learning</h3><p>We split our tagged sentences into 3 datasets :</p><ul><li>a <strong>training dataset</strong> which corresponds to the sample data used to fit the model,</li><li>a <strong>validation dataset</strong> used to tune the parameters of the classifier, for example to choose the number of units in the neural network,</li><li>a <strong>test dataset</strong> used <em>only</em> to assess the performance of the classifier.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*DEDwnWZCWoaCAQQq5RG0xg.png" /><figcaption>We use approximately 60% of the tagged sentences for training, 20% as the validation set and 20% to evaluate our model.</figcaption></figure><pre>train_test_cutoff = int(.80 * len(sentences)) <br>training_sentences = sentences[:train_test_cutoff]<br>testing_sentences = sentences[train_test_cutoff:]</pre><pre>train_val_cutoff = int(.25 * len(training_sentences))<br>validation_sentences = training_sentences[:train_val_cutoff]<br>training_sentences = training_sentences[train_val_cutoff:]</pre><h3>Feature engineering</h3><p>Our set of features is very simple.<br>For each term we create a dictionnary of features depending on the sentence where the term has been extracted from.<br>These properties could include informations about previous and next words as well as prefixes and suffixes.</p><pre>def add_basic_features(sentence_terms, index):<br>    &quot;&quot;&quot; Compute some very basic word features.</pre><pre>        :param sentence_terms: [w1, w2, ...] <br>        :type sentence_terms: list<br>        :param index: the index of the word <br>        :type index: int<br>        :return: dict containing features<br>        :rtype: dict<br>    &quot;&quot;&quot;<br>    term = sentence_terms[index]<br>    return {<br>        &#39;nb_terms&#39;: len(sentence_terms),<br>        &#39;term&#39;: term,<br>        &#39;is_first&#39;: index == 0,<br>        &#39;is_last&#39;: index == len(sentence_terms) - 1,<br>        &#39;is_capitalized&#39;: term[0].upper() == term[0],<br>        &#39;is_all_caps&#39;: term.upper() == term,<br>        &#39;is_all_lower&#39;: term.lower() == term,<br>        &#39;prefix-1&#39;: term[0],<br>        &#39;prefix-2&#39;: term[:2],<br>        &#39;prefix-3&#39;: term[:3],<br>        &#39;suffix-1&#39;: term[-1],<br>        &#39;suffix-2&#39;: term[-2:],<br>        &#39;suffix-3&#39;: term[-3:],<br>        &#39;prev_word&#39;: &#39;&#39; if index == 0 else sentence_terms[index - 1],<br>        &#39;next_word&#39;: &#39;&#39; if index == len(sentence_terms) - 1 else sentence_terms[index + 1]<br>    }</pre><p>We map our list of sentences to a list of dict features.</p><pre>def untag(tagged_sentence):<br>    &quot;&quot;&quot; <br>    Remove the tag for each tagged term.</pre><pre>:param tagged_sentence: a POS tagged sentence<br>    :type tagged_sentence: list<br>    :return: a list of tags<br>    :rtype: list of strings<br>    &quot;&quot;&quot;<br>    return [w for w, _ in tagged_sentence]</pre><pre>def transform_to_dataset(tagged_sentences):<br>    &quot;&quot;&quot;<br>    Split tagged sentences to X and y datasets and append some basic features.</pre><pre>:param tagged_sentences: a list of POS tagged sentences<br>    :param tagged_sentences: list of list of tuples (term_i, tag_i)<br>    :return: <br>    &quot;&quot;&quot;<br>    X, y = [], []</pre><pre>for pos_tags in tagged_sentences:<br>        for index, (term, class_) in enumerate(pos_tags):<br>            # Add basic NLP features for each sentence term<br>            X.append(add_basic_features(untag(pos_tags), index))<br>            y.append(class_)<br>    return X, y</pre><p>For training, validation and testing sentences, we split the attributes into X (input variables) and y (output variables).</p><pre>X_train, y_train = transform_to_dataset(training_sentences)<br>X_test, y_test = transform_to_dataset(testing_sentences)<br>X_val, y_val = transform_to_dataset(validation_sentences)</pre><h3>Features encoding</h3><p>Our neural network takes vectors as inputs, so we need to convert our dict features to vectors.<br>sklearn builtin function <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html">DictVectorizer</a> provides a straightforward way to do that.</p><pre>from sklearn.feature_extraction import DictVectorizer</pre><pre># Fit our DictVectorizer with our set of features<br>dict_vectorizer = DictVectorizer(sparse=False)<br>dict_vectorizer.fit(X_train + X_test + X_val)</pre><pre># Convert dict features to vectors<br>X_train = dict_vectorizer.transform(X_train)<br>X_test = dict_vectorizer.transform(X_test)<br>X_val = dict_vectorizer.transform(X_val)</pre><p>Our y vectors must be encoded. The output variable contains 49 different string values that are encoded as integers.</p><pre>from sklearn.preprocessing import LabelEncoder</pre><pre># Fit LabelEncoder with our list of classes<br>label_encoder = LabelEncoder()<br>label_encoder.fit(y_train + y_test + y_val)</pre><pre># Encode class values as integers<br>y_train = label_encoder.transform(y_train)<br>y_test = label_encoder.transform(y_test)<br>y_val = label_encoder.transform(y_val)</pre><p>And then we need to convert those encoded values to dummy variables (one-hot encoding).</p><pre># Convert integers to dummy variables (one hot encoded)<br>from keras.utils import np_utils</pre><pre>y_train = np_utils.to_categorical(y_train)<br>y_test = np_utils.to_categorical(y_test)<br>y_val = np_utils.to_categorical(y_val)</pre><h3>Building a Keras model</h3><p><a href="https://github.com/fchollet/keras/">Keras</a> is a high-level framework for designing and running neural networks on multiple backends like <a href="https://github.com/tensorflow/tensorflow/">TensorFlow</a>, <a href="https://github.com/Theano/Theano">Theano</a> or <a href="https://github.com/Microsoft/CNTK">CNTK</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*jv-i8ieZA9AKk5j-avbCWg.png" /></figure><p>We want to create one of the most basic neural networks: the Multilayer Perceptron. This kind of linear stack of layers can easily be made with the Sequential model. This model will contain an input layer, an hidden layer, and an output layer.<br>To overcome overfitting, we use dropout regularization. We set the dropout rate to 20%, meaning that 20% of the randomly selected neurons are ignored during training at each update cycle.</p><p>We use <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)"><em>Rectified Linear Units</em></a> (ReLU) activations for the hidden layers as they are the simplest non-linear activation functions available.</p><p>For multi-class classification, we may want to convert the units outputs to probabilities, which can be done using the <em>softmax</em> function. We decide to use the <em>categorical cross-entropy</em> loss function.<br>Finally, we choose <a href="https://arxiv.org/abs/1412.6980">Adam optimizer</a> as it seems to be well suited to classification tasks.</p><pre>from keras.models import Sequential<br>from keras.layers import Dense, Dropout, Activation</pre><pre>def build_model(input_dim, hidden_neurons, output_dim):<br>    &quot;&quot;&quot;<br>    Construct, compile and return a Keras model which will be used to fit/predict<br>    &quot;&quot;&quot;<br>    model = Sequential([<br>        Dense(hidden_neurons, input_dim=input_dim),<br>        Activation(&#39;relu&#39;),<br>        Dropout(0.2),<br>        Dense(hidden_neurons),<br>        Activation(&#39;relu&#39;),<br>        Dropout(0.2),<br>        Dense(output_dim, activation=&#39;softmax&#39;)<br>    ])</pre><pre>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>    return model</pre><h3>Creating a wrapper between Keras API and Scikit-Learn</h3><p><a href="https://github.com/fchollet/keras/">Keras</a> provides a wrapper called <a href="https://keras.io/scikit-learn-api/">KerasClassifier</a> which implements the <a href="http://scikit-learn.org/stable/">Scikit-Learn</a> classifier interface.</p><p>All model parameters are defined below. We need to provide a function that returns the structure of a neural network (build_fn).<br>The number of hidden neurons and the batch size are choose quite arbitrarily. We set the number of epochs to 5 because with more iterations the Multilayer Perceptron starts overfitting (even with <a href="https://arxiv.org/abs/1207.0580">Dropout Regularization</a>).</p><pre>from keras.wrappers.scikit_learn import KerasClassifier</pre><pre>model_params = {<br>    &#39;build_fn&#39;: build_model,<br>    &#39;input_dim&#39;: X_train.shape[1],<br>    &#39;hidden_neurons&#39;: 512,<br>    &#39;output_dim&#39;: y_train.shape[1],<br>    &#39;epochs&#39;: 5,<br>    &#39;batch_size&#39;: 256,<br>    &#39;verbose&#39;: 1,<br>    &#39;validation_data&#39;: (X_val, y_val),<br>    &#39;shuffle&#39;: True<br>}</pre><pre>clf = KerasClassifier(**model_params)</pre><h3>Training our Keras model</h3><p>Finally, we can train our Multilayer perceptron on train dataset.</p><pre>hist = clf.fit(X_train, y_train)</pre><p>With the callback history provided we can visualize the model <em>log loss</em> and <em>accuracy</em> against time.</p><pre>import matplotlib.pyplot as plt</pre><pre>def plot_model_performance(train_loss, train_acc, train_val_loss, train_val_acc):<br>    &quot;&quot;&quot; Plot model loss and accuracy through epochs. &quot;&quot;&quot;</pre><pre>    blue= &#39;#34495E&#39;<br>    green = &#39;#2ECC71&#39;<br>    orange = &#39;#E23B13&#39;</pre><pre>    # plot model loss<br>    fig, (ax1, ax2) = plt.subplots(2, figsize=(10, 8))<br>    ax1.plot(range(1, len(train_loss) + 1), train_loss, blue, linewidth=5, label=&#39;training&#39;)<br>    ax1.plot(range(1, len(train_val_loss) + 1), train_val_loss, green, linewidth=5, label=&#39;validation&#39;)<br>    ax1.set_xlabel(&#39;# epoch&#39;)<br>    ax1.set_ylabel(&#39;loss&#39;)<br>    ax1.tick_params(&#39;y&#39;)<br>    ax1.legend(loc=&#39;upper right&#39;, shadow=False)<br>    ax1.set_title(&#39;Model loss through #epochs&#39;, color=orange, fontweight=&#39;bold&#39;)</pre><pre>    # plot model accuracy<br>    ax2.plot(range(1, len(train_acc) + 1), train_acc, blue, linewidth=5, label=&#39;training&#39;)<br>    ax2.plot(range(1, len(train_val_acc) + 1), train_val_acc, green, linewidth=5, label=&#39;validation&#39;)<br>    ax2.set_xlabel(&#39;# epoch&#39;)<br>    ax2.set_ylabel(&#39;accuracy&#39;)<br>    ax2.tick_params(&#39;y&#39;)<br>    ax2.legend(loc=&#39;lower right&#39;, shadow=False)<br>    ax2.set_title(&#39;Model accuracy through #epochs&#39;, color=orange, fontweight=&#39;bold&#39;)</pre><p>Then, display model performance:</p><pre>plot_model_performance(<br>    train_loss=hist.history.get(&#39;loss&#39;, []),<br>    train_acc=hist.history.get(&#39;acc&#39;, []),<br>    train_val_loss=hist.history.get(&#39;val_loss&#39;, []),<br>    train_val_acc=hist.history.get(&#39;val_acc&#39;, [])<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*QplV6zmPAXmFPNMngI8qcQ.png" /><figcaption>Model performance vs. epochs</figcaption></figure><p>After 2 epochs, we see that our model begins to overfit.</p><h3>Evaluating our multilayer perceptron</h3><p>Since our model is trained, we can evaluate it (compute its accuracy):</p><pre>score = clf.score(X_test, y_test)<br>print(score)</pre><pre>[Out] 0.95816</pre><p>We are pretty close to 96% accuracy on test dataset, that is quite impressive when you look at the basic features we injected in the model.<br>Keep also in mind that 100% accuracy is not possible even for human annotators. We estimate humans can do Part-of-Speech tagging at about 98% accuracy.</p><h3>Visualizing the model</h3><pre>from keras.utils import plot_model</pre><pre>plot_model(clf.model, to_file=&#39;model.png&#39;, show_shapes=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*jJLD2eI0saZx_rszhPFrYg.png" /></figure><h3>Save the Keras model</h3><p>Saving a Keras model is pretty simple as a method is provided natively:</p><pre>clf.model.save(&#39;/tmp/keras_mlp.h5&#39;)</pre><p>This saves the architecture of the model, the weights as well as the training configuration (loss, optimizer).</p><h4>Ressources</h4><ul><li><em>Keras: The Python Deep Learning library</em>: <a href="https://keras.io/">[doc]</a></li><li><em>Adam: A Method for Stochastic Optimization</em>: <a href="https://arxiv.org/abs/1412.6980">[paper]</a></li><li><em>Improving neural networks by preventing co-adaptation of feature detectors: </em><a href="https://arxiv.org/abs/1207.0580">[paper]</a></li></ul><p>In this post, you learn how to define and evaluate accuracy of a neural network for multi-class classification using the Keras library.<br>The script used to illustrate this post is provided here : [<a href="https://github.com/Cdiscount/IT-Blog/blob/master/scripts/pos_tagging_neural_nets_keras.py">.py</a>|<a href="https://github.com/Cdiscount/IT-Blog/blob/master/scripts/pos_tagging_neural_nets_keras.ipynb">.ipynb</a>].</p><blockquote><em>This post was originally published on </em><a href="https://techblog.cdiscount.com/"><strong><em>Cdiscount Techblog</em></strong></a><em>.</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F8f5f8b%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F8f5f8b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href">https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href</a></iframe><figure><a href="https://becominghuman.ai/artificial-intelligence-communities-c305f28e674c"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*2f7OqE2AJK1KSrhkmD9ZMw.png" /></a></figure><figure><a href="https://upscri.be/8f5f8b"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*v-PpfkSWHbvlWWamSVHHWg.png" /></a></figure><figure><a href="https://becominghuman.ai/write-for-us-48270209de63"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Wt2auqISiEAOZxJ-I7brDQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7f93fa05537" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/part-of-speech-tagging-tutorial-with-the-keras-deep-learning-library-d7f93fa05537">Part-of-Speech tagging tutorial with the Keras Deep Learning library</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A quick experience feedback about the Cdiscount image classification Kaggle competition]]></title>
            <link>https://medium.com/@cdiscountdatascience/a-quick-experience-feedback-about-the-cdiscount-image-classification-kaggle-competition-7c3515ba899b?source=rss-cb6044f0ca86------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c3515ba899b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Cdiscount Data Science]]></dc:creator>
            <pubDate>Fri, 23 Mar 2018 15:16:50 GMT</pubDate>
            <atom:updated>2018-03-27T12:49:11.289Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A few months ago, we launched a data science competition on the famous <a href="https://www.kaggle.com/"><strong>Kaggle</strong></a> platform. The aim was to develop a product classifier based on image analysis. Indeed, our catalog is made up of more than 30 million products. Making sure they are all well classified is very challenging as well as crucial given that numerous critical algorithms (search engine ranking, product recommendation, <em>etc</em>) rely on product categorization.<br>So far we applied text mining techniques to the text descriptions of the products to predict their category. A previous <a href="https://www.datascience.net/fr/home/">challenge</a> hosted on the French platform <a href="https://www.datascience.net/fr/challenge/20/details"><strong>datascience.net</strong></a> was dedicated to this approach. Nonetheless, we were convinced that a substantial uplift could be reached by integrating images in the pipeline.</p><p>The data set provided for the challenge contains more than 15 million images of about 9 million products (<em>i.e</em> almost half of our current catalog), making it one of the largest public database of labelled images. These products are divided into more than 5000 categories, which makes this challenge an <strong>extreme multimodal classification</strong> problem. The winners of the contest shared a $35,000 prize.</p><p>The challenge concluded on December 14, 2017 and promises were kept! More than 750 competitors (distributed into 627 teams) took part in the challenge, among which some of the most talented data scientists and deep learning experts around the world. <strong>Figure 1</strong> shows the evolution of the accuracy during the challenge</p><p>Results are very impressive as the winner <em>bestfitting</em> (currently №1 at kaggle global ranking) reached <strong>79.6%</strong> accuracy on the private leaderboard and more than 120 competitors overcame 70% of correct categorization (see <strong>Figure 2</strong> below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHqhk7eRO_3aZRiARGzO7w.png" /><figcaption>Figure 1: Evolution of top accuracy and number of teams involved</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h274-ZIRvJX5UJPns9sMMQ.png" /><figcaption>Figure 2: scores distribution</figcaption></figure><h3>Strategies used</h3><p>You can get a good overview of the different machine learning algorithms used by the competitors looking at the dedicated <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion">Discussion section</a> on Kaggle or reading the <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45863">winner’s post</a>. We were able to identify some key success factors which are described below.</p><h4>Deep learning rocks!</h4><p>Even if interesting performances could be reached by traditional ML algorithms (see <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/39463">baseline submission</a> for instance), a vast majority of the top ranked solutions involve deep neural networks.<br>The usual python implementations (TensorFlow, Keras, PyTorch) were in the game and the best results were obtained by finetuning well known pretrained deep (convolutional) neural nets such as the different architectures of ResNet, Inception-ResNet, DenseNet…</p><h4>Ensembling methods to climb the last percents of the accuracy curve</h4><p>Strength lies in unity, and ensembling methods built on top of several neural nets allowed to combine the power of the different models, thus improving significantly the accuracy.</p><p>In <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45733">this topic</a>, the authors explain how they gathered outputs from several CNNs. Each individual model has a respectable accuracy (about <strong>74–75%</strong>) but combining them, even by simply average leads to a <strong>77.5%</strong> score. Adding a multi-layer ensembling algorithm (based on classical ML techniques such as XGBoost, Random Forest and other variants) further improves the accuracy of the pipeline (<strong>78.7%</strong>).</p><p>Similarly, numerous efficient solutions were obtained by teams of up to five data scientists merging their individual models andshowing the strength of the Kaggle community.</p><h4>Other tricks that make the difference</h4><p>Most of the top 20 competitors or teams applied ensembling methods over finetuned CNNs. How to stand out and get the small plus that makes you win the competition?</p><p>Different tricks were found by competitors to finetune models or prepare data, some of which are described below.</p><p>A particularity of the data set is that we provided up to 4 pictures per product. Using only the first one is often enough to find the category but in some difficult cases combining the distinct images of the product can help. Consequently, several competitors used combinations or concatenations of the pictures to improve their models. For instance, the winner (see his solution <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45863">here</a>) concatenated images of the same product into one single “mozaic” picture. Then he designed separated models for products with 1, 2, 3 or 4 pictures.</p><p>Examples are provided below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eYPKr4UM2aBToFeQ1u_q2Q.png" /><figcaption>Figure 3: the first picture seems informative enough.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*GwBbVA3wYHHGdK8j_eZ5qA.png" /><figcaption>Figure 4: all pictures are informative.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*R-a0FMvUE8eFtOUKBz9Cjw.png" /><figcaption>Figure 5: the first image doesn’t seem the easiest to deal with because of the background.</figcaption></figure><p>In the top raw (<strong>Figure 3</strong>), the first image seems to be the most relevant to predict the category. In the middle case (<strong>Figure 4</strong>), pictures are taken under distinct angles so we can believe that they are all informative. In the last raw (<strong>Figure 5</strong>), the first picture presents the item within its background which can make the classification task harder. Conversely the second one seems easier to process as there is no background. In the last two cases, using the whole set of images is probably more efficient than dealing with only one picture.</p><p>Another clever key feature of the winner’s solution is to use an optical character recognition (OCR) algorithm to extract text from the pictures. Indeed, he noticed that for some categories of products, such as CDs or books, the shape is not super informative whereas the text appearing in the pictures can potentially help.</p><p>If you are interested in more detailed insights on the algorithms and tricks used by the competitors you’ll find interesting topics in the <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion">discussion channel</a>.</p><h4>High performance hardware configurations</h4><p>It is well known that training deep learning methods is very computationally expensive, especially when dealing with huge amounts of pictures. This competition and the discussions about hardware (see <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45724">this topic</a>) give a good overview of the state of the art setups. The key finding, as you may expect, is that you need (powerful) GPUs. And the more, the better! Common hardwares are composed for instance of up to four 1080ti or Titan GPUs generally combined with 64Gb RAM and SSD storage.</p><h3>Conclusion</h3><p>The competition is a great success for Cdiscount as we could reach impressive categorization rates and learn a lot from the winning solutions. Kaggle community showed its efficiency to address such a complicated problem, taking benefit from the emulation and the mutual assistance between its brilliant members. <br>We hope that such a large labelled image dataset has the potential to contribute to deep learning improvements thanks to the amount of pictures now available and the large number of classes.</p><p>We will now test in real conditions the winning algorithms and combine it to our current text based categorization algorithm to improve our pipeline.</p><p>Thanks again to Kaggle and all the competitors who, thanks to their time, efforts and talent, had make it a success!</p><p>See you soon!</p><p>Julien Jouganous, Data Scientist at Cdiscount</p><h3>References</h3><h4>A few links</h4><ul><li><a href="https://www.datascience.net/fr/challenge/20/details">the previous challenge</a> on text based classification on <strong>datascience.net,</strong></li><li>Cdiscount Kaggle challenge <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge">homepage</a>,</li><li>the <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge">discussion channel</a>.</li></ul><h4><strong>Some interesting topics</strong></h4><ul><li>the winning <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45863">solution</a>,</li><li>an efficient <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45850">single model solution</a>,</li><li>a few other top ranked algorithms: <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45733">here</a>, <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45709">here</a> or <a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45737">there</a>,</li><li><a href="https://www.kaggle.com/c/cdiscount-image-classification-challenge/discussion/45724">hardware configurations</a>.</li></ul><blockquote>This post was originally published on <a href="https://techblog.cdiscount.com/"><strong>Cdiscount Techblog</strong></a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c3515ba899b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>