<?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 Prachi Jain on Medium]]></title>
        <description><![CDATA[Stories by Prachi Jain on Medium]]></description>
        <link>https://medium.com/@prachijain-cs12?source=rss-a9b6c476fde------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*u2i7ruGOVohxmNWK1YHDOg.jpeg</url>
            <title>Stories by Prachi Jain on Medium</title>
            <link>https://medium.com/@prachijain-cs12?source=rss-a9b6c476fde------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:46:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prachijain-cs12/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[Combat Human Trafficking by similar Hotels Recognition using images]]></title>
            <link>https://becominghuman.ai/combat-human-trafficking-by-similar-hotels-recognition-using-images-e5e67e66c060?source=rss-a9b6c476fde------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5e67e66c060</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[faiss]]></category>
            <dc:creator><![CDATA[Prachi Jain]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 08:59:32 GMT</pubDate>
            <atom:updated>2021-08-06T13:53:50.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIbH1LKIBwaFq03Y5uhabw.jpeg" /></figure><h3>Table of Contents</h3><ol><li><a href="#2282">The problem</a></li><li><a href="#6306">The challenges</a></li><li><a href="#4e00">Data Collection and description</a></li><li><a href="#b5aa">Expected Outcome</a></li><li><a href="#a063">Basic Workflow</a></li><li><a href="#8a53">Some similar approaches already explored</a></li><li><a href="#7505">Our roadmap to the solution</a></li></ol><ul><li><a href="#27ea">EDA</a></li><li><a href="#90e7">Loss Used</a></li><li><a href="#014f">Data Preprocessing</a></li><li><a href="#2cea">The Model</a></li><li><a href="#d742">The Inference</a></li><li><a href="#fdbc">Results</a></li></ul><p>8. <a href="#e034">Scope for improvements</a></p><p>9. <a href="#300b">References</a></p><h3>1. The problem</h3><p><a href="http://www.exchangeinitiative.com/">Exchange Initiative</a> is an organisation fighting back against sex trafficking. To create image search tools for human trafficking investigators, they created the <a href="https://techcrunch.com/2016/06/25/traffickcam/">TraffickCam mobile application</a>, allowing travellers to submit photos of their hotel room. Today, the organisation’s database contains 1.5 million photos from more than 145,000 hotels in the U.S., a combination of photos taken by early users of the app and from publicly available sources of hotel room images.</p><p>They organised a <a href="https://www.kaggle.com/c/hotel-id-2021-fgvc8/overview">Kaggle competition</a> to call novel approaches for a <strong>hotel recognition</strong> solution for human trafficking investigations since victims are often photographed in hotel rooms. Identifying these hotels is vital to trafficking investigations as they can help track down current and future victims who might be taken to the same places. We want to identify the hotel seen in test images from the TraffickCam dataset, which are based on a large gallery of training images with known hotel IDs. <strong>For any test image, we should predict the most similar hotel id’s sorted in the most relevant to least relevant order.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6_QRIlnCooqB33m-bhORw.jpeg" /><figcaption>Given an input image of a hotel room, we are interested to identify the top n number of similar Hotels IDs for it Image Source:<a href="https://www2.seas.gwu.edu/~pless/papers/Hotels50k.pdf">https://www2.seas.gwu.edu/~pless/papers/Hotels50k.pdf</a></figcaption></figure><h3>2. The challenges</h3><p>It has been observed that there can be <em>little</em> similarity between different rooms within the same hotel, and <em>high</em> similarity between rooms from different hotels (especially if they are from the same hotel chain). It implies that with a large number of classes in each image, here we have potentially <strong>high intraclass</strong> and <strong>low inter class variation</strong>. Recognising a hotel from images is challenging because of <em>low image quality, uncommon camera perspectives, large occlusions (often the victim)</em>, and the <em>similarity of objects</em> (e.g., furniture, art, bedding) across different hotel rooms.</p><p>Identifying the <em>chain</em> could narrow the range of possibilities, but only down to a set that is <strong>much harder to tell apart</strong> and is still scattered across a wide geographic area. So, the real value lies in getting the number of candidates to a small enough number that a human investigator could follow up on all of them.</p><figure><a href="https://aijobsboard.com/?fbclid=IwAR0GcsLs8A6CFM-fynrZMM3sTgo_Zpbto2CjglJm0Dmi6otC6YWc7CDFpQk"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAlwXfVrtYspdCzmC8iADw.png" /></a><figcaption>Big Data Jobs</figcaption></figure><h3>3. Data Collection and description</h3><p>The data has been provided at <a href="https://www.kaggle.com/c/hotel-id-2021-fgvc8/data">https://www.kaggle.com/c/hotel-id-2021-fgvc8/data</a></p><p>So, the given dataset in the Kaggle problem consists of hotel room images that have been crowd-sourced and uploaded through the TraffickCam mobile application. It is a rich dataset of photos of hotel room interiors, without any people present, for this task.</p><p>The training set contains <strong>97000+</strong> images from around <strong>7700 hotels</strong> from across the globe. All of the images for each hotel chain are in a dedicated subfolder for that chain.</p><h3>Trending AI Articles:</h3><blockquote><a href="https://becominghuman.ai/why-corporate-ai-projects-fail-part-1-4-3b820041ab00">1. Why Corporate AI projects fail?</a></blockquote><blockquote><a href="https://becominghuman.ai/how-ai-will-power-the-next-wave-of-healthcare-innovation-695a2196aae8">2. How AI Will Power the Next Wave of Healthcare Innovation?</a></blockquote><blockquote><a href="https://becominghuman.ai/machine-learning-by-using-regression-model-f0c7993a66c8">3. Machine Learning by Using Regression Model</a></blockquote><blockquote><a href="https://becominghuman.ai/top-data-science-platforms-in-2021-other-than-kaggle-a1b4609c06b0">4. Top Data Science Platforms in 2021 Other than Kaggle</a></blockquote><h3>4. Expected Outcome</h3><p>For each image in the test set, we must predict a space-delimited list of hotel IDs that could match that image. The list should be sorted such that the first ID is considered the most relevant one and the last the least relevant one.</p><p>The table below shows the expected solution format.</p><pre>image, hotel_id <br>99e91ad5f2870678.jpg, 36363 53586 18807 64314 60181<br>b5cc62ab665591a9.jpg, 36363 53586 18807 64314 60181<br>d5664a972d5a644b.jpg, 36363 53586 18807 64314 60181</pre><h3>5. Basic Workflow</h3><p>The overview of the expected pipeline looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*3Zi3_VUAYh5w78KGLoO37g.png" /><figcaption>Input, Data Processing, and Training for the hotel images</figcaption></figure><h3>6. Some similar approaches already explored</h3><p>There have been various research works and experiments performed in the area of <em>fine-grained visual recognition</em> tasks like this in one form or the other. Some of them are summarised below to give a brief overview of the scope:</p><ul><li><em>Transfer learning in practice. Image classification for hotel images with fast.ai library (</em><a href="https://nexocode.com/blog/posts/transfer-learning-in-practice/"><em>Link</em></a><em>): </em>The research team at Nexocode used Fastai for the image classification of hotel images. They collected already classified data from free sources like Kaggle, MIT and the open API of Google Graphics. The first hundred results for each keyword (category) given by the API is usually quite accurate. The images were normalised using fastai. Choosing transfer learning, they used the top layers of <strong>ResNet50</strong> which is trained on ImageNet. Using fastai, they plot a learning rate graph to find a range where the loss is still decreasing. They used a dropout, weight decay regularisation, and data augmentation to prevent overfitting. Achieved an accuracy of 70.4% with a reasonable train and val loss. They further improved it upto 80% by removing unnecessary classes and correcting some wrong labels or removing unrelated images.</li><li><em>Understanding Aesthetics with Deep Learning (</em><a href="https://developer.nvidia.com/blog/understanding-aesthetics-deep-learning/"><em>Link</em></a><em>): </em>The blog by EyeEm talks about the role played by deep learning to help them distinguish the master photographs from the amateur ones. It has been expressed as a mathematical space in which the distance between the two images that are aesthetically pleasing is less than the distance between an aesthetically pleasing one and a mediocre one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*mfPVzlvMLhtnnT5x_CqHAw.png" /></figure><p>They used supervised machine learning, training a VGG-11 model with a hinge loss on their dataset in <strong>triplets form</strong>: query, positive, and negative class. Their main idea took advantage of the image similarity which resulted from the ordering in the triplets.</p><p>They used the Triple Hinge Loss: for a given triplet of two well-crafted images ( <em>I1</em> and<em> I2</em>) and a mediocre one (<em>I3</em>) , to learn a feature representation <em>ψ </em>, such that distance between <em>ψ(I1) </em>and <em>ψ(I2) </em>should be less than the distance between <em>ψ(I1) </em>and <em>ψ(I3)</em>. It is also desirable to ensure that the distance between the positive and negative images is greater by at least a given margin <em>c</em> than the distance between the two positive images. A loss function that can express this is as an extension of the hinge loss function, given by the following equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*hKmNLd_5cbChfqkAmAfCqA.png" /></figure><ul><li><em>Effects of user-provided photos on hotel review helpfulness: An analytical approach with deep learning (</em><a href="https://www.researchgate.net/publication/322477802_Effects_of_user-provided_photos_on_hotel_review_helpfulness_An_analytical_approach_with_deep_leaning"><em>Link</em></a><em>): </em>This paper clearly demonstrates the effect of using image features from deep learning outperform using a text only model in deciding the helpfulness present in a hotel review. CNN aims to detect features layer by layer through multiple simple-to-complex feature extraction steps. Based on simpler features like edges or corners detected by lower layers, CNN can identify more complicated ones such as rectangles or circles in intermediate layers, which can then be stacked to build sophisticated objects like hotels or buildings. A <strong>152-layer deep residual network (ResNet)</strong> was adopted for final image feature representation. The both texts and images in a review were treated as a mixed sequence M = {w1, …,wf, i1, …, is}. The feature sequence was then fed into a LSTM module to construct the holistic representation.</li><li><em>Hotels-50K: A Global Hotel Recognition Dataset by Abby Stylianou , Hong Xuan , Maya Shende , Jonathan Brandt , Richard Souvenir and Robert Pless from George Washington University, Adobe Research, Temple University (</em><a href="https://www2.seas.gwu.edu/~pless/papers/Hotels50k.pdf"><em>Link</em></a><em>): </em>Hotels-50k is a large-scale curated dataset of over 1 million annotated hotel room images from 50,000 unique hotels around the world.It is designed to support research in hotel recognition to aid in criminal investigations. Hotel recognition requires learning both —i) the <em>generic scene recognition</em> (<em>”What type of building is this?”</em>) i.e. shared properties of all of the rooms in a particular hotel, such as its decor or star rating, or commonly used colour profiles, as well as ii)recognising duplicated instances of furniture, art and bedding that may be used in different configurations throughout the hotel i.e. <em>place recognition </em>(<em>”What specific church is this?”</em>). These images include professionally captured photographs from travel websites and crowd-sourced images (submitted by travellers) from a mobile application. The images from travel websites tend to be with excellent lighting conditions, of the nicest rooms in a hotel. While the crowdsourced images, share more visual characteristics with the images used in real-world human trafficking investigations. The crowdsourced images are taken with similar devices, at varying orientations, with luggage and other clutter, and without professional lighting. The images are augmented with increasingly larger ”people-shaped” masks. The masks are generated using silhouettes from ’people’ regions in the MS-COCO semantic labels dataset (Lin et al. 2014).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*7a1UzkTWUSS9rl6Tps_oAQ.png" /><figcaption>The images in the test set are augmented with person-shaped masks of varying sizes</figcaption></figure><p>The results are provided as the <strong>posterior probabilities</strong> of hotel chains or instances for each of the test images. The evaluation metrics include the <strong>average multi-class log loss</strong> and <strong>top-K classification accuracy</strong>. The FIXED-OBJECT method is a <strong>Resnet50 </strong>network trained on ImageNet giving 1001-D output. The FIXED-SCENE method uses a <strong>VGG model</strong> trained on the Places365 dataset with 512-D output of the final pooling layer.The training scheme is the combinatorial variant of <strong>triplet loss</strong> described in (Hermans, Beyer, and Leibe 2017). Images from the batch are randomly selected and rotated between -35 and 35 degrees, cropped between 60% and 100% of the original size, modified with color and brightness, and masked with person shaped silhouettes, similar to the process used for the test data. The chain identification task was simple enough that even the fixed methods not fine-tuned to the task achieved nearly 80% top-5 accuracy on this task.</p><h3>7. Our roadmap to the solution</h3><p>In order to design an effective solution, first, we analyse the interrelationships in the datasets using Exploratory Data Analysis (EDA).</p><h4>EDA</h4><p>The following insights are derived from the dataset:</p><ul><li>The most common hotel ID’s are found about in the range of 0 to 1000 and then keeps falling down for subsequent hotel id’s.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*088ZMXuwmUWnrpbUrDBRmw.png" /></figure><ul><li>The most common hotel chain IDs are observed in the extremes i.e. in the range of 0 to 10 and also a decent number around 70 to 90.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*faQkm5xmF36IRqFQnafXJg.png" /></figure><ul><li>The most number of images taken for any Hotel ID or chain is from 2016 to 2017.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*4_oSSy7rP96w5CWDVrr3PQ.png" /></figure><h4>Loss Used</h4><p>To enhance discriminative power, it becomes imperative to choose an appropriate loss function in recognition tasks. Empirical results have shown great results by incorporating margins in well-established loss functions. Here we use an<strong> Additive Angular Margin Loss (ArcFace)</strong> to obtain highly discriminative features for robust hotel recognition. It finds major applications in area of maximising face class separability but can fit pretty well in our use case also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*EOpeS30soSjSx5fu.jpg" /></figure><p>The softmax loss function ,which is used more commonly, however has some drawbacks. It does not explicitly optimise the feature embedding to enforce higher similarity for intraclass samples and diversity for inter-class samples, which results in a performance gap for deep face recognition under large intra-class appearance variations.</p><p>So the Angular margin losses are constructed by modifying the Softmax loss function (Softmax loss = Softmax activation + Cross-Entropy loss). ArcFace loss transforms the logits, WjTxi=||Wj|| ||xi||cos⁡θj, where θj is the angle between the weight Wj and the feature xi. The individual weight ||Wj||=1 is fixed by l2 normalisation. The embedding feature ||xi|| is fixed by l2 normalisation and re-scaled to s. <em>The normalisation step on features and weights makes the predictions only depend on the angle between the feature and the weight.</em> The learned embedding features are thus distributed on a hypersphere with a radius of s. Finally, an additive angular margin penalty <em>m</em> is added between xi and Wyi to simultaneously enhance the intra-class compactness and inter-class discrepancy. Since the proposed additive angular margin penalty is equal to the geodesic distance margin penalty in the normalised hypersphere, the method is named <strong>ArcFace</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swKDY35Ni8bF_SkojVAWKQ.png" /></figure><p>An angular margin m is added within cos θ. Since cos(θ+ m) is lower than cos(θ) when θ ∈ [0, π − m], the constraint is more stringent for classification.</p><p>A simple pseudo code can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*PO-2JmoACC-H0ifE.png" /></figure><h4>Data Preprocessing</h4><p>Now let’s see how do we pre-process the images in order to make the model learn efficiently.</p><ul><li>To suit the hardware constraints and achieve the most suitable loss and training time tradeoffs, the input images dataset was <em>resized</em> from 1024 to <em>256x256</em> pixels. This reduced the size of the dataset from about 26GB down to a few GBs.</li><li>The hotel ID column i.e. the target column is non-continuous , so it is <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html"><em>label encoded</em></a> so that it can be more representative of the number of classes.</li><li>The shuffled training images are read, resized to <em>64x64</em> and the RGB array values are <em>normalised</em>.</li><li>Random augmentations like <em>flipping, rotation, brightness, saturation, hue,</em> etc. are applied on the image.</li><li>Take a batch of size <em>64</em> from it.</li></ul><h4>The Model</h4><p>A simple description of the architecture of the model used is — first, the ResNet50 model is used as the backbone to get the embeddings for an input image batch, and in the same custom function, these embeddings along with the image labels are used to calculate the Arc Margin Logits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80e3cf4ab0829feac7eb8d03cd15d79/href">https://medium.com/media/f80e3cf4ab0829feac7eb8d03cd15d79/href</a></iframe><p>The model takes the image and the label together as an input, and returns the arc margin as the output.</p><p>The per epoch loss is calculated with a custom softmax function where the <em>sparse_softmax_cross_entropy_with_logits</em> is calculated between the true label and the predicted arc margin logits.</p><p>It took a total of about 200 epochs to get the least loss. A learning rate of 0.01 (reduced to 0.001 for the last 70 epochs) was used with an <em>SGD optimiser + momentum</em> to train the model.</p><p>The best model with weights were saved for faster model access in the future.The tensorboard logs show:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*BlMfdwu1lgJaqVcLTLQfEA.png" /><figcaption>To view the tensorboard for the detailed scalars, histograms, etc., visit <a href="https://tensorboard.dev/experiment/kWKPHLmpQXimixrJ7SYpDg/">https://tensorboard.dev/experiment/kWKPHLmpQXimixrJ7SYpDg/</a></figcaption></figure><h4>The Inference</h4><p>This model was trained to minimise the ArcFace loss using propagation of weights. Now for our use case, the actual purpose of the model is to get the best <em>embeddings</em> for the images. So a new model is created which uses the second last layer of this model(the batch-normalised backbone ResNet50 weights), to output the embeddings. It is created using this <a href="https://stackoverflow.com/questions/42427179/keras-intermediate-layers-output">method</a> and the test model is saved.</p><p>The saved inference model is also then using <a href="https://www.tensorflow.org/lite/performance/post_training_quantization">TFLite</a>, quantised to float16 which reduces the size upto half the original model file size in order to fit the limited memory and run faster after deploying on a cloud application platform like <a href="https://www.heroku.com/home">Heroku</a>.</p><p>The train and test features are generated using the test model and then l2 normalised. Next, the state-of-the-art similarity search technique <a href="https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/">faiss</a> is used to train a <strong>k-means</strong> model for 20 iterations, having number of dimensions as the embeddings dimensions and number of clusters as the number of classes (i.e. number of hotel IDs). It also gives the training total square loss. Creating an IndexFlatL2 from it, the actual centroids are found and saved for each line vector in train embeddings. The index is saved for inference purpose. It can be searched with the test embeddings to get their top-n nearest distance class centroids and their indices. Refer <a href="https://github.com/prachij94/Hotel_id-recognition">Github</a> for the complete code.</p><h4>Results</h4><p>The saved testing model is used in a <a href="https://streamlit.io/">Streamlit</a> app for deploying the solution. A demo video for the app can be viewed <a href="https://drive.google.com/file/d/165DAktN2OO1LuU2BXbsVVfoMjk1cY-6Y/view?usp=sharing">here</a>. The application is live at <a href="http://hotel-id-api.herokuapp.com/">http://hotel-id-api.herokuapp.com/</a></p><p><a href="https://drive.google.com/file/d/165DAktN2OO1LuU2BXbsVVfoMjk1cY-6Y/view">hotel-id-app.mp4</a></p><p>Below are some snapshots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVW-Dcz8LHYjLjZeZ4QCFA.png" /><figcaption>The file uploader</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJO0JWWCps-wxbCnVwlfkw.png" /><figcaption>After a valid image is uploaded, the classification begins</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rz2eyKOUt5-mXnbvUr7lFQ.png" /><figcaption>Top 5 similar hotel IDs are given as results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfzscS8jbSCx85d0PM6_3A.png" /><figcaption>If the visualise button is clicked, the plot starts getting prepared at the backend</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJvSVIdDDU6SyN9cctsytg.png" /><figcaption>A figure showing each Hotel ID possible as a cluster centroid (black), and the 5 predicted hotel IDs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*0tpVi9hwItKwCeEYRHUciA.png" /><figcaption>A closer look at the predicted Hotel IDs marked with star (in order) and annotated in respective boxes</figcaption></figure><h3>8. Scope for improvements</h3><ul><li>As demonstrated by promising results in various research papers and blogs, the performance of the model can be improved further by trying out other <em>losses</em> like triplet loss, CosFace etc. or other types of <em>backbones</em> like VGGNet, DenseNet161 etc. Also, with sufficient hardware resources, we could try out with more <em>augmentations</em> and larger <em>batch</em> and <em>image sizes</em>.</li><li>For inference, instead of taking the current unsupervised approach using k-means clustering, we can try taking a more <em>deterministic</em> method. We can compute the mean vector from the train embeddings per class and treating them as centroids to find out distances of the test features. Hence, getting the top-n nearest points per hotel id based on identifying some threshold.</li></ul><h3>9. References</h3><ul><li><a href="https://arxiv.org/abs/1801.07698">https://www.arxiv.org/abs/1801.07698</a></li><li><a href="https://github.com/peteryuX/arcface-tf2">https://www.github.com/peteryuX/arcface-tf2</a></li><li><a href="https://www.tensorflow.org/guide/keras/custom_layers_and_models">https://tensorflow.org/guide/keras/custom_layers_and_models</a></li><li><a href="https://stackoverflow.com/questions/52039079/how-to-get-intermediate-output-when-using-tf-keras-application">https://www.stackoverflow.com/questions/52039079/how-to-get-intermediate-output-when-using-tf-keras-application</a></li><li><a href="https://stackoverflow.com/questions/42427179/keras-intermediate-layers-output">https://www.stackoverflow.com/questions/42427179/keras-intermediate-layers-output</a></li><li><a href="https://github.com/facebookresearch/faiss/wiki/Faiss-building-blocks:-clustering,-PCA,-quantization">https://www.github.com/facebookresearch/faiss/wiki/Faiss-building-blocks:-clustering,-PCA,-quantization</a></li><li><a href="https://nexocode.com/blog/posts/transfer-learning-in-practice/">https://nexocode.com/blog/posts/transfer-learning-in-practice/</a></li><li><a href="https://developer.nvidia.com/blog/understanding-aesthetics-deep-learning/">https://developer.nvidia.com/blog/understanding-aesthetics-deep-learning/</a></li><li><a href="https://www.researchgate.net/publication/322477802_Effects_of_user-provided_photos_on_hotel_review_helpfulness_An_analytical_approach_with_deep_leaning">https://www.researchgate.net/publication/322477802_Effects_of_user-provided_photos_on_hotel_review_helpfulness_An_analytical_approach_with_deep_leaning</a></li><li><a href="https://www2.seas.gwu.edu/~pless/papers/Hotels50k.pdf">https://www2.seas.gwu.edu/~pless/papers/Hotels50k.pdf</a></li><li><a href="https://medium.com/kayak-tech/hotel-image-categorization-with-deep-learning-ffa8429e55b5">https://medium.com/kayak-tech/hotel-image-categorization-with-deep-learning-ffa8429e55b5</a></li><li><a href="https://arxiv.org/pdf/2007.12749v2.pdf">https://arxiv.org/pdf/2007.12749v2.pdf</a></li><li><a href="https://www.tensorflow.org/lite/performance/post_training_quantization">https://www.tensorflow.org/lite/performance/post_training_quantization</a></li><li><a href="https://www.tensorflow.org/lite/guide/inference#load_and_run_a_model_in_python">https://www.tensorflow.org/lite/guide/inference#load_and_run_a_model_in_python</a></li><li><a href="http://www.appliedaicourse.com/">www.appliedaicourse.com</a></li></ul><p>All the python notebooks can be found at the <strong>GitHub </strong>link: <a href="https://github.com/prachij94/Hotel_id-recognition">https://github.com/prachij94/Hotel_id-recognition</a></p><p>Thanks for reading through till the end! Please share doubts, feedback, or anything that can help me better learn a thing or two, at my <strong>LinkedIn </strong>profile: <a href="https://in.linkedin.com/in/prachi-jain-bb3750102">https://in.linkedin.com/in/prachi-jain-bb3750102</a></p><h3>Don’t forget to give us your 👏 !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*2lvCls4yjxVMfZSR" /></figure><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=e5e67e66c060" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/combat-human-trafficking-by-similar-hotels-recognition-using-images-e5e67e66c060">Combat Human Trafficking by similar Hotels Recognition using images</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[Water availability prediction using historical data]]></title>
            <link>https://prachijain-cs12.medium.com/water-availability-prediction-using-historical-data-b9044bfddd76?source=rss-a9b6c476fde------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9044bfddd76</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[water]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Prachi Jain]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 01:37:26 GMT</pubDate>
            <atom:updated>2021-06-08T16:24:07.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*C2Uo7qO31IzS_2-LHA3Jrw.jpeg" /><figcaption>Here we try to preserve the <strong>“blue gold”</strong> using data to forecast water level throughout the year and better regulate the daily supply over different regions</figcaption></figure><h3>Table of Contents</h3><ol><li><a href="#2282">The problem</a></li><li><a href="#6306">The challenge that lies behind</a></li><li><a href="#4e00">Data Collection and description</a></li><li><a href="#b5aa">Expected Outcome</a></li><li><a href="#a063">Basic Workflow</a></li><li><a href="#8a53">Some similar approaches already explored</a></li><li><a href="#7505">Our roadmap to the solution</a></li></ol><ul><li><a href="#27ea">EDA</a></li><li><a href="#90e7">Metrics Used</a></li><li><a href="#014f">Data Preprocessing</a></li><li><a href="#940f">Feature Engineering</a></li><li><a href="#2cea">The Model</a></li></ul><p>8. <a href="#e034">Scope for improvements</a></p><p>9. <a href="#300b">References</a></p><h3>1. The problem</h3><p>The Acea Group is one of the largest Italian multiutility operators in the water services sector supplying 9 million inhabitants. It organized this competition on Kaggle to get help in predicting the water level in various types of water bodies over different seasons of the year. It is crucial for a water supply company to forecast the water level in a waterbody <em>(water spring, lake, river, or aquifer)</em> to handle daily consumption.</p><p>It can become tedious in scenarios like during fall and winter, water bodies are refilled, but during spring and summer, they start to drain. To help preserve the health of these water bodies it is important <strong>to predict the most efficient water availability, in terms of level and water flow for each day of the year.</strong></p><h3>2. The challenge that lies behind</h3><p>The Acea Group provides data for 4 types of water bodies, namely, water spring, lake, river, and aquifer. While the primary intention is the same i.e. to predict water availability, the reality is that <strong>each waterbody has such unique characteristics that their attributes are not linked to each other</strong>. This problem uses datasets that are completely independent of each other. As each waterbody is different from the other, the related features are also different.</p><p>To determine how the features influence the water availability of each waterbody poses a challenge. So we want to design a solution that helps better understand volumes so that we can ensure water availability for each time interval(day/month) of the year.</p><p>It is of the utmost importance to notice that some features like <strong>rainfall </strong>and <strong>temperature</strong>, which are present in each dataset, <strong>don’t go alongside the date</strong>. Indeed, both rainfall and temperature affect water level features. This means, for instance, that rain fell on 1st January doesn’t affect the mentioned features right the same day but some time later. As <strong>we don’t know how many days/weeks/months later rainfall affects these features</strong>, this is another aspect to keep into consideration when analyzing the dataset.</p><h3>3. Data Collection and description</h3><p>The data has been provided at <a href="https://www.kaggle.com/c/acea-water-prediction/data">https://www.kaggle.com/c/acea-water-prediction/data</a></p><p>There are <em>nine different datasets</em>, completely <strong>independent </strong>and not linked to each other. The Acea Group deals with four different types of waterbodies: water spring (<em>three </em>datasets), lake (<em>one </em>dataset), river (<em>one </em>dataset), and aquifers (<em>four </em>datasets). A brief description of each one: <a href="https://www.kaggle.com/c/acea-water-prediction/data">link</a>.</p><h3>4. Expected Outcome</h3><p>The table below shows the expected feature to forecast for each waterbody.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*vQ7km1kXtb13iAbD1uzbYw.png" /></figure><p>In conclusion, we want to generate <em>four </em>mathematical models, one for each category of water body (aquifers, water springs, river, lake) that might be applicable to every single waterbody.</p><h3>5. Basic Workflow</h3><p>The overview of the expected pipeline looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sP6SJ4ayRJ4DzFClxuSLFg.png" /><figcaption>Input, Data Processing, and output for the four water bodies</figcaption></figure><h3>6. Some similar approaches already explored</h3><p>There have been various research works and experiments performed in the area of predicting water levels in an area in one form or the other. Some of them are summarised below to give a brief overview of the scope:</p><ul><li><em>Short-term water level prediction using neural networks and neuro-fuzzy approach by Bunchingiv Bazartseren, Gerald Hildebrandt, K.-P. Holz (</em><a href="https://www.researchgate.net/publication/223259105_Short-term_water_level_prediction_using_neural_networks_and_neuro-fuzzy_approach"><em>Link</em></a><em>):</em> The paper demonstrates a short-term prediction of water level using ANNs and neuro-fuzzy systems as well as the linear statistical models, auto-regressive moving average (ARMA), and auto-regressive exogenous (ARX). The unstable outcome of the linear models at the beginning of the verification period, together with the late response for a longer prediction span caused lower performance attributes. The ANN models were chosen due to their superior prediction ability above the other models considered.</li><li><em>Development of Water Level Prediction Models Using Machine Learning in Wetlands: A Case Study of Upo Wetland in South Korea by Changhyun Choi, Jungwook Kim, Heechan Han, Daegun Han, and Hung Soo Kim (</em><a href="https://www.mdpi.com/2073-4441/12/1/93?type=check_update&amp;version=1"><em>Link</em></a><em>): </em>This paper uses various machine learning models such as ANNs, DTs, RFs, SVMs. Since it has many variables that are not linear in relationships, the correlation between the dependent and independent variables was examined using <strong>MI (Mutual information)</strong> rather than the commonly used Pearson correlation. The mutual information between two random variables X and Y have been defined in terms of their joint probability distribution p(x, y) as shown here:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*PyM6LZ79oPDGeGKRhYoDiw.png" /></figure><p>Based on the predictive performance evaluation results, the Random Forest was the most suitable for simulating the water level.</p><ul><li><em>Analysis and Prediction of Dammed Water Level in a Hydropower Reservoir Using Machine Learning and Persistence-Based Techniques by C. Castillo-Botón, D.Casillas-Pérez, C. Casanova-Mateo, L. M. Moreno-Saavedra, B. Morales-Díaz, J.Sanz-Justo, P. A. Gutiérrez, and S. Salcedo-Sanz</em> (<a href="https://www.mdpi.com/2073-4441/12/6/1528/htm"><em>Link</em></a>): This paper covers long and short term predictions for the dammed water level in a hydropower reservoir. A set of models, including different types of neural networks, Support Vector Regression(SVR), or Gaussian processes was tested. The original data were on a daily basis, thus a <strong>weekly aggregation</strong> was performed both for long and short-term analyses. <em>This improved the representation of the differences in the changes of the level of the water stored in the reservoir; otherwise, the differences in a smaller scale of time (daily or hourly) would be too small and unstable to properly train the model.</em> Depending on the type of variable, either an average or a sum was performed. The best overall result according to RMSE(Root Mean Square Error) was obtained with the configuration seasonal data, temporal partition, which uses four different ML models for each season. According to MAE(Mean Absolute Error), the best overall result was obtained with the configuration standard data, temporal partitioning using an SVR algorithm.</li></ul><h3>7. Our roadmap to the solution</h3><p>In order to design an effective solution, first, we deeply analyze the interrelationships in the datasets using Exploratory Data Analysis (EDA).</p><h4>EDA</h4><p>The following insights are derived when features from each dataset were checked as per their respective target feature (Refer to the EDA notebook in GitHub <a href="https://github.com/prachij94/Acea-smart-water-analytics">link</a>):</p><ul><li><em>There is a large proportion of </em><strong><em>missing values</em></strong><em> in most datasets of aquifers(~60% to 85%), lakes(~85%), rivers(~85%), springs(~55% to 75%) including major features like depth to groundwater, rainfall, temp, flow rate, etc.</em></li></ul><p>Check the following graphs of the percentage of <strong>missing values</strong> in each feature in each waterbody dataset-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*NswqlcRospOoonQrSUP3gw.png" /><figcaption>Aquifer Auser missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*_S0KqZO3j6-oWOwnZ1Cd2g.png" /><figcaption>Aquifer Doganella missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*ZmcozsnX63axs01i1cJYcg.png" /><figcaption>Aquifer Luco missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Fm8YFuMA-xHnLhePD7poig.png" /><figcaption>Aquifer Petrignano missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*tvraXIdspumcF6YZYKQumw.png" /><figcaption>Lake Bilancino missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*TXrxdw4ayUNfnnRkUW1Osg.png" /><figcaption>River Arno missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*bMW-46bvvCaZ-oUpHvGOrQ.png" /><figcaption>Water Spring Amiata missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*PeMhov34--amC6Ikk9ylaQ.png" /><figcaption>Water Spring Lupa missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*EVQ5lGK2vjcnRNSV3GawLg.png" /><figcaption>Water Spring Madonna Di Cannneto missing values</figcaption></figure><p>See an example heatmap to study <strong>correlation </strong>for each waterbody type below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIwPOHMV6yy72UffX2oiqA.png" /><figcaption>Aquifer Auser correlation (refer EDA pynb <a href="https://github.com/prachij94/Acea-smart-water-analytics">GitHub </a>for a clearer plot)</figcaption></figure><ul><li><em>Most aquifers have a strong positive correlation with rainfall and temperature features and a negative correlation with depth, hydrometry, and volume features.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*SmUY_rXs4wzeCGkEVaPBCA.png" /><figcaption>Lake Bilancino correlation</figcaption></figure><ul><li><em>Lake is positively correlated to rainfall.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NlmG1ugpmedAJUHBmwooQ.png" /><figcaption>River Arno correlation (refer EDA pynb <a href="https://github.com/prachij94/Acea-smart-water-analytics">GitHub </a>for a clearer plot)</figcaption></figure><ul><li><em>The river is positively correlated to rainfall and weakly negatively to temperature.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixoWWBy_KAfYldCDeAGFfw.png" /><figcaption>Water Spring Amiata correlation (refer EDA pynb <a href="https://github.com/prachij94/Acea-smart-water-analytics">GitHub </a>for a clearer plot)</figcaption></figure><ul><li><em>For water springs, rainfall, temperature are strongly positively correlated and weakly negatively correlated to depth to groundwater, and flow rate features.</em></li></ul><p>Look at the plot of <strong>univariate analysis</strong> for one feature in Aquifer Auser below. Refer to the EDA <a href="https://github.com/prachij94/Acea-smart-water-analytics">pynb </a>for all the other such plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*p2va55gz1OJQarM5c1KuXQ.png" /><figcaption>Aquifer Auser Rainfall feature univariate analysis</figcaption></figure><p><strong>Observations:</strong></p><ul><li><em>There are a considerable number of outliers in rainfall features from 100mm to 300mm and few in the hydrometry, volume features in Aquifers.</em></li><li><em>In Lake, there are lots of outliers in rainfall and flow rate features.</em></li><li><em>In River Arno, in the rainfall features, there are a considerable number of outliers till the range of up to 120 mm and a few in the Hydrometry feature.</em></li><li><em>Water springs have a considerable number of outliers in rainfall features to the range of up to 130 mm.</em></li></ul><p>Now let’s assess the <strong>yearly </strong>and <strong>monthly </strong>observations for a single water body for eg. Aquifer Auser (Refer <a href="https://github.com/prachij94/Acea-smart-water-analytics">GitHub </a>for all the other plots and their respective observations):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*DAFvkxSZ9uUdXPgMULNrwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*mRYg47P7jMsm2d9L0pEGAA.png" /></figure><ul><li><em>The mean depth to groundwater per year keeps on dipping &amp; drops to an average of -6 mm into 2020. This happens when mean rainfall and temp are 4 mm and 9 degrees respectively, which are moderate as compared to other years&#39; means. Also, the mean volume and mean hydrometry are -6500 cm and -0.2 m in 2020 which is very low.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*PsaS-m4nFo8RGlXSwWem2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*4NZWHR_KORyaiV0ADeJtng.png" /></figure><ul><li><em>The maximum average rainfall is recorded in the month of October or November on an average. The maximum temperature is found in July or August. The mean volume is also highest at -8700 cm and mean hydrometry at -0.10 m in July and August. This is around the same time the average depth to groundwater is found at a maximum of -6.7 m.</em></li></ul><h4>Metrics Used</h4><p>We have chosen our own metrics for this problem: <strong>Median Absolute Error (MAE), Root Mean Square Log Error(RMSLE), and R Squared (R²)</strong> because of the following reasons -</p><ul><li><em>MAE </em>is robust to outliers whereas RMSE is not. Using median is an extreme way of trimming extreme values. Hence median absolute error reduces the bias in favor of low forecasts. Also, MAE is really suited from an interpretation standpoint.</li><li><em>RMSLE </em>is used because the underestimation of the target variable is not acceptable but overestimation can be tolerated. The RMLSE incurs a larger penalty for the underestimation of the actual value. Also, we don’t want to penalize huge differences in the predicted and the actual values when both predicted and actual values are huge numbers. RMSLE metric (unlike RMSE) only considers the relative error between and the Predicted and the actual value and the scale of the error are not significant.</li><li>High <em>R²</em> means that the correlation between observed and predicted values is high. It tells how good our regression model is as compared to a very simple model that just predicts the mean value of target from the train set as predictions.</li></ul><h4>Data Preprocessing</h4><p>Now process the data in order to remove the anomalies found in EDA.</p><p>First, the major issue of missing values in all datasets is addressed. It is preprocessed in two steps:</p><ul><li>initially take only the rows where target features are not null. Impute the missing values in the independent features using <strong><em>knn imputation</em></strong> with the selected least error k value (this is done by plotting k values with our chosen metrics i.e. <em>MAE, RMSLE, and R2 score)</em></li><li>using the complete dataset (with filled features) to predict missing values in the respective target feature with Random Forest or other baseline models like Linear Regression, Decision Tree, or KNN.</li></ul><p>Check the below code snippet and plots for one waterbody:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7327d1e4f7675152c295637789fa878a/href">https://medium.com/media/7327d1e4f7675152c295637789fa878a/href</a></iframe><p>then we see different plots for comparing these models error metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*f4vw1UPUn0D176fiCJKKnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*qDcLukURwhGHI-jzoz8kbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*snxG0WyhQqiNIs1HpYFOUg.png" /></figure><p>then the best model and k value we get from all 3 metrics are used for predicting missing values in the target feature. in this example, it comes out to be k=15 with a Random forest regressor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8843197af268112ce8fa229f9c5058a4/href">https://medium.com/media/8843197af268112ce8fa229f9c5058a4/href</a></iframe><p>This way we can get all the 9 datasets with 100% filled values.</p><h4>Feature Engineering</h4><p>The primary goal is to have 4 models at the end, one for each waterbody. Also, we have to take into account the possible latency in the variables due to the effect of rainfall and temperature. Thus we integrate the datasets into their respective waterbody type by taking the <em>average </em>based on different time durations i.e. daily, weekly, monthly, and yearly.</p><p>Then we find out the <em>Median Absolute error trends</em> in each of these durations models when the variables are <em>shifted </em>by days, weeks, or months. Hence, the final data for each water body will have the actual values of the target variables as affected by rainfall and temperature.</p><p>For eg. in Aquifers, we first take the mean of all rainfall, temperature, volume, hydrometry, and depth features in each aquifer dataset, then combine them and again take daily mean, weekly mean or monthly mean based on the Date column. This gives us datasets aquifer_daily, aquifer_weekly, and aquifer_monthly.</p><p>In each of these new datasets, we shift each feature value by 1 to 31 days, 1 to 52 weeks, and 1 to 12 months. Then using a Random Forest Regressor, note the time duration after which the MAE is lowest to predict that shifted feature (i.e. the rainfall and temp effect is most appropriate).</p><p>A sample code snippet for shifting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8535d8af863b15c97e40637d93ca3dd/href">https://medium.com/media/b8535d8af863b15c97e40637d93ca3dd/href</a></iframe><p>Observing best results at 26 days (aquifer_daily), 8 weeks(aquifer_weekly), and 2 months(aquifer_monthly), we made the final aquifers dataset by shifting the values by 56 days (8 weeks or 2 months) backward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/901ba6261a14e0862d69803b0a8e14e9/href">https://medium.com/media/901ba6261a14e0862d69803b0a8e14e9/href</a></iframe><p>Likewise, do the analysis for all water bodies and ultimately get 4 feature engineered datasets having the true effect of rainfall and temperature.</p><h4>The Model</h4><p>The datasets are first <em>normalized </em>to remove the negative values. Then several types of models are tried to get the least error metrics/best predictions. knn, Linear Regression, Random Forest, SGRegression, Decision Trees, XGBoost, Adaboost were tried along with rigorous hyperparameter tuning in GridSearchCV. But the best results were observed when <strong>Multi-Layer Perceptron</strong> was used. It was achieved with the best-found combination of the number of layers to use, dropouts, optimizer, custom loss function &amp; metrics(here RMSLE), batch_size, epochs, etc for each individual water body.</p><p>The <em>train and validation graphs</em> for each of the four water bodies can also be found in the Model pynb in <a href="https://github.com/prachij94/Acea-smart-water-analytics">GitHub</a>. Here are a few snapshots of them:</p><p><strong>Aquifer model </strong>(Find its complete tensorboard <a href="https://tensorboard.dev/experiment/aqbHZ4VmQDWurZKn2bTVCQ/">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*2Cp2VoI7XsUGnibuIVR2Hw.png" /><figcaption>color coding for the graphs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*XzTlQkr-F1yp0eFNghupMg.png" /><figcaption>Aquifer model loss per epoch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*sXZVwTGqY0Y-DQxxHzms7w.png" /><figcaption>Aquifer model rmse per epoch</figcaption></figure><p><strong>Lake model </strong>(Find its complete tensorboard <a href="https://tensorboard.dev/experiment/DxtD800iQte9H9Xo1D4Low/">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*0iBXI6_2bZiqThRG3gMRpQ.png" /><figcaption>Lakes model loss per epoch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*SlO1zTN7WiGFrAdxqKJQcw.png" /><figcaption>Lakes model rmse per epoch</figcaption></figure><p><strong>River model </strong>(Find its complete tensorboard <a href="https://tensorboard.dev/experiment/3OUj6QneTKqzIOcGsJbPsA/">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*5wDm9vTmtLiUZgkjydO8eA.png" /><figcaption>Rivers model loss per epoch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*v5jnwM6yE4W_PIXCrRli7w.png" /><figcaption>Rivers model rmse per epoch</figcaption></figure><p><strong>Water Springs model</strong> (Find its complete tensorboard <a href="https://tensorboard.dev/experiment/r8Y3lQUpQhawazoCgDxGpA/">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*BP-2WTFD8ff8CxQ-JrC8Eg.png" /><figcaption>Water Springs model loss per epoch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*BLVJFm0ruwuElUFxpB6VIw.png" /><figcaption>Water Springs model rmse per epoch</figcaption></figure><p>While most algorithms performed well to predict for Aquifers, the MLP was able to capture the least predictions for each waterbody type. Below is a comparative summary of the R2 score for different models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*ffOfjJazuKLHOHFax1g7yA.png" /></figure><p>So while training, the best MLP models’ logs and weights were saved for faster model access in the future.</p><p>The saved weights are used to load the respective model in the flask app for the problem. It has been deployed on <a href="https://www.heroku.com/">Heroku</a>. The app can be accessed at <a href="https://acea-flask-api.herokuapp.com/index">https://acea-flask-api.herokuapp.com/index</a>. See a snapshot for it below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozqxFzdiGX1pRxsXB2B_1g.png" /><figcaption>The web application to access the predictions</figcaption></figure><h3>8. Scope for improvements</h3><p>Various types of Machine Learning algorithms and MLP have been explored for solving the problem. So now it would be appropriate to say that exploring more neural networks like CNNs or LSTMs can yield good results. Also, linear statistical models like auto-regressive moving average (ARMA), and auto-regressive exogenous (ARX) can also be tested to capture the seasonal trend in the datasets.</p><h3>9. References</h3><ul><li><a href="https://www.researchgate.net/publication/223259105_Short-term_water_level_prediction_using_neural_networks_and_neuro-fuzzy_approach">https://www.researchgate.net/publication/223259105_Short-term_water_level_prediction_using_neural_networks_and_neuro-fuzzy_approach</a></li><li><a href="https://www.mdpi.com/2073-4441/12/1/93?type=check_update&amp;version=1">https://www.mdpi.com/2073-4441/12/1/93?type=check_update&amp;version=1</a></li><li><a href="https://www.mdpi.com/2073-4441/12/6/1528/htm">https://www.mdpi.com/2073-4441/12/6/1528/htm</a></li><li><a href="https://www.researchgate.net/publication/328086006_Short-term_water_demand_forecasting_using_machine_learning_techniques">https://www.researchgate.net/publication/328086006_Short-term_water_demand_forecasting_using_machine_learning_techniques</a></li><li><a href="https://skemman.is/bitstream/1946/32366/1/HallaMarinos.pdf">https://skemman.is/bitstream/1946/32366/1/HallaMarinos.pdf</a></li><li><a href="https://machinelearningmastery.com/knn-imputation-for-missing-values-in-machine-learning/">https://machinelearningmastery.com/knn-imputation-for-missing-values-in-machine-learning/</a></li><li><a href="https://www.techiediaries.com/flask-tutorial-templates/">https://www.techiediaries.com/flask-tutorial-templates/</a></li><li><a href="https://www.geeksforgeeks.org/python-pandas-dataframe-ffill/">https://www.geeksforgeeks.org/python-pandas-dataframe-ffill/</a></li><li><a href="https://keras.io/api/losses/#creating-custom-losses">https://keras.io/api/losses/#creating-custom-losses</a></li><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a></li></ul><p>All the pynb’s for the problem can be found at the <strong>GitHub </strong>link: <a href="https://github.com/prachij94/Acea-smart-water-analytics">https://github.com/prachij94/Acea-smart-water-analytics</a></p><p>Thanks for reading through till the end! Please share doubts, feedback, or anything that can help me better learn a thing or two, at my <strong>LinkedIn </strong>profile: <a href="https://in.linkedin.com/in/prachi-jain-bb3750102">https://in.linkedin.com/in/prachi-jain-bb3750102</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9044bfddd76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification for E-commerce [Part I]]]></title>
            <link>https://medium.com/data-science/product-image-classification-with-deep-learning-part-i-5bc4e8dccf41?source=rss-a9b6c476fde------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bc4e8dccf41</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prachi Jain]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 12:20:21 GMT</pubDate>
            <atom:updated>2019-02-13T15:12:19.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Classification for E-Commerce — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*9mdFRvqCYIxWSuDF.jpg" /><figcaption>This eye-catching image becomes all the more enchanting when you get to know that our brain processes visuals <strong>60,000</strong> times faster than text and retains <strong>80</strong> percent of what we see versus just <strong>20</strong> percent of what we read.</figcaption></figure><h3>When Images become Storytellers</h3><p>Images have often assumed the role of telling stories and expressing powerful ideas with just a few strokes of the brush as they say ‘<em>a picture speaks louder than a thousand words’. </em>An image’s ability to narrate ideas has attracted humans and with half of the human brain devoted directly or indirectly to vision, visuals become our primary sense for understanding the world around us.</p><p>In this article, I will explain how we used images to solve one of the most popular business problems i.e. classification of products.</p><h3><strong>The Holy Grail</strong></h3><p>A giant online marketplace like <a href="https://dir.indiamart.com/">Indiamart</a> has thousands of macro categories for listing various products. A product must get mapped under the most appropriate micro category on the platform.<em>[ For more clarity on the definition of the </em><strong><em>macro category</em></strong><em> and </em><strong><em>micro category</em></strong><em> please refer to this commendable </em><a href="https://medium.com/@mukeshkumar_561/product-classification-using-machine-learning-part-i-5a1cd0c2caf2"><em>post</em></a><em>’s section: ‘My Problem, My Way’]</em></p><p><strong>The goal of this post is to build intuition and understanding of how neural networks can be trained to identify the micro category of a product using its images.</strong></p><blockquote>For instance, In a macro category <em>‘Leather Safety Gloves’ , </em>there can be various<em> </em>micro categories like <em>Industrial Leather Gloves, Leather Welding Gloves, Chrome Leather Gloves, etc.</em> We intend on classifying our products such that an <em>Industrial</em> <em>Leather</em> <em>Safety Glove </em>image<em> </em>is always classified into the <em>Industrial</em> <em>Leather</em> <em>Safety Glove </em>micro category<em>. </em>Likewise, an image of a <em>Work Boot</em> always predicts a micro category <em>Safety Work Boot</em> where its macro category is ‘<em>Safety Boots</em>’.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*IZCv0J0NREgJ6af7oDZv7w.png" /><figcaption>For an Industrial Leather Glove product, ‘Leather Safety Gloves’<em> is a </em><strong><em>macrocategory</em></strong><em> for which the </em><strong><em>microcategory </em></strong><em>is ‘Industrial Leather Gloves’</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*2ktOqQwirCu3AtNLUWYuLQ.png" /><figcaption>For a Work Boot product, ‘Safety Boots’ <em>is the </em><strong><em>macro category</em></strong><em> and the micro category</em><strong><em> </em></strong><em>here</em><strong><em> </em></strong><em>is ‘Safety Work Boot’</em></figcaption></figure><p>Let us now have a look at the concepts used behind image classification. If you want to jump straight to the implementation, feel free to skip ‘<strong><em>What’s under the hood?-The technology basics’ </em></strong>portion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vDld7zpfWszhq9lE6oMQtg.gif" /><figcaption>Predicting the number written inside the image would have become comically trivial to dauntingly difficult for a machine using only its pixel information, without the concept of Machine Learning and Neural Network!</figcaption></figure><h3>What’s under the hood?-The technology basics</h3><p>We are going to use <em>Convolutional Neural Networks(CNN) </em>for classifying the products’ images using <a href="https://en.wikipedia.org/wiki/Supervised_learning">Supervised Learning</a> and run it on <em>PyTorch(</em>which is an Artificial Intelligence framework developed by Facebook). For this purpose, we take up Facebook’s <strong>ResNet</strong> model which is pre-trained on more than a million images from the <a href="http://www.image-net.org/about-overview">ImageNet database</a>.</p><h4>What is the Pre-trained Model?</h4><p>A pre-trained model has been previously trained on a data set and contains the weights that represent the <strong>features </strong>of whichever data set it was trained on. Learned features are often transferable to different data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*jNx-vvaQtqU9bIKMQsv6Zg.jpeg" /></figure><h4>What is Deep Learning?</h4><p>Deep Learning is a subset of machine learning which generally has more than one hidden layer. The prime thing about Deep Learning is that it can achieve very good results where there is an abundance of (typically labeled) data.</p><blockquote>In mathematics, convolution is a mathematical operation on two functions to produce a third function that expresses how the shape of one is modified by the other.</blockquote><p><strong>Convolutional neural networks</strong> <strong>(CNN</strong>) are computing systems inspired by the <a href="https://en.wikipedia.org/wiki/Biological_neural_network">biological neural networks</a> that constitute animal brains. Such systems <strong><em>learn</em></strong><em> (progressively improve their ability)</em> to do tasks by considering examples, generally without task-specific programming. For example, they might learn to identify images that contain cats analyzing example images that have been manually labeled as “cat” or “no cat” and using the analytic results to identify cats in other images. <strong>Labelling</strong> typically takes a set of unlabelled data and augments each piece of that unlabelled data with meaningful tags that are informative.</p><p><em>Residual Learning tries to solve the problems of both the complexity in training of deeper neural networks as well as their saturating accuracy with depth</em>.</p><p><strong>What is Residual Learning?</strong></p><p>In general CNN, several layers are stacked and are trained to the task at hand. The network learns several low/mid/high-level features at the end of its layers. In residual learning, instead of trying to learn some features, we try to learn some residual.</p><blockquote><em>Residual can be simply understood as the subtraction of the feature learned minus the input of that layer</em>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*JCy4o3c6vs9jgAF35V0LOQ.png" /><figcaption>Residual Learning: A building block</figcaption></figure><p>ResNet does this by directly connecting the input of the nth layer to some (n+x)th layer. It uses <strong>ReLU</strong> (ReLU stands for the <strong>rectified linear unit</strong>, and is a type of activation function).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Jg0CamAWkgBJSKk2o8rGPw.gif" /><figcaption>A ‘Rectified’ Linear Unit substitutes everything dissimilar (negative value) with zero. So by the end, we are left with only a similar looking image.</figcaption></figure><p>If you are unsure what activation function to use in your network, ReLU is usually a good first choice. Why? Please read <a href="https://www.tinymind.com/learn/terms/relu">this</a> for more on ReLU.</p><p>ResNet34 is a 34 layer deep Residual Network. Other variants like ResNet50,ResNet101 and ResNet152 are also available.</p><h3>System Requirements</h3><p>Download or clone the ResNet model from Facebook’s <a href="https://github.com/facebook/fb.resnet.torch">Github</a> link.</p><p>Install the Torch ResNet dependencies on <a href="http://www.ubuntu.com/">Ubuntu 14.04+</a>:</p><ul><li>Install <a href="http://torch.ch/docs/getting-started.html">Torch</a> on a machine with <strong>CUDA GPU</strong> (NVIDIA GPU with compute <strong>capability 3.5 or above</strong>)</li><li>Install <a href="https://developer.nvidia.com/cudnn">cuDNN v4 or v5</a> and the Torch <a href="https://github.com/soumith/cudnn.torch/tree/R4">cuDNN bindings</a></li></ul><p>See the <a href="https://github.com/facebook/fb.resnet.torch/blob/master/INSTALL.md">installation instructions</a> for a step-by-step guide.</p><h3>Let’s get started!</h3><p><strong>Prerequisites:</strong> A basic understanding of Python &amp; Linux commands is assumed for moving further.</p><h4><strong><em>HOW WE EMPLOYED RESNET FOR CUSTOM DATA SET?</em></strong></h4><h4><strong>Data Collection-</strong></h4><p>Knowing Your Data first step can take you unprecedented heights in achieving the desired accuracy of predicted results. We identified the attributes required for our custom labels to use with the trained model and fetched the <strong>Micro Category ID</strong>, <strong>Product ID, </strong>and the <strong>Product Images’ URL </strong>into a tsv (tab separated values) format.</p><p>We downloaded the images from the urls into a folder structure organized as-</p><p>The label names are kept as individual folder names and each of them has their related images. This entire structure is enveloped into another folder which should be named ‘<strong>train</strong>’. Similarly, another folder with the name ‘<strong>val</strong>’ having the validation set for testing (i.e. label names folders having product images) should be kept at the same location as ‘train’.<em>[ This folder organization standard is given by Facebook and is required for its model to work]</em></p><p>In our scenario, the structure should look something like:</p><pre>train/&lt;Micro_category_ID1&gt;/&lt;Product_ID1.jpg&gt;<br>train/&lt;Micro_category_ID2&gt;/&lt;Product_ID1.jpg&gt;<br>val/&lt;Micro_category_ID1&gt;/&lt;Product_ID1.jpg&gt;<br>val/&lt;Micro_category_ID2&gt;/&lt;Product_ID1.jpg&gt;</pre><p>To achieve this, we used the following Linux command which should be fired in the Terminal at the path ‘train’:</p><pre>while read -r mcat_id product_id url; do if [ ! -d &quot;${mcat_id}&quot; ]; then mkdir -p ${mcat_id}; fi; cd $mcat_id; wget -O $product_id $url; cd ..; done &lt; tsvfilename</pre><p>This command reads the micro category id, product id and image URL from the tsv file and iteratively, in the corresponding micro category folder path, downloads an image from the URL renaming it as the Product ID (for easy identification afterward).</p><p><strong>Voilà! </strong>We have our training data ready. Wait…what? No, it’s still not there!</p><p>One of the most crucial procedures to be performed for getting the sought-after results follows.</p><h4>Data Cleaning-</h4><p>We want to prepare a homogeneous input data set to avoid chances of the model getting biased towards certain micro category ID’s images at the training time and hence, always predicting those micro-categories.</p><p>We devised a shell script which converts all the images to .jpeg (both in name and format, excluding .png, .gif, etc.),removes erroneous files downloaded, deletes duplicate files and reduces down all the images’ dimensions to 224 X 224 px (if the width or height is greater than 224 px).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dd4e512b536e6f2888c34ebae14cbc6/href">https://medium.com/media/6dd4e512b536e6f2888c34ebae14cbc6/href</a></iframe><p>We chose the image dimension size 224 X 224 px because the <em>top1</em> and <em>top5 </em>errors are observed to be lesser for this setting. For more details check <a href="https://datascience.stackexchange.com/questions/16601/reason-for-square-images-for-deep-learning">this </a>out.</p><blockquote>In <strong>top1</strong> score, you check if the top class predicted (the one having the highest probability) is the same as the target label.</blockquote><blockquote>In the case of <strong>top5</strong> score, you check if the target label is one of your top 5 predictions (the 5 ones with the highest probabilities).</blockquote><h4>Label Loading-</h4><p>As the name suggests, it’s a process for manipulating the data load on our labels in such a manner that each of the labels’ images count reaches a comparable level.</p><p>In order to feed the model with the data covering various kinds of product images received from users every day, we performed <strong>image augmentations</strong> on the existing data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*DZtrIJMlZJux94PGEeLa5w.png" /><figcaption>Here, the input image has been augmented in various forms (by introducing noise and inclination) to increase scarcely available training data set.</figcaption></figure><p>The following python script was used to mirror each image, rotating them clockwise, anti-clockwise, also a grainy image for each was created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/180d33c93bd2c3230c1ee40226081a8b/href">https://medium.com/media/180d33c93bd2c3230c1ee40226081a8b/href</a></iframe><p>We also have to ensure that some Micro Category IDs do not end up with more weight than others and bias the model thus, predicting incorrect results. This may be the case where some micro category has more listed products (with images) than the other.</p><blockquote>For instance, In Macro Category ‘Inflatable Furniture’ , the Micro Category ‘Inflatable Sofa’ has more number of products with images than Micro category ‘Inflatable Couch’.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nXO27dZrcPWKGSmJVy9rw.png" /></figure><p>We used a Python script which multiplies images in the folder <strong>train</strong>’s Micro category ID folders. Currently, we have taken the multiplication factor as 98 percentile (i.e. that one image count out of all individual folder’s image counts where 98% images of the total count are covered).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a4c4ad0ed655d3c49a4c2a0c9587977/href">https://medium.com/media/6a4c4ad0ed655d3c49a4c2a0c9587977/href</a></iframe><p>Good to go for the training finally!</p><h3>Training the model-</h3><p>Use the <strong><em>main.lua </em></strong>file under the folder downloaded from Github i.e. fb.resnet.torch to train the model’s layers with our own data set.</p><pre>th ~/fb.resnet.torch/main.lua -nClasses 122 -nEpochs 100 -data ~/imageclassification/train/ -save ~/Desktop/imageclassification_c122e100b30t4g1 -batchSize 30 -nThreads 4 -nGPU 1</pre><ul><li><strong>-nClasses </strong>is our number of labels (i.e. micro Category IDs)</li><li><strong>-data</strong> is the path of the train folder</li><li><strong>-save</strong> is the folder path where all models (i.e. .t7 files) will be saved (A model is generated at the end of each epoch in this new folder specified i.e. ~/Desktop/imageclassification_c122e100b10t4g1, where each model is trained above its preceding model’s data.)</li><li><strong>-batchSize</strong> is the number of images taken to train in each epoch</li><li>-<strong>nEpochs</strong> is the number of iterations we want our model to run for (We also get the top1 and top5 error at the end of each epoch which is used for the analysis of the best model)</li><li><strong>-nThreads</strong> is the number of threads used of the GPU</li><li>-<strong>nGPU</strong> is the numbers of GPU we are going to use for the training</li></ul><p>Another parameter is <strong>-depth</strong> (not used here) and hence, by default, <em>we have a ResNet-34 model</em>. Had it been 50, we would have a ResNet-50 model.</p><p>Various other parameters can be used at the time of training as per your convenience and resource availability. They can be explored by:</p><pre>th main.lua --help</pre><p><strong>OKAY! Let’s fire the command!</strong></p><p><strong>DONE!</strong></p><p>Depending upon your training data set size and system speed, you should be <strong>patient</strong> and provide your student with <strong>ample</strong> <strong>time</strong> to learn well :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*awgfGEeoSVOZUP3-fOffMw.gif" /><figcaption>Training…Training……Training!!!</figcaption></figure><p><strong>main.lua</strong> automatically generates two extra models in parallel i.e. <strong>model_best.t7</strong> and <strong>latest.t7 </strong>in the -save folder.</p><blockquote>model_best.t7 is the replica of the model which was created on an epoch which had the least top1 and top5 errors.</blockquote><blockquote>latest.t7 is the fully trained model i.e. the model created by the last epoch.</blockquote><p>These two models are not always the same. In our case, the best model was observed to be generated at the epoch 99 but the latest model was that from epoch 100. So, <strong>we used the model_best.t7 for testing.</strong></p><h3>Testing the model-</h3><p>The <strong>classify.lua</strong> (in the folder fb.resnet.torch/pretrained/) is used to get the top 5 predictions from model_best.t7 for all our test images.</p><p>An important thing to note here is that the <em>classify.lua derives the prediction labels from the imagenet.lua</em>(in the same folder i.e. ‘pretrained’).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7ZmGIMNVY5EiysOPHIw-A.png" /></figure><p>So, we substitute the old labels in imagenet.lua (names of birds, animals, etc. from the ImageNet database) with our own label values i.e. Micro category IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyyiRNlt8gbHOQH3GoijCw.png" /><figcaption>The left image shows the original labels in the <strong>imagenet.lua</strong> file. The micro category ID’s which are used as our labels are being substituted in the same file as shown in the right picture.</figcaption></figure><p>Now, let us test our best model!</p><p>We picked some labels from the ‘train’ and copied them in the ‘val’ for testing the accuracy of our trained model on the same data it was trained on.</p><p>The testing command below outputs the top 5 predicted results for each image in ‘val’ along with their predicted probabilities:</p><pre>for f in ~/imageclassification/val/* ;do ( [ -d $f ] &amp;&amp; cd &quot;$f&quot; &amp;&amp; echo Entering into $f &amp;&amp; th ~/fb.resnet.torch/pretrained/classify_new.lua ~/Desktop/imageclassification_c122e100b30t4g1/model_best.t7 $f/*  &gt;&gt; ~/Desktop/imageclassification_c122e100b30t4g1.txt); done</pre><h3>The Aftermath</h3><p>This text file created was analyzed by converting it into an excel file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJWZi9DzZsU3YomsKOh-2Q.png" /><figcaption>The testing file created by running <strong>classify.lua</strong></figcaption></figure><p>The excel file has the above predictions separated as columns (using an R script) for <strong>Original Micro Category ID</strong> and <strong>Product ID</strong> (from the images’ local path) and also the <strong>Predicted Micro Category 1, Predicted Micro Category 1’s probability</strong>.</p><p>By putting a match check on the predicted and original Micro Category, we observed the predictions to be true in <strong>99.28%</strong> of the cases. <em>These are those cases on which the model was trained.</em></p><p>Later, we repeated the testing activity for 70 <strong>new products</strong> added(thus, the trained model had not learned them earlier).</p><p>In this case, <em>above a threshold of 50% model confidence(probability) which covered 80% of the data, </em>we observed the accuracy as <strong>95.38%.</strong></p><p>The Precision is observed as <strong>1.00</strong> and Sensitivity/Recall as <strong>0.95</strong> for the model. The confusion matrix for this result is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*DcqbClAF15lkaQXhVvLwzA.png" /><figcaption>The matrix shows results for 65/70 cases excluding 5 cases where the user uploaded product image was not clear or was irrelevant for this macro category.</figcaption></figure><h3><strong>What follows ahead…</strong></h3><ul><li>We are working on analyzing the prediction accuracy at <em>Macro Category </em>level as well.</li><li>We intend to employ feature extraction to find similar images among different Micro Categories. A useful script for this purpose i.e. <em>exract-features.lua</em> is provided in the fb.resnet.torch/pretained folder.</li><li>We wish to leverage Image classification in identifying <em>banned</em> content on the platform.</li></ul><p>Further posts in this series will follow soon to highlight the implementation of the above goals.</p><p>I hope this piece helped you expand your knowledge about using Resnet for custom business cases, If you have any questions or comments I would love to hear from you. You can reach me at <em>jain.prachi@indiamart.com</em></p><p><em>Thanks to </em><a href="https://medium.com/u/47a096395dd5"><em>Vikram Varshney</em></a><em>, </em><a href="https://medium.com/u/f3499cb43377"><em>Ayush Gupta</em></a><em>, </em><a href="https://medium.com/u/17b024118255"><em>Ashutosh Singh</em></a><em>, </em><a href="https://medium.com/u/1b7897ab0b1c"><em>Mukesh Kumar</em></a><em> for the extended support.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bc4e8dccf41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/product-image-classification-with-deep-learning-part-i-5bc4e8dccf41">Image Classification for E-commerce [Part I]</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>