<?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 Ashutosh Singh on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Singh on Medium]]></description>
        <link>https://medium.com/@ashutoshsingh93?source=rss-17b024118255------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fMwPPxLE_y_dwBjApqcD4g.jpeg</url>
            <title>Stories by Ashutosh Singh on Medium</title>
            <link>https://medium.com/@ashutoshsingh93?source=rss-17b024118255------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:47:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutoshsingh93/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[Recommendation System for E-Commerce using Collaborative Filtering]]></title>
            <link>https://medium.com/@ashutoshsingh93/recommendation-system-for-e-commerce-using-collaborative-filtering-fa04d6ab1fd8?source=rss-17b024118255------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa04d6ab1fd8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[indiamart]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 22 Jul 2019 12:58:02 GMT</pubDate>
            <atom:updated>2019-07-30T06:36:21.726Z</atom:updated>
            <content:encoded><![CDATA[<h4>Recommendation of product categories to sellers based on their existing behavior.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cysLD_zxKamlS2re-l-dUg.png" /><figcaption>Recommender System</figcaption></figure><p>As online businesses and e-commerce are growing in popularity, a considerable challenge is helping customers through the recommendation of a wide variety of product categories to efficiently find the one they will like the most. One of the technique to handle the above challenge is a recommendation system. The most common task of a recommendation system is to improve customer experience through the most relevant recommendation of items/products based on their previous behavior such as their buy lead purchase pattern and product mapping history. In this article, we will focus on the theoretical approach, some mathematics, the implementation of the above approach using Python as well as saving the model and loading the same to use for deployment.</p><p>Before moving forward let’s understand what a <strong>Buy Lead</strong> and <strong>Product Categories</strong> in the context of <a href="https://www.indiamart.com/">Indiamart</a>. A Buy Lead is basically a buyers requirement posted on our platform, whereas a Product is added in sellers catalog. Both products and Buy leads mapped to certain product categories also known as MCATs(micro categories). At Indiamart there are more than 110k MCATs and more than 140k paid subscribers. For detail understanding of products in the context of Indiamart please refer to this <a href="https://towardsdatascience.com/classifying-products-as-banned-or-approved-using-text-mining-5b48d2eb1544">article</a>.</p><h3>About Collaborative Filtering and ALS:</h3><p><a href="https://en.wikipedia.org/wiki/Collaborative_filtering">Collaborative Filtering</a> is a process of making a recommendation or predictions about the interest of a user based on preferences and taste of many other users. The predictions made using the collaborative technique are specific to a user but use information obtained from many different users.</p><p>ALS (Alternating Least Squares) is an implicit recommendation algorithm to make a recommendation of products and product categories to the users. ALS is an iterative optimization process where for every iteration it tries to arrive closer and closer to a factorized representation of the original data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcfEmEntXaoH2ffRKBKfvw.png" /><figcaption><strong>R(nxm) = U(nxp) xV(pxm)</strong></figcaption></figure><p>By randomly assigning the values in User matrix(<strong>U</strong>) which is a <em>(n x p)</em> matrix and Item matrix(<strong>V</strong>) which is a <em>(p x m) </em>matrix, and then by using <em>least-squares </em>iteratively we can arrive with the weights that yield the best approximation of <strong><em>R </em></strong>which will be a <em>(n x m)</em> matrix. The <em>least-squares </em>approach in its basic forms means fitting some line to the data, measuring the sum of squared distances from all points to the line and trying to get an optimal fit by minimizing this value.</p><p>With the alternating least squares approach, we use a similar technique but iteratively alternate between optimizing U(User matrix) and fixing V(Item matrix) and vice versa. We do this for each iteration to arrive closer to <strong>R = U x V, </strong>Where R is Rating Matrix, U is User Matrix and V is Item Matrix. In our use case, an item is a product category(MCATs). The complete approach is based on the research of <em>Yifan Hu, Yehuda Koren, Chris Volinsky</em> in their <a href="http://yifanhu.net/PUB/cf.pdf">paper</a>.</p><p>The computational bottleneck in this method is calculating User matrix(U) and item matrix(V). Firstly we used a simple mathematical approach which takes a long time but later on, we have used an implicit technique in cython to handle the computational issues. In ALS we iteratively compute user vectors <em>(U_i)</em> and item vectors <em>(Y_i) </em>using the below formula:</p><p><strong>X_u = ((Y.T*Y + Y.T*(Cu — I) * Y) + λ*I)^-1 * (X.T * Cu * p(u))<br> Y_m = ((X.T*X + X.T*(Cm — I) * X) + λ*I)^-1 * (Y.T * Cm * p(m))</strong></p><p><strong>Where:</strong></p><ol><li><strong>X and Y: </strong>X is the user matrics and Y is the item matrix. In ALS these matrices will be updated alternatingly.</li><li><strong>Cu and Cm: </strong>Confidence values for users and mcats.</li><li><strong>Lambda</strong>(<strong>λ):</strong> Regularizer value. Generally used to reduce overfitting in a machine learning model(we’re using 0.1).</li><li><strong>p(u) and p(m): </strong>The preference for an item(binary). If known then preference is 1 and zero if not known.</li><li><strong>I (Identity /np.eye): </strong>The identity matrix. Square matrix with ones at the diagonal elements and zeros everywhere else</li></ol><h3>Making recommendation:</h3><ol><li>To calculate the recommendation score we have calculated the dot products between User vector<em>(Ui)</em> and the transpose of Item Vectors<em>(VT)</em>. i;e <strong>Recommendation score = Ui.VT. </strong>A higher value of the dot product means more confidence in the prediction of an item for a particular user.</li><li>After calculating the above score we sorted the score in descending order to get the most suitable top 10 recommendations for each user.</li><li>We can also use this approach to calculate similarity among mcats/items by taking the dot product of the item vector(Vi) and its transpose(ViT). <strong>Similarity Score = V.ViT. </strong>This score can be used to get item-item similarity based on cosine distance between one item vector and another. A higher value of cosθ between the two items indicates more similarity among them.</li></ol><h3>Implementation Steps:</h3><p><strong>Data Preparation and Cleaning: </strong>The<strong> </strong>first step in every machine learning project is data preparation which includes (extraction of data, cleaning(<em>removing unnecessary data and handling missing values</em>). We have prepared data for User_ID<em>(Seller in our case)</em>, MCATs(product categories) where their product have been mapped and count of BLs they are purchasing from mcats(<em>included those mcats whose products were not available in sellers catalog but they are purchasing leads in that</em>). The sample dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*B7qrKi-GUHtkUyXurQ33IA.png" /><figcaption>The sample data format for model training*</figcaption></figure><blockquote>*The above data is just a randomly generated sample which does not contain any original information of data. The number of lead purchased can range from 0 to n implicitly.</blockquote><p><strong>Creation of Sparse matrix(User x Item/MCAT): </strong>After preparation of the above data we have created a sparse matrix <strong>(R)</strong>which is a combination of User and MCAT data. This is a large matrix which covers entire user and MCAT features. Python code for data processing and creation of Sparse matrix</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae26abcd4d92b7942472b95762fac959/href">https://medium.com/media/ae26abcd4d92b7942472b95762fac959/href</a></iframe><p><strong>Calculation of User vectors and MCAT vectors: </strong>User vectors and MCAT vectors have been calculated using the same formula that we discussed earlier, we have used the same formula in python<em>(spsolve in scipy linear algebra package)</em> to calculate these feature vectors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dd6b3239b02788d986fcc623ee07044/href">https://medium.com/media/0dd6b3239b02788d986fcc623ee07044/href</a></iframe><p><strong>Recommendation of mcats to users: </strong>Once we have created our users and MCAT(product categories) vectors we are ready to recommend mcats against a user by taking dot products of user vectors and the transpose of item vector and sorting them in descending order of the recommendation score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e48da88e593e877acf8748adec8386c2/href">https://medium.com/media/e48da88e593e877acf8748adec8386c2/href</a></iframe><p><strong>Speeding the process and reducing computational time: </strong>As these steps are taking a long time while creating a very high dimensional matrix and training model file. We have used the Cython implementation of the same approach created by <a href="http://www.benfrederickson.com/">Ben Frederickson</a>. The detailed library of this implementation is available <a href="https://github.com/benfred/implicit">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/811c16dcdc99fdcaf2b07e90d3f9c498/href">https://medium.com/media/811c16dcdc99fdcaf2b07e90d3f9c498/href</a></iframe><p><strong>Saving the model file: </strong>Once we have created the model using the approach we need the save the model so that there is no need to train again at the time of testing or deployment. There multiple ways like<em> joblib from sklearn.external , pickle, etc.</em> to do similar tasks. We have used pickle dump to save the model file and pickle load to further load the trained model in any system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e7617beb13ec70f5e40e54c52862d4/href">https://medium.com/media/15e7617beb13ec70f5e40e54c52862d4/href</a></iframe><h3>Sample Results</h3><p>We have run this model to get predicted mcats against a user and recommendation score against the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*95rOQS-W080Ee7NiAFZgDw.png" /><figcaption>Random;y generated output format</figcaption></figure><p><strong>e.g </strong>A seller who is currently dealing in mcats like<strong> </strong>Currency Counting Machine, Spot Billing Machine, Portable barcode Printers, Handheld Billing machine, etc. Let us see what model is recommending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*3geq7wtqzSvGNt6z" /><figcaption><strong>MCATs in which a seller has products available or purchasing buy leads</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/0*0XiNqSDNNA8rusvG" /><figcaption><strong>MCATs recommended by the model</strong></figcaption></figure><h3>Summary</h3><p>In this article, we have discussed how to build a recommendation system using Alternating Least Square method of implicit collaborative filtering. We have covered the optimization of the model to save computational time and system utilization, and we have also discussed how to save and reload our model using pickle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa04d6ab1fd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying Products as Banned Or Approved using Text Mining- Part II]]></title>
            <link>https://medium.com/data-science/classifying-products-as-banned-or-approved-using-text-mining-part-ii-1cdd9b7ebc6e?source=rss-17b024118255------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdd9b7ebc6e</guid>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fasttext]]></category>
            <category><![CDATA[moderation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Thu, 25 Apr 2019 12:48:15 GMT</pubDate>
            <atom:updated>2019-04-29T07:35:38.740Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this part, we will explain how to optimize the existing Machine Learning model in <a href="https://towardsdatascience.com/classifying-products-as-banned-or-approved-using-text-mining-5b48d2eb1544">Part I</a> and the deployment of this ML model using Flask.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*jbfAi9yVWv7J4FtdwSZnpw.png" /><figcaption>Connecting the dots -moving from M to L in Machine Learning</figcaption></figure><p>In the previous article of this series, We have discussed the business problem, shown how to train the model using fastText and classification of Banned or Approved products based on information like(<em>Product Name, product description, and specifications</em>). <strong>To understand a product in the context of </strong><a href="https://dir.indiamart.com/"><strong>Indiamart</strong></a><strong> please refer to this </strong><a href="https://towardsdatascience.com/classifying-products-as-banned-or-approved-using-text-mining-5b48d2eb1544"><strong>article</strong></a><strong>.</strong></p><h3>Going from 85% to 98% and aiming more…..</h3><p>The accuracy of the model as mentioned in the previous article was 85% when we match the results with a human auditor.</p><p>In order to improve the accuracy of this model, we have included some additional data while training the model and performed hyper-parameter tuning. In machine learning, more accurate training data gives better results<em>(we can say that for the machine, garbage in is garbage out and vice-versa).</em></p><h3><strong>The Hyper-Parameter Tuning:</strong></h3><p>In fastText, there are some tuning parameters<em>(like Learning Rate(LR),wordN-grams, Charancter_nGrams(minn), Number of iterations(epoch), etc.)</em>which can be optimized to improve the performance of the classifier while training the model. These tuning parameters vary from case to case.</p><p>In our case, we ran multiple permutations and combinations on these hyperparameters while training the model and then selected the best among them. Use the below commands to get models with multiple combinations of tuning parameters.</p><pre>while read p; do while read q; do while read r; do while read s; do fasttext  supervised -input ~/Desktop/Banned_Model/train.txt -output ~/Desktop/Banned_Model/hypertuned/$p.$q.$r.$s -lr $p -minn $q -epoch $r -wordNgrams $s -thread 4 -loss hs -lrUpdateRate 100; done ; done</pre><p>At this stage, we have created more than 2k unique models. Next step was to select the best one among them. The testing command to select the best model based on its precision, recall, and accuracy is as follows:</p><pre>for b in ~/Desktop/Banned_Model/hypertuned/*.bin ;do ( echo Test results with $b &amp;&amp; fasttext test $b /home/Desktop/test\val.txt ); done &gt;&gt; /home/Desktop/banned_hyper_parameters_test.txt</pre><p>Using this approach we were able to select the best model based on the most suitable combination of hyper-parameters. These hyper-parameters may vary from one use case to another.</p><p><strong>The Model Accuracy:</strong></p><p>At this stage, the model is able to predict correctly at an accuracy of above 98% when we match the results with a human auditor and we have finalized our Machine Learning model and saved it as a ‘.bin’ file. The next goal was to put this machine learning model on production.</p><h3><strong>The Model Deployment: Getting things live</strong></h3><p>The simple way here is to call a REST API and get predictions from the model. As we know there are a number of web dev frameworks written in javascript, ASP.net, PHP, etc. But in our case, we have used python to create our machine learning model and we were looking for a web-based interface in python itself. Here <a href="http://flask.pocoo.org/">Flask</a> came into the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*1nwAzh8UAQT3yeH8N7KX0g.png" /><figcaption>ML Model deployment using Flask</figcaption></figure><blockquote><strong>What is Flask?</strong></blockquote><p>Flask is a python based <strong>microframework</strong> than can be used to develop web applications, websites, deploy the ML model quite easily. The <strong>microframework</strong> Flask is based on the Pocoo projects Werkzeug and Jinja2. Werkzeug is a toolkit for Web Server Gateway Interface (WSGI) applications and is licensed under a <a href="http://flask.pocoo.org/docs/1.0/license/">BSD License</a>. Before moving to the deployment we need to download flask and some other libraries.</p><pre><strong>pip install flask</strong></pre><p>Let&#39;s create a folder <strong>Flask_Deploy </strong>and copy the Machine Learning model into the same.</p><pre><strong>mkdir Flask_Deploy</strong></pre><p>Next step is to create two python scripts, one for handling data pre-processing/cleaning and another one for getting requests to predict results based on textual input.</p><p>Import flask in python.</p><blockquote><strong>app = flask.Flask(__name__) :</strong> To create an instance of Flask</blockquote><blockquote><strong>@app.route(“/predict”) : </strong><em>Used to specify the flask app route over the web. for e.g: http://0.0.0.0:5000/predict?msg=The input string .</em><strong><em>“predict and msg” are keys here</em></strong><em>.</em></blockquote><p>To access the string submitted in the URL(?msg = Input String) we use below attributes:</p><pre><strong>Input = flask.request.args.get(&quot;msg&quot;)</strong></pre><blockquote><strong>flask.jasonify(data): </strong><em>Used to return a python dictionary in a JSON format.</em></blockquote><blockquote><strong>app.run(host=0.0.0.0)</strong><em>: Used to run flask app on host address. In this example we ar running it on local host.</em></blockquote><p>After creating the web application, we will get a URL that points to our flask endpoint. Thanks <a href="https://medium.com/u/ba9d2ef2623c">Shantanu Aggarwal</a> @ Alok Kumar for helping with this code on such a short notice .In order to handle data pre-processing, we have created a script preprocess.py and saved in the same directory(Flask_Deploy) where we have saved the ML model file so that, we can call it easily whenever required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1593558c542d31429ef4b7e33ff95860/href">https://medium.com/media/1593558c542d31429ef4b7e33ff95860/href</a></iframe><p>In our case, we are getting a lot of unnecessary data like special characters, hyperlinks, some stop-words, duplicated word, etc. To handle these we have created the below script as per our use case and saved it as preprocess.py</p><p><strong>Script to handle data cleaning and pre-processing:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b02f70e6e4d57a8c01145ac32e301caa/href">https://medium.com/media/b02f70e6e4d57a8c01145ac32e301caa/href</a></iframe><h3><strong>The Final Run :</strong></h3><pre><strong>cd Flask_Deploy<br>python3 flask_banned_model.py</strong></pre><p>After deploying the model we are able to check the predictions, model accuracy, latency as well as load handling time of the model. We can also log the results, data input, latency, etc. into a table as per our requirements.</p><h3><strong>Conclusion:</strong></h3><p>The ultimate aim of any machine learning model is to go live without much fuss. The above simple but effective model was finally deployed after a lot of team effort and hard work was put in. Also, we are glad to mention that we were able to achieve a remarkable latency of approximately 4 ms for the above model. We are exhaustively testing the model for any issues and the next article in the series will share the performance of the model and the optimization in terms of time and money we were able to save or incur due to this model.</p><h3>When Team Work Does Wonders !!</h3><p>The model is a fruit of the continuous efforts by the entire team. Thanks @<a href="https://medium.com/u/47a096395dd5">Vikram Varshney</a>, <a href="https://medium.com/u/f3022f1424ae">Sunil Parolia</a> for initiating the project, <a href="https://medium.com/u/a9b6c476fde">Prachi Jain</a> for model training and hyper parameter tuning, <a href="https://medium.com/u/7012b8be20c2">Pradeep Chopra</a>, @ Ritika Aggarwal for ensuring thorough testing of the model , @Medha Tyagi @Ankita Saraswat for all the product side knowledge @Alok Kumar ,@ Puneet Aggarwal , <a href="https://medium.com/u/ba9d2ef2623c">Shantanu Aggarwal</a> @ Shipra Gupta , @Abhishek Arora for all the help with the deployment of the model , @ Saurabh Singhal , @ Neeta Singhal for comprehensive evaluation of the model and providing wonderful insights throughout.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdd9b7ebc6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/classifying-products-as-banned-or-approved-using-text-mining-part-ii-1cdd9b7ebc6e">Classifying Products as Banned Or Approved using Text Mining- Part II</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plotting text and image vectors using t-SNE]]></title>
            <link>https://medium.com/data-science/plotting-text-and-image-vectors-using-t-sne-d0e43e55d89?source=rss-17b024118255------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e43e55d89</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 11 Mar 2019 13:27:08 GMT</pubDate>
            <atom:updated>2019-03-11T15:44:21.748Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How to plot multidimensional vectors created using Infersent and Resnet in two-dimensional space.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ba8uvFOXvmp0rrIsF8149Q.png" /><figcaption>Power to your eye - Happy Visualizing</figcaption></figure><h3>Doing wonders with Visualization</h3><p>John Micternan rightly pointed out that ‘In presentation lies the true entertainment’, and if you can present your data in a way the other guy wished, he would be in a state of bliss. Imagine a world where communication of all data could be visualized, both my brain and my boss would thank me for the gesture. <a href="https://medium.com/u/47a096395dd5">Vikram Varshney</a> <a href="https://medium.com/u/f3499cb43377">Ayush Gupta</a> . Given the human brain’s comfort when it comes to pictorial content and considering the fact the 90% of the information transmitted through the human brain is visual,we have tried to plot sentence and image vectors in a 2-D space ,where each spatial spot represents a sentence and similar sentence vectors would be placed in spatial proximity.</p><p><strong>The Problem Statement:</strong></p><p>To plot sentence and image vectors where sentence vectors are arrived at using Infersent or Google’s Universal Sentence Encoder and images vectors are features extracted in the Resnet 50 model.</p><p>Our sentences are nothing but a combination of a Product’s Name, description and its specifications whereas an Image is basically the product image. To get a hold of what a product means in the context of Indiamart, please <a href="https://towardsdatascience.com/classifying-products-as-banned-or-approved-using-text-mining-5b48d2eb1544">read here.</a></p><h3><strong>Understanding Text and Image Vectors</strong></h3><p>Text vectors (either word vectors or sentence vectors )are created by converting textual data into the numerical form using embedding techniques like word2vec, fasttext, Infersent, Google universal sentence encoder etc. The dimension of your vector may depend upon your technique of preparing it. For example, Infesent creates a vector of 4096 dimensions for each sentence, whereas GUSE(Google Universal Sentence Encoder) creates a vector of 512 dimensions for each sentence.</p><p>Image vectors are the feature vector of an image created using some image feature extraction techniques. In our case, we have Resnet image vectors having 512 dimensions for each and every image.</p><p><em>Note: In this post, we are not dwelling into details of a sentence or word embedding (they will be covered separately in another blog), rather the focus is how we depicted them on a scatter plot.</em></p><h3><strong>Going Multidimensional and Coming Back</strong></h3><p>The difficulty with visualizing the distributed representation of text and image feature vectors is that they are multidimensional(for e.g some vectors are 512 dimensional whereas some are of 4096 dimensions) which are quite higher than the usual 2 or 3-dimensional vector plots that human can see and interpret.</p><p>Since there are no direct ways to project these data points on the plot that is easy for humans to understand, we need some powerful method to map these high dimensional data into 2 or 3-dimensional space. Here t-SNE played the trick for us.</p><p>The below images shows how each vector was converted to a 2-D Array for ease of plotting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*-I7E6BdHBl6GshEgmk4WOw.png" /><figcaption>Multidimensional Vectors converted to a two-dimensional vector using t-SNE.</figcaption></figure><h3><strong>What is t-SNE?</strong></h3><p><a href="http://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf">t-SNE</a> stands for t-distributed stochastic neighbor embedding. It is a technique for dimensionality reduction that is best suited for the visualization of high dimensional data-set. t-SNE is a randomized algorithm, i;e every time we run the algorithm it returns slightly different results on the same data-set. To control this we set a random state with some arbitrary value. Random state is used here to seed the cost function of the algorithm.</p><h3><strong>Giving Colors to thoughts -The Scatter Plot</strong></h3><p>The below steps will guide you to depict your vectors on a scatter plot.</p><p><strong>Step1: </strong>Import necessary libraries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8d4547bf94314f7907a3947989e5a7/href">https://medium.com/media/fb8d4547bf94314f7907a3947989e5a7/href</a></iframe><p><strong>Step 2: Loading vectors created using different embedding techniques: </strong>In this step, we have loaded the large dimensional vector created using GUSE, Infersent or Resnet (in case of image vectors) and fitted into 2 d space using t-SNE algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff093ad548c792777f62d0f6d59d321/href">https://medium.com/media/3ff093ad548c792777f62d0f6d59d321/href</a></iframe><p><strong>Step 3: Create a User defined function to plot the above vector in 2-d space: </strong>We have used a combination of t-SNE, matplotlib and seaborn to create the scatter plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12ec073eb2a39c299579a0579a38515d/href">https://medium.com/media/12ec073eb2a39c299579a0579a38515d/href</a></iframe><p><strong>Step 4: Visualizing and saving the plot</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2b91c712a024703d00d0365a7c6ca54/href">https://medium.com/media/f2b91c712a024703d00d0365a7c6ca54/href</a></iframe><p><strong><em>Visualization based on K-Means cluster of the above sentence vectors</em></strong></p><p>We used <a href="https://en.wikipedia.org/wiki/K-means_clustering">K-Means </a>clustering to group similar sentence vectors. 18 such clusters were formed. The below scatter diagram shows the distribution of products within each cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vp4MZDhbaB3g_HO1bmsZmA.png" /></figure><p><strong><em>Visualization based on the existing cluster of the sentence vectors.</em></strong></p><p>Here the sentence vectors were plotted on the basis of it’s existing cluster. Each product (sentence vector) belongs to some cluster or category and each category has a unique color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQ-St6tKVmm_uDV0N9mk0Q.png" /><figcaption>We can see how the products(sentences) from Earthmoving Bucket are spread across the plot suggesting their nearness to other related clusters.</figcaption></figure><p><strong>Adding an axis to your 2-d space: </strong>We can do the same by simply setting x-limit(going from -60 to + 60 in our case) and y-limit(going from -60 to +60) on the axis</p><h4>De-coding the plot</h4><p>Each dot in the scatter plot represents the text inside a single product. Products with semantically similar text are placed close to each other. The color of each dot represents the cluster to which it belongs i.e all sentences in cluster 0 are represented in red, in cluster 1 are represented in orange and so on.</p><p><strong><em>Visualization of Image vectors</em></strong></p><p>Each spot in the plot represents the features of a single image. Similar images fall in a closely knit space. Each image is converted to feature vectors using Resnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAqNIrK86wYQHB65hY0_4A.jpeg" /><figcaption>Image Vectors plotted in a 2-D Space. On close observation, it is seen that similar images are occupying close spaces while different image vectors are scattered in the plot.</figcaption></figure><h3>Putting things to use</h3><p>The scatter plot has multiple applications for us-it told us how similar our existing images or sentences were and whether the current categorization is appropriate with respect to the products mapped in it. It also helped us categorize a new set of products or images.</p><p>Check out the <a href="https://github.com/ashutoshsingh25/Plotting-multidimensional-vectors-using-t-SNE/blob/master/TSNE%20Code%20for%20clusring%20image%20and%20text%20vectors%20with%20labels.ipynb">full python code on my Github</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e43e55d89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/plotting-text-and-image-vectors-using-t-sne-d0e43e55d89">Plotting text and image vectors using t-SNE</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying Products as Banned Or Approved using Text Mining]]></title>
            <link>https://medium.com/data-science/classifying-products-as-banned-or-approved-using-text-mining-5b48d2eb1544?source=rss-17b024118255------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b48d2eb1544</guid>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[moderation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Wed, 02 Jan 2019 15:36:12 GMT</pubDate>
            <atom:updated>2019-08-26T06:56:54.851Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classifying Products as Banned Or Approved using Text Mining Part-I</h3><h4>Product Classification as Banned or Approved based on textual information available against it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*OdUj1NCHLkGYBizhEt1_Iw.jpeg" /><figcaption>Classifying products as Approved or Rejected based on its content.</figcaption></figure><p>Let me start with some facts that I have established over my limited encounters with machine learning based problems — ‘You can’t find the best fit as there is none, just keep trying — that’s the key’ and ‘data is the best investment option you have — spend a lot of time on it’.</p><p>Coming to the problem at hand — <strong>identify ‘banned’ content on Indiamart, an online platform </strong>which attracts millions of users every day. By ‘banned’ I mean the content which is not allowed as per the current legal framework in the country and what’s more -it’s dynamic. eg: A jacket made of cow leather is a ‘banned’ product while a leather upholstery executive revolving chair is not.</p><p>Before moving forward, let us get hold of what a product is in the context of <a href="https://dir.indiamart.com/">Indiamart</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGnWIizdVOdya5B3uMaFkA.png" /><figcaption>This is a product. We have over 60 million such products with us.</figcaption></figure><p><em>Note: I will be using the product in the context of content in the article. A product here is nothing but a description of what content is available against a particular item. A product has a title, a description, an image of the item you are selling, it’s price etc.</em></p><h3>Understanding the Problem</h3><p>We had to classify our products<em>(new as well as existing)</em>as <strong>Approved</strong> or <strong>Banned</strong> based on the information available against it.</p><blockquote>For instance ,any product which mentions of narcotic salts needs to be marked as ‘banned’ and removed from the mainstream content.</blockquote><h3>The ‘Keyword’ Based Challenge</h3><p>In our current approach, we mark a product as banned or approved based on keyword match, i.e We have a list of banned keywords and if that keyword exists in the product’s name, we mark it as banned else mark it as approved.</p><p>What this lead to was that certain relevant products were being classified as banned though they should have been approved eg. ‘Cat’ is present in our list of banned keywords, so products like ‘wooden cat gift pieces’, ‘CAT Bulldozer’ etc got banned which led to the loss of good content.</p><h3>Solving the ‘Cat Vs Cat’ Conundrum</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*qqUqFW3lKfcFZAQ6lVMbAA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*UzjH6SsnwKBgUSvTO8yfpA.jpeg" /><figcaption>‘Cat’ -the animal and the machine</figcaption></figure><p>A supervised text-based classifier which was trained using previously labeled examples played the trick for us. <strong>The goal of this classifier was to categorize a product in one of the two labels ‘Banned’ or ‘Approved’</strong> .eg of the labels used for training</p><blockquote>_label_Approved dell wireless mouse black color</blockquote><blockquote>_label_Banned cowhide leather black jacket</blockquote><p>We fed the machine with an existing set of products labeled as ‘Banned’ or ‘Approved’ for it to build a relationship so that it can predict whether a product should be accepted or rejected. Then a different set of products was again fed to the machine and it was asked whether this product should be accepted or rejected.</p><p>We were able to better capture the intent and context of the product this time- <strong>a CAT bulldozer or a CAT Excavator was not ‘banned’ while ‘cat fur jacket’ was banned.</strong></p><p><em>The description and specifications available against products (which was not being considered in the existing keyword service ) were also used to train and test the model.</em></p><h3>The Testing Machine: What’s Under The Hood</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*GgLb5y5Ba-BbkEg6cAr21g.png" /><figcaption>Process Flow for the Problem</figcaption></figure><p>We used fastText to train our model. <a href="http://fasttext.cc/">fastText</a> is an open source library from <strong>Facebook</strong> for efficient learning of word representations and sentence classification.</p><p><em>In case you are new to fastText and face issues running it, please refer to this </em><a href="https://youtu.be/nXp5aWWoWeY"><em>video tutorial</em></a><em>.</em></p><p>Training Data: A file having labeled data rows. All products essentially had one of the two labels either ‘Banned’ or ‘Approved’ and the corpus was all the content available against the product.</p><p><strong>Training Command :</strong></p><pre><em>~/fastText/fasttext.exe supervised -input ~/Training_Files/training_file.txt -output ~/Model_path/model.bin -lr 0.5 -epoch 75 -minn 5-thread 4 -wordNgram 2 -lrUpdateRate 100;</em></pre><p><em>Note: The hyper-parameters used here have been selected after performing hyper-parameter tuning which allows you to get parameters which will help you get an enhanced accuracy for your use case. These may vary depending upon the data-set under consideration</em></p><p><strong>Training the model in python:</strong></p><p>We can also perform the same in python using below mention code, it will create the model file(.bin).</p><pre>$ git clone https://github.com/facebookresearch/fastText.git<br>$ cd fastText<br>$ pip install .<br><br>import fastText<br><br>train_file_name = &quot;training_model.txt&quot;<br>model_name = &quot;Banned_Model&quot;<br><br>classifier = fasttext.train_supervised(str(train_file_name),<br>                                            str(model_name), label_prefix=&#39;__label__&#39;,<br>                                            epoch=75,lr=0.5,word_ngrams=2,minn 5,bucket=200000,dim=100,loss=&#39;hs&#39;)</pre><pre># To Save the model for further use:<br>classifier.save_model(&quot;Banned_Model.bin&quot;)</pre><pre># To Predict the classes/Labels from the above model</pre><pre>model = fastText.load_model(model_name+&quot;.bin&quot;)<br>Test_String = [&#39;xyz&#39;]<br>Model_Results = model.predict(Test_String,k=1)[0][0][0]</pre><p><strong>Precision and Recall:</strong></p><pre>P@1    : 0.987<br>R@1    : 0.987</pre><p><strong>Testing The Model :</strong></p><pre>~/fastText/fasttext.exe predict-prob ~/Model_path/model.bin - 1;</pre><p>You will get something like this on your output screen</p><pre>imart@DESKTOP-CFGCP74 ~                                                                                                               <br>$ fastText/fasttext.exe predict-prob ~/Model_path/model4mo1.bin - 1                                         <br>deca durabolin nandrolene decatonate bottle                                                                                           <br>__label__Banned 0.995814</pre><p>K Fold Cross Validation was used to validate the model.</p><p><strong>An interesting example:</strong> Samsung mobile phones which are not banned while their fake counterparts are banned. Can the model detect such cases? Lets test</p><pre>imart@DESKTOP-CFGCP74 ~                                                                                                               <br>$ fastText/fasttext.exe predict-prob ~/Model_path/model4mo1.bin/model4mo1.bin - 1                                         <br><strong>samsung mobile phone </strong>                                                                                                                 <br>__label__<strong>Approved</strong> 1.00001                                                                                                             <br><strong>samsung clone mobile phone</strong>                                                                                                            <br>__label__<strong>Banned</strong> 1.00002</pre><h3>Data Cleaning: The Master Stroke</h3><p>In machine learning , ‘<strong>Garbage In is Garbage Out</strong>’ so make sure that you perform required data operations before using your data for training the model — here we converted entire data to lowercase, removed XML, HTML tags like &lt;li&gt;&lt;/li&gt;,&lt;ui&gt;&lt;/ui&gt; etc., special symbols and stop-words relevant for the use case.</p><h3>What about Product Images❓</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*LcUEgvUJMHmt-uFWNtpgOA.png" /></figure><p>A Product Image having lots of text.</p><blockquote><strong>Text Extracted using OCR</strong>👉 B-Complex Mutimineras,With Antioxidants Capsules Minreal Promotes Energy Metabolism Supports Heart Health Ria</blockquote><p>Some products have images with text written on them. <strong>Extracting that text and feeding that into the model also helped us to better categorize the product as ‘Banned’ or ‘Approved’.</strong> OCR(<strong>Optical Character Recognition)</strong> was used here to extract the relevant data from the image.</p><h3>What is OCR❓</h3><p><strong>OCR</strong> stands for <strong>Optical Character Recognition</strong>. Using OCR we can scan images and documents containing texts and converts them into documents that can be edited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*9QVJ_7GbTN7FsdoxjwyDRw.jpeg" /><figcaption>image scanning application using OCR</figcaption></figure><p>In our case, OCR helps us to extract text from product images, more importantly in cases where no textual information is available in the Product Name, Product Description, and Specification.</p><p><strong>Google Cloud Vision API and Tesseract </strong>can be explored for this.</p><h3>The Road Ahead</h3><p>As of now, the model is accurate for every 85/100 products being tested by it when we match results with a human auditor. Another fact that I am able to gather is that ‘<em>the real world is not as easily classified as we tend to believe</em>’, the use of a human will always be necessary to determine “gray areas” that require a human touch. I am working on reducing these gray areas and will soon come up with a follow-up article. Please refer to <a href="https://towardsdatascience.com/classifying-products-as-banned-or-approved-using-text-mining-part-ii-1cdd9b7ebc6e">Part II</a> of this series for further read.</p><p><a href="https://medium.com/u/47a096395dd5">Vikram Varshney</a>, <a href="https://medium.com/u/f3499cb43377">Ayush Gupta</a> thanks for your continuous contribution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b48d2eb1544" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/classifying-products-as-banned-or-approved-using-text-mining-5b48d2eb1544">Classifying Products as Banned Or Approved using Text Mining</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>