<?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 Md Shahbaz Alam on Medium]]></title>
        <description><![CDATA[Stories by Md Shahbaz Alam on Medium]]></description>
        <link>https://medium.com/@msalamiitd?source=rss-eeae2c1b5903------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U8MiexS_ncoRHgIj1HiXeA.jpeg</url>
            <title>Stories by Md Shahbaz Alam on Medium</title>
            <link>https://medium.com/@msalamiitd?source=rss-eeae2c1b5903------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:48:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msalamiitd/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[Enhancing Your Shopping Experience: The Power of Amazon Product Recommendation]]></title>
            <link>https://msalamiitd.medium.com/enhancing-your-shopping-experience-the-power-of-amazon-product-recommendation-63b51edf7ae5?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b51edf7ae5</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 13:20:51 GMT</pubDate>
            <atom:updated>2024-02-10T13:20:51.193Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Your digital ally in the pursuit of products, transforming the art of browsing into a science of personalization.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPssSxmMlJeMyQbalWcc1w.png" /></figure><h3><strong>Introduction</strong></h3><p>In the vast digital marketplace, where choices seem endless and decision-making can be overwhelming, Amazon stands out as a beacon of convenience and diversity. One of the key features that contribute to Amazon’s success is its robust product recommendation system. Seamlessly integrated into the user experience, Amazon’s recommendation engine utilizes advanced algorithms and user behavior analysis to provide personalized suggestions, making the shopping journey more enjoyable and efficient.</p><h3>Table of contents:</h3><ol><li>Business problem.</li><li>Source of Data/Data Extraction.</li><li>Evaluation metrics.</li><li>Mapping the real-world problem.</li><li>Exploratory Data Analysis(EDA).</li><li>Data Engineering.</li><li>Machine Learning Models.</li><li>Deep Learning Models.</li><li>Deployment.</li><li>Future Work and Improvements.</li><li>References.</li></ol><h3>1. Business problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*scGXHXiqFpE3W1iCJPW3jg.png" /></figure><ul><li>Whenever we visit amazon.com, this is our <strong>product image</strong>. We have multiple images of the same product.</li><li>“DHRUVI TRENDZ” is the <strong>brand name</strong>.</li><li>“DHRUVI TRENDZ Women’s Regular fit Rayon Shirt” is the<strong> title</strong>. The title has a lot of interesting and important information.</li><li>Below the title, we have the <strong>price,size,colour and then product description.</strong></li></ul><p>Then it shows related/similar products in terms of our search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BazCfWp6cVX_tVAMetcztw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TColffx5dTA4-PWLf_k1w.png" /></figure><ul><li>It also shows us “customer also shopped for” products which are also recommendations.</li><li><strong>Why care about product recommendations?</strong><br>It is estimated that around 35% of the revenues that amazon makes are because of product recommendations. Due to product recommendation bars, as shown above, the user ends up buying a product or two.</li></ul><h4>Amazon internally uses two types of recommendation systems:</h4><p>1)<strong> Content-Based Recommendation:</strong> <em>When we search about polka dot shirts, it uses text and images to recommend similar products</em>.<br>2) <strong>Collaborative filtering based Recommendation:<br></strong><em>Imagine, User U1 browsed through products i1,i2,i3<br>User U2 browsed through i1,i3,i4<br>Then I can recommend User U3, the product i3 when he is on page i1.<br>So, this is called a collaborative filtering-based recommendation. Unfortunately, we don’t have this data.</em></p><p>So, in our case study, we will use content-based recommendations.</p><h3>2. Source of Data/Data Extraction.</h3><p>Diverse data sources were tapped to curate information on Amazon products</p><p>1. Encompassing data acquired from third-party <a href="https://cseweb.ucsd.edu/~jmcauley/datasets.html#amazon_reviews">sources</a> and leveraging web scraping techniques.</p><p>2. In adherence to policies, the Amazon Product Advertising API was strategically employed to procure comprehensive data from amazon.com.</p><p>Focused on women’s tops and shirts, the dataset comprises approximately 183,000 products, enriched with key attributes such as Image-URL, Title, Price, Product Description, among others. Our analytical emphasis is primarily directed towards the dataset pertaining to women’s tops.</p><h3>3. Evaluation metrics.</h3><p>We are use <strong><em>Euclidean distance</em></strong> as evaluation metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*IJ0ervC3d49r_JC9sgvIaQ.png" /><figcaption>Euclidean distance</figcaption></figure><h4>a. Similarity Measurement:</h4><ul><li>Euclidean distance provides a measure of similarity between items in a multi-dimensional space. In the context of product recommendation, each product can be represented as a vector in this space based on its features (such as product attributes, user reviews, or image features).</li></ul><h4>b. Vector Representation:</h4><ul><li>Products with similar features or characteristics will have vectors that are close to each other in the multi-dimensional space, while dissimilar products will have vectors that are farther apart. Euclidean distance quantifies this spatial separation.</li></ul><h3>4. Mapping the real-world problem.</h3><p>Amazon’s product recommendation system addresses a real-world problem by enhancing user experience and driving business outcomes. Here’s how it maps to real-world challenges and solutions:</p><h4>Information Overload and Choice Paralysis:</h4><p>In online marketplaces like Amazon, users face an overwhelming number of product options. The recommendation system streamlines the vast product catalog, presenting users with personalized suggestions based on their preferences, reducing information overload, and helping users make informed decisions.</p><h4>Personalization and Relevance:</h4><p>Generic product recommendations may not resonate with individual user preferences. Amazon’s recommendation system analyzes user behavior, past purchases, and preferences to deliver personalized suggestions. This enhances the relevance of recommendations, making the shopping experience more tailored to each user.</p><h4>Increasing Business Revenue:</h4><p>Maximizing sales and revenue is a core objective for e-commerce platforms. The recommendation system drives cross-selling and upselling opportunities by suggesting complementary products or higher-value items. This contributes to increased average order values and overall revenue.</p><h3>5. Exploratory Data Analysis(EDA).</h3><p>EDA is the most crucial component of any statistical or mathematical modeling. EDA assists us in better understanding the data and gaining new insights. Only when we have a thorough grasp of the data can we apply significant feature engineering to it. Dataset is a set of data points. A row here represents a product in this dataset which is also known as data point.</p><ul><li>Each column represents a variable/feature of a given product. For ex: It can have a price, title, imageURL etc.</li><li>Number of data points/products: 183138</li><li>Number of features/variables: 19</li></ul><h4>Sample of data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Z8_ZWCFacrlLMchbIrhAQ.png" /></figure><blockquote><strong><em>Some important features</em></strong></blockquote><p><strong><em>1. Asin (Amazon standard identification number):</em></strong> A unique no given to each product at amazon.com.<br><strong><em>2. Brand:</em></strong> brand to which the product belongs to)<br><strong><em>3. color:</em></strong> color information of apparel, it can contain many colors as a value , for ex: black and blue stripes)<br><strong><em>4. product_type_name:</em></strong> Type of the apparel, ex: SHIRT/TSHIRT )<br><strong><em>5. medium_image_url:</em></strong> URL of the image)<br><strong><em>6. title:</em></strong> Title of the product<br><strong><em>7. formatted_price:</em></strong> price of the product.</p><h4>5.1 Missing Items.</h4><p>As you can see there are some columns contains null values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*yrYk1hrubhrqrpVfrzoRKg.png" /></figure><p>All 10 columns contains more than 50% of NULL values.</p><h4>5.2 Product type</h4><p>Product database is biased around product types, most of the product types is Shirt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgWaWN_yQ7k3KZz-eQ894Q.png" /></figure><h4>5.3 Brand type</h4><p>There are so many brands,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5Uo2MdG2cCeKfmZ1UsF7A.png" /></figure><h4>5.4 Color</h4><p>As you can see that most of the products contains black color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUG1jbrnypBGUF0m4i_PwQ.png" /></figure><h4>5.5 Title</h4><p>There are so many titles are repeated, we have to go depth deeper about the titles, may be there are so some products which have different ASIN number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owFyaYhz-LulH4ostSSLHg.png" /></figure><h4>5.6 Duplicates items</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7X3jqkdtL83oHlmkx6UO9Q.png" /></figure><h4>6. Data Engineering.</h4><p>There are so many duplicates title.</p><blockquote><strong>Remove duplicates : part 1</strong></blockquote><p>we can observe these products/Shirts are exactly same in color except different in size maybe(S,M,L,XL). Let’s say, the first image is the query product and we have to find similar products. If we recommend these exact shirts as query product of just different size to the customer , then it leads to bad customer experience because titles are exactly same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*oOi2PtfN70nuJbHLKcRJwQ.png" /></figure><blockquote><strong>Remove duplicates : part 2</strong></blockquote><p>we can observe these products/Shirts are exactly different color. Let’s say, the first image is the query product and we have to find similar products. If we recommend these exact shirts as query product of just different size to the customer , then it leads to bad customer experience because titles are exactly same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kGyiNcLUeehlNK2y0StqVA.png" /></figure><p>In our data there are many duplicate products like the above examples, we need to de-dupe them for better results.</p><h3>7. Machine Learning Models.</h3><blockquote>Text based product similarity</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/0*cUPNokcsYoQNgD1N.png" /></figure><ul><li>For every product, we have a title. <strong>Given a title, How can we convert it into a d-dimensional point ? </strong>There are multiple ways to convert a text into d-dimensional point.</li><li>Given a d-dimensional representation of title,we can use similarity measures to find similar products.</li></ul><h4>7.1 Bag of Words(BOW).</h4><p>a. Apply BOW on Title feature.</p><p><strong>Converting text to an n-D vector</strong></p><ol><li>S = Set of words which are present in any of the titles (T1,T2,T3,….,Tn).<br>Let’s say this set S has size “d”, or d is size of unique words in S.<br>d = no of unique words in S.</li><li>Now , I will be creating a d-dimensional vector for each title. Let’s say word1 in vocabulary/set is present 0 times in title 1, so we put value as “0” in the vector. Similarly word 4 is present 2 times in title 1, so we put the value as “2” in the vector.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*8g8IxQ_0X9pP7ZGx.png" /></figure><p>So in bag of words, I am excluding the sequence of the text or the sequence information. It is an extremely simple &amp; powerful technique.</p><blockquote><strong><em>Bag of Words based Product Similarity</em></strong></blockquote><ul><li>Our function bag_of_words_model takes title id and no of similar products you want it to recommend as the parameters.</li><li>pairwise_dist will store the distance from given input apparel to all remaining apparels. The metric I used here is euclidian distance to measure distance between one title to another title.</li><li>np.argsort will return indices of the smallest distances of title feature.</li><li>pdists will store the smallest distances of title feature.</li><li>data frame indices also stored the indices of smallest distaces.</li><li>we will pass<br>1. doc_id<br>2. title1<br>3. title2<br>4. URL<br>5.model to the get_result function.</li><li>Now, we will call the bag-of-words model for a product to get similar products.</li></ul><blockquote>Search product………………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MvP8Jet0Ks89WZXx11ZBA.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmL9e-HO1qqpS-QPtd93fA.png" /><figcaption>1st recommended product</figcaption></figure><p>1st recommended product. The difference between 1st recommend product and search product is by one word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5p1ZMiU7zDvp8WlHcwmKw.png" /><figcaption>2nd recommended product</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QPG5EP-9wPz00Oqx7W_BQ.png" /><figcaption>3rd recommended product</figcaption></figure><h4>b. Apply BOW on Title feature with additional features(color, brand, and product type).</h4><p>In this approach algorithm is also use the brand, color and product types as features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S52nywgGOhMWaoK3tlgETg.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WnyJuW7OQDj_RxaqE2XCQ.png" /></figure><p>As we seen first recommended product title have so much difference from search product title but it recommend due to color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HI1e40V7aAAIJ0mYdPMnsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC1YVox82sZdIVaJOoeODQ.png" /></figure><ul><li>Let’s understand the visualization: heatmap<br>Here it says, the word pink is not present in the query, that’s why it is “0”.<br>The word tiger is present in query, so it is “1”.<br>Similarly all other words are present in the query.<br>The more pink it is or the more non zero values you have, the more closer both titles are or the more is the overlap. The color represents the intersection with the query/input title.</li></ul><blockquote><strong>Code….</strong></blockquote><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product using BOW algorithm based on color,<br>brand, product type, and title.<br>=================================================================<br>&quot;&quot;&quot;<br>import pandas as pd<br>import requests<br>import re<br>from io import BytesIO<br>from PIL import Image<br>import numpy as np<br>import seaborn as sns<br>from sklearn.metrics import pairwise_distances<br>from sklearn.feature_extraction.text import CountVectorizer<br>from collections import Counter<br>from matplotlib import gridspec<br>import matplotlib.pyplot as plt<br><br>__author__ = &quot;Md Shahbaz Alam&quot;<br>__email__ = &quot;msalamiitd@gmail.com&quot;<br>__credits__ = &quot;Md Shahbaz Alam&quot;<br><br><br>class Recommendation_BOW:<br>    def __init__(self, asin, num_results):<br>        self.asin_index = None<br>        self.title_features = None<br>        self.data = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br>        self.asin = asin<br>        self.num_results = num_results<br><br>    def display_img(self, url, ax, fig):<br>        response = requests.get(url)<br>        img = Image.open(BytesIO(response.content))<br>        plt.imshow(img)<br><br>    def plot_heatmap(self, keys, values, labels, url, text):<br>        gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[4, 1])<br>        fig = plt.figure(figsize=(25, 3))<br>        ax = plt.subplot(gs[0])<br>        ax = sns.heatmap(np.array([values]), annot=np.array([labels]))<br>        ax.set_xticklabels(keys)<br>        ax.set_title(text)<br>        ax = plt.subplot(gs[1])<br>        ax.grid(False)<br>        ax.set_xticks([])<br>        ax.set_yticks([])<br>        self.display_img(url, ax, fig)<br>        plt.show()<br><br>    def plot_heatmap_image(self, doc_id, vec1, vec2, url, text, model):<br>        intersection = set(vec1.keys()) &amp; set(vec2.keys())<br>        for i in vec2:<br>            if i not in intersection:<br>                vec2[i] = 0<br>        keys = list(vec2.keys())<br><br>        values = [vec2[x] for x in vec2.keys()]<br><br>        labels = values<br><br>        self.plot_heatmap(keys, values, labels, url, text)<br><br>    def text_to_vector(self, text):<br>        word = re.compile(r&#39;\w+&#39;)<br>        words = word.findall(text)<br>        return Counter(words)<br><br>    def get_result(self, doc_id, content_a, content_b, url, model):<br>        text1 = content_a<br>        text2 = content_b<br>        vector1 = self.text_to_vector(text1)<br>        vector2 = self.text_to_vector(text2)<br>        self.plot_heatmap_image(doc_id, vector1, vector2, url, text2, model)<br><br>    def vectorized(self):<br>        title_vectorizer = CountVectorizer()<br>        self.title_features = title_vectorizer.fit_transform(self.data[&#39;title&#39;])<br><br>    def get_similar_product(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            self.vectorized()<br>            pairwise_dist = pairwise_distances(self.title_features, self.title_features[self.asin_index])<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            return indices<br>        else:<br>            return None<br><br>    def bag_of_words_model(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            self.vectorized()<br>            pairwise_dist = pairwise_distances(self.title_features, self.title_features[self.asin_index])<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            pdists = np.sort(pairwise_dist.flatten())[0:self.num_results]<br>            df_indices = list(self.data.index[indices])<br>            for i in range(0, len(indices)):<br>                self.get_result(indices[i], self.data[&#39;title&#39;].loc[df_indices[0]],<br>                                self.data[&#39;title&#39;].loc[df_indices[i]], self.data[&#39;medium_image_url&#39;].loc[df_indices[i]],<br>                                &#39;bag_of_words&#39;)<br>                print(&#39;ASIN :&#39;, self.data[&#39;asin&#39;].loc[df_indices[i]])<br>                print(&#39;Brand:&#39;, self.data[&#39;brand&#39;].loc[df_indices[i]])<br>                print(&#39;Title:&#39;, self.data[&#39;title&#39;].loc[df_indices[i]])<br>                print(&#39;Euclidean similarity with the query image :&#39;, pdists[i])<br>                print(&#39;=&#39; * 100)<br>        else:<br>            print(&#39;ASIN number is not in data base&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    recommendation = Recommendation_BOW(asin=&#39;B015YKMU80&#39;, num_results=3)<br>    recommendation.bag_of_words_model()</pre><h4>7.2 Term frequency and inverse document frequency(TF-IDF).</h4><p><strong>featurizing text based on word-importance</strong></p><ul><li>Each of title is known as document and collection of document is known as document corpus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*i6MRSc2SgwEsfu2yntynoQ.png" /></figure><ul><li>Term frequency means how frequently a term or word occurs in a document/title. If wj occurs multiple times in a title, then term frequency also increases.</li><li>IDF(Inverse Document Frequency): Given a document corpus and word j, it gives us natural logarithm of no of documents in the corpus by no of documents in the corpus that contains the word Wj.</li></ul><blockquote>Search product………………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fyNlRVfV46jo-7_dRpPsQ.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfFpq1IvffiooLWXLcfSfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsAFJPgGJMCRM96BWbWU-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iT3-JuJzoIu3Ur8H1QAhOg.png" /></figure><p>Code…..</p><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product using TFIDF algorithm based on color,<br>brand, product type, and title.<br>========================================================================<br>&quot;&quot;&quot;<br><br>import pandas as pd<br>import requests<br>import re<br>from io import BytesIO<br>from PIL import Image<br>import numpy as np<br>import seaborn as sns<br>from sklearn.metrics import pairwise_distances<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from collections import Counter<br>from matplotlib import gridspec<br>import matplotlib.pyplot as plt<br><br>__author__ = &quot;Md Shahbaz Alam&quot;<br>__email__ = &quot;msalamiitd@gmail.com&quot;<br>__credits__ = &quot;Md Shahbaz Alam&quot;<br><br><br>class Recommendation_TFIDF:<br>    def __init__(self, asin, num_results):<br>        self.title_features = None<br>        self.title_vectorizer=None<br>        self.data = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br>        self.asin = asin<br>        self.num_results = num_results<br><br>    def display_img(self, url, ax, fig):<br>        response = requests.get(url)<br>        img = Image.open(BytesIO(response.content))<br>        plt.imshow(img)<br><br>    def plot_heatmap(self, keys, values, labels, url, text):<br>        gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[4, 1])<br>        fig = plt.figure(figsize=(25, 3))<br>        ax = plt.subplot(gs[0])<br>        ax = sns.heatmap(np.array([values]), annot=np.array([labels]))<br>        ax.set_xticklabels(keys)<br>        ax.set_title(text)<br>        ax = plt.subplot(gs[1])<br>        ax.grid(False)<br>        ax.set_xticks([])<br>        ax.set_yticks([])<br>        self.display_img(url, ax, fig)<br>        plt.show()<br><br>    def plot_heatmap_image(self, doc_id, vec1, vec2, url, text):<br>        intersection = set(vec1.keys()) &amp; set(vec2.keys())<br>        for i in vec2:<br>            if i not in intersection:<br>                vec2[i] = 0<br>        keys = list(vec2.keys())<br><br>        values = [vec2[x] for x in vec2.keys()]<br>        labels = []<br>        for x in vec2.keys():<br>            if x in self.title_vectorizer.vocabulary_:<br>                labels.append(self.title_features[doc_id, self.title_vectorizer.vocabulary_[x]])<br>            else:<br>                labels.append(0)<br><br>        self.plot_heatmap(keys, values, labels, url, text)<br><br>    def text_to_vector(self, text):<br>        word = re.compile(r&#39;\w+&#39;)<br>        words = word.findall(text)<br>        return Counter(words)<br><br>    def get_result(self, doc_id, content_a, content_b, url):<br>        text1 = content_a<br>        text2 = content_b<br>        vector1 = self.text_to_vector(text1)<br>        vector2 = self.text_to_vector(text2)<br>        self.plot_heatmap_image(doc_id, vector1, vector2, url, text2)<br><br>    def vectorized(self):<br>        title_vectorizer = TfidfVectorizer(min_df=0.0)<br>        title_features = title_vectorizer.fit_transform(self.data[&#39;title&#39;])<br>        return title_vectorizer, title_features<br><br><br>    def get_similar_product(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            self.title_vectorizer, self.title_features = self.vectorized()<br>            pairwise_dist = pairwise_distances(self.title_features, self.title_features[self.asin_index])<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            return indices<br>        else:<br>            return None<br><br>    def tfidf_model(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            self.title_vectorizer, self.title_features =self.vectorized()<br>            pairwise_dist = pairwise_distances(self.title_features, self.title_features[self.asin_index])<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            pdists = np.sort(pairwise_dist.flatten())[0:self.num_results]<br>            df_indices = list(self.data.index[indices])<br>            for i in range(0, len(indices)):<br>                self.get_result(indices[i], self.data[&#39;title&#39;].loc[df_indices[0]],<br>                                self.data[&#39;title&#39;].loc[df_indices[i]], self.data[&#39;medium_image_url&#39;].loc[df_indices[i]])<br>                print(&#39;ASIN :&#39;, self.data[&#39;asin&#39;].loc[df_indices[i]])<br>                print(&#39;Brand:&#39;, self.data[&#39;brand&#39;].loc[df_indices[i]])<br>                print(&#39;Title:&#39;, self.data[&#39;title&#39;].loc[df_indices[i]])<br>                print(&#39;Euclidean similarity with the query image :&#39;, pdists[i])<br>                print(&#39;=&#39; * 100)<br>        else:<br>            print(&#39;ASIN number is not in data base&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    recommendation = Recommendation_TFIDF(asin=&#39;B015YKMU80&#39;, num_results=3)<br>    recommendation.tfidf_model()</pre><h4>7.3 Inverse document frequency(IDF).</h4><blockquote>Observation of IDF</blockquote><ul><li>Words don’t repeat often.</li><li>There are variations in titles, as there are longer and shorter titles.</li><li>Term frequency(TF) for shorter titles are high. In that case, tfidf will prefer shorter titles.</li><li>So in our case, term frequency would have made sense if Ti is a web-page or a long document, because words that occur more often should be given importance. Here each title is hardly having 15 or 20 words, so it’s better to drop term frequency and use only IDF(Inverse document frequency).We can experiment it out and see for the results if it worked out better than tfidf or not.</li><li>To use IDF attribute only and ignore TF values, we fitted data using CountVectorizer and defined our own IDF function.</li><li>In our case it did not work out that well.</li></ul><blockquote>Search product………………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByO3Z1FvMOjBUZLDF1zw4Q.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Qe_7FZt8GFqkMUopnq2Ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vMCqdR6DsX489Bfhf6_JQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyD9r65iN4wPAooRjIh5cQ.png" /></figure><p>Code…..</p><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product using IDF based on color, brand,<br>product type, and title.<br>=======================================================================<br>&quot;&quot;&quot;<br><br>import pandas as pd<br>import requests<br>import re<br>import math<br>import logging<br>from io import BytesIO<br>from PIL import Image<br>import numpy as np<br>import seaborn as sns<br>from sklearn.metrics import pairwise_distances<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from collections import Counter<br>from matplotlib import gridspec<br>import matplotlib.pyplot as plt<br><br>__author__ = &quot;Md Shahbaz Alam&quot;<br>__email__ = &quot;msalamiitd@gmail.com&quot;<br>__credits__ = &quot;Md Shahbaz Alam&quot;<br>LOGGER = logging.getLogger(__name__)<br><br><br>class Recommendation_IDF:<br>    def __init__(self, asin, num_results):<br>        self.title_features = None<br>        self.title_vectorizer = None<br>        self.data = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br>        self.asin = asin<br>        self.num_results = num_results<br><br>    def display_img(self, url, ax, fig):<br>        response = requests.get(url)<br>        img = Image.open(BytesIO(response.content))<br>        plt.imshow(img)<br><br>    def plot_heatmap(self, keys, values, labels, url, text):<br>        gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[4, 1])<br>        fig = plt.figure(figsize=(25, 3))<br>        ax = plt.subplot(gs[0])<br>        ax = sns.heatmap(np.array([values]), annot=np.array([labels]))<br>        ax.set_xticklabels(keys)<br>        ax.set_title(text)<br>        ax = plt.subplot(gs[1])<br>        ax.grid(False)<br>        ax.set_xticks([])<br>        ax.set_yticks([])<br>        self.display_img(url, ax, fig)<br>        plt.show()<br><br>    def plot_heatmap_image(self, doc_id, vec1, vec2, url, text):<br>        intersection = set(vec1.keys()) &amp; set(vec2.keys())<br>        for i in vec2:<br>            if i not in intersection:<br>                vec2[i] = 0<br>        keys = list(vec2.keys())<br><br>        values = [vec2[x] for x in vec2.keys()]<br>        labels = []<br>        for x in vec2.keys():<br>            if x in self.title_vectorizer.vocabulary_:<br>                labels.append(self.title_features[doc_id, self.title_vectorizer.vocabulary_[x]])<br>            else:<br>                labels.append(0)<br><br>        self.plot_heatmap(keys, values, labels, url, text)<br><br>    def text_to_vector(self, text):<br>        word = re.compile(r&#39;\w+&#39;)<br>        words = word.findall(text)<br>        return Counter(words)<br><br>    def get_result(self, doc_id, content_a, content_b, url):<br>        text1 = content_a<br>        text2 = content_b<br>        vector1 = self.text_to_vector(text1)<br>        vector2 = self.text_to_vector(text2)<br>        self.plot_heatmap_image(doc_id, vector1, vector2, url, text2)<br><br>    def vectorized(self):<br>        title_vectorizer = TfidfVectorizer(min_df=0.0)<br>        title_features = title_vectorizer.fit_transform(self.data[&#39;title&#39;])<br>        for i in title_vectorizer.vocabulary_.keys():<br>            idf_val = self.idf(i)<br>            for j in title_features[:, title_vectorizer.vocabulary_[i]].nonzero()[0]:<br>                title_features[j, title_vectorizer.vocabulary_[i]] = idf_val<br>        return title_vectorizer, title_features<br><br>    def n_containing(self, word):<br>        # return the number of documents which had the given word<br>        return sum(1 for blob in self.data[&#39;title&#39;] if word in blob.split())<br><br>    def idf(self, word):<br>        # idf = log(#number of docs / #number of docs which had the given word)<br>        return math.log(self.data.shape[0] / (self.n_containing(word)))<br><br>    def get_similar_product(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            self.title_vectorizer, self.title_features = self.vectorized()<br>            pairwise_dist = pairwise_distances(self.title_features, self.title_features[self.asin_index])<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            return indices<br>        else:<br>            return None<br><br>    def idf_model(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            self.title_vectorizer, self.title_features = self.vectorized()<br>            pairwise_dist = pairwise_distances(self.title_features, self.title_features[self.asin_index])<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            pdists = np.sort(pairwise_dist.flatten())[0:self.num_results]<br>            df_indices = list(self.data.index[indices])<br>            for i in range(0, len(indices)):<br>                self.get_result(indices[i], self.data[&#39;title&#39;].loc[df_indices[0]],<br>                                self.data[&#39;title&#39;].loc[df_indices[i]], self.data[&#39;medium_image_url&#39;].loc[df_indices[i]])<br>                print(&#39;ASIN :&#39;, self.data[&#39;asin&#39;].loc[df_indices[i]])<br>                print(&#39;Brand:&#39;, self.data[&#39;brand&#39;].loc[df_indices[i]])<br>                print(&#39;Title:&#39;, self.data[&#39;title&#39;].loc[df_indices[i]])<br>                print(&#39;Euclidean similarity with the query image :&#39;, pdists[i])<br>                print(&#39;=&#39; * 100)<br>        else:<br>            print(&#39;ASIN number is not in data base&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    recommendation = Recommendation_IDF(asin=&#39;B015YKMU80&#39;, num_results=3)<br>    recommendation.idf_model()</pre><h4>7.4 Average word 2 Vec.</h4><p>Bag of words, tfidf and idf don’t account for semantics. All were frequency based techniques and used to return sparse vectors.</p><ul><li>Given title, we want it to convert it into d- dimensional array and use euclidean distance for finding similarity. But can we find semantic similarity ?</li><li>One such very popular technique is Word2Vec. It returns me an dense array or most of the cells are non zero. Word2Vec algorithm will observe pattern in our data corpus and give us a d-dimensional vector. Word2Vec typically requires very large data corpus.</li><li>Google has trained Word2Vec on google news corpus and for each word in this corpus we get 300 dimensional vector. Google has provided us this model free of cost. So we will use google news word2vec.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*XFTt2ry49v-FiXZU8gEQEw.png" /></figure><ul><li>Let’s assume there are k words in our title Ti. To get word2vec of Ti, we take sum of all the first components of all words, similarly keep adding components of all cells till 300 dimension and get a new vector. I will then divide all the components of the new vector by k. This is known as average word2Vec of any sentence.</li></ul><blockquote><strong><em>Search products………………………</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00wpVAQ0sEBycSJ0hzDd9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*ILfYSv_ULY9q2yLf9u9Zww.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3S-E05bV-9SIsaqA_DinA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*KaEwcwl8V6YAVbUvWYkiBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MKEQJE5VkLfuUZzyOujuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*lLXMFDLidOxSOrKCdMxGMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOQgO6-tPpM72pkI9Abw5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*qP4XzTbVlc65GHUrFuZDKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JALKE0d_dysFYM9_7GJmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*FJk7crXiJsOvIfPB8R2iWw.png" /></figure><p>Code……</p><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product using Average word to vector <br>based on color, brand, product type, and title.<br>========================================================================================<br>&quot;&quot;&quot;<br>import pickle<br>import requests<br>import logging<br>import matplotlib.pyplot as plt<br>from PIL import Image<br>from io import BytesIO<br>import seaborn as sns<br>import pandas as pd<br>from sklearn.metrics import pairwise_distances<br>from matplotlib import gridspec<br>import numpy as np<br><br>__author__ = &quot;Md Shahbaz Alam&quot;<br>__email__ = &quot;msalamiitd@gmail.com&quot;<br>__credits__ = &quot;Md Shahbaz Alam&quot;<br>LOGGER = logging.getLogger(__name__)<br><br><br>class Recommendation_word2vec:<br>    def __init__(self, asin, num_results):<br>        self.vocab = None<br>        self.model = None<br>        self.w2v_title = []<br>        self.data = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br>        self.asin = asin<br>        self.num_results = num_results<br><br>    def display_img(self, url, ax, fig):<br>        response = requests.get(url)<br>        img = Image.open(BytesIO(response.content))<br>        plt.imshow(img)<br><br>    def get_distance(self, vec1, vec2):<br>        final_dist = []<br>        for i in vec1:<br>            dist = []<br>            for j in vec2:<br>                dist.append(np.linalg.norm(i - j))<br>            final_dist.append(np.array(dist))<br>        return np.array(final_dist)<br><br>    def get_word_vec(self, sentence, doc_id, m_name):<br>        vec = []<br>        for i in sentence.split():<br>            if i in self.vocab:<br>                vec.append(self.model[i])<br>            else:<br>                vec.append(np.zeros(shape=(300,)))<br>        return np.array(vec)<br><br>    def build_avg_vec(self, sentence, num_features, doc_id, m_name):<br>        &quot;&quot;&quot;<br>        Get average word to vec algorithm<br>        :param sentence: string<br>        :param num_features: int<br>        :param doc_id: int<br>        :param m_name: string<br>        :return:<br>        &quot;&quot;&quot;<br><br>        featureVec = np.zeros((num_features,), dtype=&quot;float32&quot;)<br>        nwords = 0<br>        for word in sentence.split():<br>            nwords += 1<br>            if word in self.vocab:<br>                featureVec = np.add(featureVec, self.model[word])<br>        if nwords &gt; 0:<br>            featureVec = np.divide(featureVec, nwords)<br>        return featureVec<br><br>    def heat_map_w2v(self, sentence1, sentence2, url, doc_id1, doc_id2, model):<br>        &quot;&quot;&quot;<br>        Get the heat map<br>        :param sentence1: list<br>        :param sentence2: array<br>        :param url: str<br>        :param doc_id1: int64<br>        :param doc_id2: int<br>        :param model: str<br>        :return: None<br>        &quot;&quot;&quot;<br>        s1_vec = self.get_word_vec(sentence1, doc_id1, model)<br>        s2_vec = self.get_word_vec(sentence2, doc_id2, model)<br>        s1_s2_dist = self.get_distance(s1_vec, s2_vec)<br>        gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[2, 1])<br>        fig = plt.figure(figsize=(15, 15))<br>        ax = plt.subplot(gs[0])<br>        ax = sns.heatmap(np.round(s1_s2_dist, 4), annot=True)<br>        ax.set_xticklabels(sentence2.split())<br>        ax.set_yticklabels(sentence1.split())<br>        ax.set_title(sentence2)<br><br>        ax = plt.subplot(gs[1])<br>        ax.grid(False)<br>        ax.set_xticks([])<br>        ax.set_yticks([])<br>        self.display_img(url, ax, fig)<br><br>        plt.show()<br><br>    def get_similar_product(self):<br>        &quot;&quot;&quot;<br>        Find similar product<br>        :return: int<br>        &quot;&quot;&quot;<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            doc_id = 0<br>            with open(&#39;database/word2vec_model&#39;, &#39;rb&#39;) as f:<br>                self.model = pickle.load(f)<br>            self.vocab = self.model.keys()<br>            for i in self.data[&#39;title&#39;]:<br>                self.w2v_title.append(self.build_avg_vec(i, 300, doc_id, &#39;avg&#39;))<br>                doc_id += 1<br>            self.w2v_title = np.array(self.w2v_title)<br>            pairwise_dist = pairwise_distances(self.w2v_title, self.w2v_title[self.asin_index].reshape(1, -1))<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            return indices<br>        else:<br>            return None<br><br>    def avg_w2v_model(self):<br>        &quot;&quot;&quot;<br><br>        :return:<br>        &quot;&quot;&quot;<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            doc_id = 0<br>            with open(&#39;database/word2vec_model&#39;, &#39;rb&#39;) as f:<br>                self.model = pickle.load(f)<br>            self.vocab = self.model.keys()<br>            for i in self.data[&#39;title&#39;]:<br>                self.w2v_title.append(self.build_avg_vec(i, 300, doc_id, &#39;avg&#39;))<br>                doc_id += 1<br>            self.w2v_title = np.array(self.w2v_title)<br>            pairwise_dist = pairwise_distances(self.w2v_title, self.w2v_title[self.asin_index].reshape(1, -1))<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            pdists = np.sort(pairwise_dist.flatten())[0:self.num_results]<br>            df_indices = list(self.data.index[indices])<br><br>            for i in range(0, len(indices)):<br>                self.heat_map_w2v(self.data[&#39;title&#39;].loc[df_indices[0]], self.data[&#39;title&#39;].loc[df_indices[i]],<br>                                  self.data[&#39;medium_image_url&#39;].loc[df_indices[i]], indices[0], indices[i], &#39;avg&#39;)<br>                print(&#39;ASIN :&#39;, self.data[&#39;asin&#39;].loc[df_indices[i]])<br>                print(&#39;BRAND :&#39;, self.data[&#39;brand&#39;].loc[df_indices[i]])<br>                print(&#39;euclidean distance from given input image :&#39;, pdists[i])<br>                print(&#39;=&#39; * 125)<br>        else:<br>            print(&#39;ASIN number is not in data base&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    recommendation = Recommendation_word2vec(asin =&#39;B015YKMU80&#39;, num_results=3)<br>    recommendation.avg_w2v_model()</pre><h4>7.5 Weighted Word 2 vec.</h4><p>Instead of computing TF-IDF, we can only compute TF-IDF weighted Word2Vec. TF-IDF also gives us word importance in our corpus because if a word occurs few times then it is given higher importance and word2vec gives us semantic similarity. I have not used term frequencies with word2vec in my code because titles are small and most words occur only once.</p><blockquote>Search products………………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UK0cOuSbAska4SWiWLeTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*caywpYggYAwr8PHJbPrBRw.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWZqTcZwLzn3b4GBe4pJFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*wAFqMVb9FjFL6h_R2yH6_w.png" /></figure><p>1st recommended product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaUFyauZEDk9HAWMiTxY-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*xM78ad9L3pqsj6D2QUsYBg.png" /></figure><p>2nd recommended product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wi-P5oPShb4jZ9LZlUg2Fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*G9M-dYz1RjD9VLTA_GiB-w.png" /></figure><p>3rd recommended product.</p><h4>7.6 Algorithm with color and brand as additional features.</h4><p>Till now, we have just used titles for product similarity. We have not used brand and color yet. These are the additional variables, that we can leverage.</p><ul><li>For each product Pi, we already got title vector. Similarly for each product Pi, we will get brand vector and color vector. Once we get these 3 vectors, we will concatenate these vectors.</li><li>Let’s say, I have m no of brands. Let’s assume, product bi has brand bi, How do I write it as a vector ?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*T4SKm0qd1JzDOxO3zSbodA.png" /></figure><ul><li>So this will be a m dimensional vector. The value corresponding to the cell which is the brand is let’s say ith index value. Only ith index value in the vector will be “1” , rest all the cells will have “0” as the value. Such an encoding is called one hot encoding. Similarly, we will carry out one hot encoding for colors too.</li><li>Now after concatenating, I have a vector where part of the vector is representing title, part of the vector is representing brand and part of the vector is representing color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*RqkcYyoj1HSetGo0SPxqdg.png" /></figure><ul><li>Let’s assume, we want to prefer showing our customers products of the same brand or same color. So, can I modify my euclidean distance to somehow incorporate this preference ?<br>All we have to do is to take weighted euclidean distance. We have to construct three weights : weights for title (Wt), weights for brand (Wb), weights for color (Wc). Then you multiple each of the elements of title vector with Wt, each of the elements of brand vector with Wb and each of the elements of color vector with Wc. After you multiply, you just take the euclidean distances.</li></ul><blockquote>Search products………………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZRvho9GGIEeOEyJeFEiCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*du2yKoIoR5tA8yIQIen9OQ.png" /></figure><blockquote>Recommended Products…………………</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lvpCjv3svQzCQkpAR8W7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*S6e1yt_y7B4tQ7J2j-x5DA.png" /></figure><p>1st recommended products</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyaleITfcFqaQG8tyME0NQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*esXupCHVxpi-a-CgdQWfHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oiu0ix4s_RXdB2lnloV8_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*1_oj-sSHE5T-mdOtttnDQQ.png" /></figure><p>Code…….</p><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product using weighted word to vector<br>based on color, brand, product type, and title.<br>========================================================================================<br>&quot;&quot;&quot;<br>import pickle<br>import requests<br>import matplotlib.pyplot as plt<br>from PIL import Image<br>from io import BytesIO<br>import seaborn as sns<br>import pandas as pd<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.metrics import pairwise_distances<br>from matplotlib import gridspec<br>import numpy as np<br><br><br>class Recommendation_weighted_word2vec:<br>    def __init__(self, asin, num_results):<br>        self.vocab = None<br>        self.model = None<br>        self.title_features = None<br>        self.title_vectorizer = None<br>        self.w2v_title = []<br>        self.data = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br>        self.asin = asin<br>        self.num_results = num_results<br><br>    def display_img(self, url, ax, fig):<br>        response = requests.get(url)<br>        img = Image.open(BytesIO(response.content))<br>        plt.imshow(img)<br><br>    def get_distance(self, vec1, vec2):<br>        final_dist = []<br>        for i in vec1:<br>            dist = []<br>            for j in vec2:<br>                dist.append(np.linalg.norm(i - j))<br>            final_dist.append(np.array(dist))<br>        return np.array(final_dist)<br><br>    def get_word_vec(self, sentence, doc_id, m_name):<br>        vec = []<br>        for i in sentence.split():<br>            if i in self.vocab and i in self.title_vectorizer.vocabulary_:<br>                vec.append(self.title_features[doc_id, self.title_vectorizer.vocabulary_[i]] * self.model[i])<br>            else:<br>                vec.append(np.zeros(shape=(300,)))<br>        return np.array(vec)<br><br>    def build_avg_vec(self, sentence, num_features, doc_id, m_name):<br><br>        featureVec = np.zeros((num_features,), dtype=&quot;float32&quot;)<br>        nwords = 0<br>        for word in sentence.split():<br>            nwords += 1<br>            if word in self.vocab:<br>                featureVec = np.add(featureVec, self.model[word])<br>        if nwords &gt; 0:<br>            featureVec = np.divide(featureVec, nwords)<br>        return featureVec<br><br>    def heat_map_w2v(self, sentence1, sentence2, url, doc_id1, doc_id2, model):<br>        s1_vec = self.get_word_vec(sentence1, doc_id1, model)<br>        s2_vec = self.get_word_vec(sentence2, doc_id2, model)<br>        s1_s2_dist = self.get_distance(s1_vec, s2_vec)<br>        gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[2, 1])<br>        fig = plt.figure(figsize=(15, 15))<br>        ax = plt.subplot(gs[0])<br>        ax = sns.heatmap(np.round(s1_s2_dist, 4), annot=True)<br>        ax.set_xticklabels(sentence2.split())<br>        ax.set_yticklabels(sentence1.split())<br>        ax.set_title(sentence2)<br><br>        ax = plt.subplot(gs[1])<br>        ax.grid(False)<br>        ax.set_xticks([])<br>        ax.set_yticks([])<br>        self.display_img(url, ax, fig)<br><br>        plt.show()<br>    def vectorized(self):<br>        title_vectorizer = TfidfVectorizer(min_df=0.0)<br>        title_features = title_vectorizer.fit_transform(self.data[&#39;title&#39;])<br>        return title_vectorizer, title_features<br><br>    def get_similar_product(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            doc_id = 0<br>            self.title_vectorizer, self.title_features = self.vectorized()  # Fix here<br>            with open(&#39;database/word2vec_model&#39;, &#39;rb&#39;) as f:<br>                self.model = pickle.load(f)<br>            self.vocab = self.model.keys()<br>            for i in self.data[&#39;title&#39;]:<br>                self.w2v_title.append(self.build_avg_vec(i, 300, doc_id, &#39;avg&#39;))<br>                doc_id += 1<br>            self.w2v_title = np.array(self.w2v_title)<br>            pairwise_dist = pairwise_distances(self.w2v_title, self.w2v_title[self.asin_index].reshape(1, -1))<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            return indices<br>        else:<br>            return None<br><br>    def weighted_w2v_model(self):<br>        self.data = self.data.reset_index(drop=True)<br>        self.asin_index = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            doc_id = 0<br>            self.title_vectorizer, self.title_features = self.vectorized()  # Fix here<br>            with open(&#39;database/word2vec_model&#39;, &#39;rb&#39;) as f:<br>                self.model = pickle.load(f)<br>            self.vocab = self.model.keys()<br>            for i in self.data[&#39;title&#39;]:<br>                self.w2v_title.append(self.build_avg_vec(i, 300, doc_id, &#39;avg&#39;))<br>                doc_id += 1<br>            self.w2v_title = np.array(self.w2v_title)<br>            pairwise_dist = pairwise_distances(self.w2v_title, self.w2v_title[self.asin_index].reshape(1, -1))<br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            pdists = np.sort(pairwise_dist.flatten())[0:self.num_results]<br>            df_indices = list(self.data.index[indices])<br><br>            for i in range(0, len(indices)):<br>                self.heat_map_w2v(self.data[&#39;title&#39;].loc[df_indices[0]], self.data[&#39;title&#39;].loc[df_indices[i]],<br>                                  self.data[&#39;medium_image_url&#39;].loc[df_indices[i]], indices[0], indices[i], &#39;avg&#39;)<br>                print(&#39;ASIN :&#39;, self.data[&#39;asin&#39;].loc[df_indices[i]])<br>                print(&#39;BRAND :&#39;, self.data[&#39;brand&#39;].loc[df_indices[i]])<br>                print(&#39;euclidean distance from given input image :&#39;, pdists[i])<br>                print(&#39;=&#39; * 125)<br>        else:<br>            print(&#39;ASIN number is not in data base&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    recommendation = Recommendation_weighted_word2vec(asin=&#39;B0758TBKRJ&#39;, num_results= 3)<br>    recommendation.weighted_w2v_model()</pre><h3>8. Deep Learning Models.</h3><blockquote><strong>ConvNets: How to featurize an image: edges, shapes, parts</strong></blockquote><ul><li>For each product Pi, I possess a unique URL linking to its respective image. To convert these images into d-dimensional vectors, I leverage Convolutional Neural Networks (CNNs), specifically VGG-16. This process involves extracting diverse features, including edges, shapes, colors, and patterns such as flower or animal prints.</li><li>We have the capability to extract diverse features from images, encompassing details such as edges, shapes, colors, and intricate patterns like flower or animal prints. Upon considering an image, we can systematically construct a vector wherein distinct segments represent color, shapes, and patterns or edges. This structured vectorization allows us to employ Euclidean distance as a metric to measure the dissimilarity between two vectors.</li><li>When presented with an image, I employ Convolutional Neural Networks (CNNs) such as VGG-16 to transform the image into a dense vector representation. In cases where two images exhibit a high degree of similarity, the Euclidean distance between the vectors derived from Image 1 and Image 2, namely Vector 1 and Vector 2 respectively, tends to be minimal.</li><li>We employ the VGG-16 Convolutional Neural Network (CNN) architecture for the purpose of establishing image-based product similarity. VGG-16, a well-established CNN, is adept at transforming input images into high-dimensional vectors, precisely 25,088 dimensions in our specific application.</li><li>All my images are of length (224,224) and I have about 16,042 samples.</li><li>The important function <strong>save_bottlebeck_features</strong> has 3 parts. The first part basically builds the VGG-16 network. The generator part takes each of my images and run through the VGG-16 network and returns me the 25,088 dimensional features. I also collect asins name for each of my product. At the end, I am doing a numpy save, I am saving my 16K images converted into CNN vector features into .npy files along with the asin names.</li><li>Remember, here we include top = false, so it won’t include the last fully connected layers and hence the output won’t be 1000. The last conv layer in VGG-16 gives an output of shape 512 x 7 x7. On flattening this output we will get 25,088 length vector.</li><li>Now we will use euclidean distance to find similarity. I will simply load the image features for the 16K images and their corresponding asins names. I will load the original 16K dataset, where I have title , brand, color, URL , type of each product.Now we will get similar products using CNN features of VGG-16.</li><li>I define the function “get_similar_products_cnn” and pass the parameters such as image id and number of similar results for the query I want. Just like our any previous models, I find my pairwise distances and also find the nearest points. I will just call the function and get similar products.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*Ikg70WtNA9kRkGjI2C9O2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*bCCase_hZAm5AW4a9S6X-w.png" /></figure><blockquote>Here, It will only uses the image to find similar products.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*d9dAW1vLEuNJ1se-x8VJmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*D--n-ycq_GZODUwTvnZMeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*dP2FyEoPNeXGF61BfPSNXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwjPbTraUUsvCr4DJfJOcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*5JZAWyhE0Iv4JEylObUhyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*KIFlHwTrI3o63wZ8C-4qsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*WYjHPPKdSCXadg6Su1ERUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*yaFr3g6zcGO2OJuflpCJVw.png" /></figure><blockquote>Code……</blockquote><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product using pretrained VGG16 model,<br>based on color, brand, product type, and title.<br>========================================================================================<br>&quot;&quot;&quot;<br>import numpy as np<br>from sklearn.metrics import pairwise_distances<br>import matplotlib.pyplot as plt<br>from PIL import Image<br>import pandas as pd<br>import requests<br>import logging<br>from io import BytesIO<br><br>__author__ = &quot;Md Shahbaz Alam&quot;<br>__email__ = &quot;msalamiitd@gmail.com&quot;<br>__credits__ = &quot;Md Shahbaz Alam&quot;<br>LOGGER = logging.getLogger(__name__)<br><br><br>class Deep_Learning_VGG16:<br>    def __init__(self, asin, num_results):<br>        self.asin = asin<br>        self.num_results = num_results<br>        self.data = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br>        self.df_asins = list(self.data[&#39;asin&#39;])<br>        self.bottleneck_features_train = np.load(&#39;database/16k_data_cnn_features.npy&#39;)<br>        self.asins = np.load(&#39;database/16k_data_cnn_feature_asins.npy&#39;)<br><br>    # get similar products using CNN features (VGG-16)<br><br>    def get_similar_product(self):<br>        self.data = self.data.reset_index(drop=True)<br>        doc_id = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            asins = list(self.asins)<br>            # doc_id = asins.index(self.df_asins[doc_id])<br>            pairwise_dist = pairwise_distances(self.bottleneck_features_train,<br>                                               self.bottleneck_features_train[doc_id].reshape(1, -1))<br><br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            return indices<br>        else:<br>            return None<br><br>    def get_similar_products_cnn(self):<br>        self.data = self.data.reset_index(drop=True)<br>        doc_id = self.data[self.data[&#39;asin&#39;] == self.asin].index<br>        asins = list(self.asins)<br>        if self.asin in self.data[&#39;asin&#39;].values:<br>            # doc_id = asins.index(self.df_asins[doc_id])<br>            pairwise_dist = pairwise_distances(self.bottleneck_features_train,<br>                                               self.bottleneck_features_train[doc_id].reshape(1, -1))<br><br>            indices = np.argsort(pairwise_dist.flatten())[0:self.num_results]<br>            pdists = np.sort(pairwise_dist.flatten())[0:self.num_results]<br><br>            for i in range(len(indices)):<br>                rows = self.data[[&#39;asin&#39;, &#39;brand&#39;, &#39;medium_image_url&#39;, &#39;title&#39;]].loc[<br>                    self.data[&#39;asin&#39;] == asins[indices[i]]]<br>                for indx, row in rows.iterrows():<br>                    img = Image.open(BytesIO(requests.get(row[&#39;medium_image_url&#39;]).content))<br>                    plt.imshow(img)<br>                    plt.show()<br>                    print(&#39;Product Title: &#39;, row[&#39;title&#39;])<br>                    print(&#39;ASIN :&#39;, row[&#39;asin&#39;])<br>                    print(&#39;Brand:&#39;, row[&#39;brand&#39;])<br>                    print(&#39;Euclidean Distance from input image:&#39;, pdists[i])<br>                    print(&#39;Amazon Url: www.amzon.com/dp/&#39; + asins[indices[i]])<br>        else:<br>            print(&#39;ASIN number is not in data base&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    recommendation = Deep_Learning_VGG16(&#39;B015YKMU80&#39;, 10)<br>    recommendation.get_similar_products_cnn()</pre><h3>9. Deployment.</h3><p>The model has been deployed using a streamlined process involving Streamlit and Docker applications, enhancing user-friendliness. To optimize accessibility and performance, the application is now hosted on an Amazon EC2 instance, ensuring a seamless and reliable user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzTSioPY8E_u-gdSzB7joQ.png" /><figcaption>Sample of User interface</figcaption></figure><h4>Deployment Overview:</h4><p>In the deployment phase, users have the capability to receive personalized product recommendations based on sophisticated algorithms leveraging the Amazon Standard Identification Number (ASIN). The recommendation engine employs a diverse set of algorithms, including Bag of Words (BOW), Term Frequency-Inverse Document Frequency (TFIDF), Inverse Document Frequency (IDF), Average Word to Vector, Weighted Word to Vector, and a pretrained VGG16 model. The engine intelligently combines the results generated by each algorithm to ensure a comprehensive and refined set of recommendations.</p><h4>Key Parameters for Deployment:</h4><h4>(i) ASIN (Amazon Standard Identification Number):</h4><ul><li>The system processes and refines recommendations based on the unique ASIN associated with each product.</li></ul><h4>(ii) Algorithm Selection.</h4><p>Users have the flexibility to choose from a range of advanced algorithms:<br> a. BOW (Bag of Words)<br> b. TFIDF (Term Frequency-Inverse Document Frequency)<br> c. IDF (Inverse Document Frequency)<br> d. AVG Word to Vec (Average Word to Vector)<br> e. Weighted Word to Vec (Weighted Word to Vector)<br> f. Pretrained VGG16 Model</p><h4>(iii) Algorithm Combination:</h4><ul><li>The recommendation engine intelligently combines the results obtained from each selected algorithm to provide a holistic and diverse set of recommendations.</li></ul><h4>(iv) Number of Recommendations:</h4><p>Users can specify the desired quantity of recommendations to tailor the output to their preferences.</p><p>This deployment framework ensures a sophisticated, customizable, and user-centric experience, utilizing cutting-edge algorithms to deliver highly relevant product recommendations.</p><pre># -- coding: UTF-8 --<br>&quot;&quot;&quot;<br>Method to recommend similar product based on color, brand, product type, and title.<br>========================================================================================<br>&quot;&quot;&quot;<br><br>import pandas as pd<br>from PIL import Image<br>import requests<br>from io import BytesIO<br>import streamlit as st<br>from ML_Algorithm.merge_result import Combine_results<br><br><br>__author__ = &quot;msalamiitd@gmail.com&quot;<br><br><br>st.set_page_config(page_title=&#39;Amazon Recommendation&#39;, page_icon=&#39;🏡&#39;, layout=&#39;centered&#39;)<br>st.title(&#39;:green[Amazon Apparel Recommendations]&#39;)<br><br>if all(key not in st.session_state.keys() for key in &#39;data&#39;):<br>    st.session_state[&#39;data&#39;] = pd.read_pickle(&#39;database/16k_apperal_data_preprocessed&#39;)<br><br><br>def fetch_image_from_https://medium.com/url(url):<br>    response = requests.get(url)<br>    img = Image.open(BytesIO(response.content))<br>    return img<br><br><br>asin_number = st.text_input(&#39;Enter ASIN number&#39;)<br>select_algorithm = st.selectbox(&#39;Choose Algorithm&#39;,<br>                                options=[&#39;Bag of Word(BOW)&#39;,<br>                                         &#39;Term frequency-inverse document frequency(TF-IDF)&#39;,<br>                                         &#39;Inverse document frequency(IDF)&#39;,<br>                                         &#39;Average Word 2 Vec&#39;,<br>                                         &#39;IDF weighted Word 2 vec&#39;,<br>                                         &#39;Algorithm with brand and color&#39;,<br>                                         &#39;Deep Learning(VGG16)&#39;,<br>                                         &#39;All the algorithm combined results&#39;])<br><br>number_ = st.number_input(&#39;Number of recommendation&#39;, min_value=1, max_value=10)<br>data = st.session_state[&#39;data&#39;]<br>submit_button = st.button(label=&#39;Prediction&#39;, type=&#39;primary&#39;)<br>if submit_button:<br>    if asin_number is not None:<br>        indices = Combine_results(asin_number, number_, select_algorithm).Recommended_results()<br>        df_indices = list(data.index[indices])<br>        st.write(&#39;:red[Search Items]&#39;)<br>        indexes = data[data[&#39;asin&#39;] == asin_number].index<br>        col1, col2 = st.columns(2)<br>        with col1:<br>            img_url = data[&#39;medium_image_url&#39;].loc[indexes[0]]<br>            image = fetch_image_from_url(https://medium.com/img_url)<br>            st.image(image)<br>        with col2:<br>            st.write(&#39;ASIN :&#39;, data[&#39;asin&#39;].loc[indexes[0]])<br>            st.write(&#39;Brand:&#39;, data[&#39;brand&#39;].loc[indexes[0]])<br>            st.write(&#39;Title:&#39;, data[&#39;title&#39;].loc[indexes[0]])<br>        st.write(&#39;=&#39;*88)<br>        st.write(&#39;:red[Recommended Items]&#39;)<br>        for i in range(len(df_indices)-1):<br>            col1, col2 = st.columns(2)<br>            with col1:<br>                img_url = data[&#39;medium_image_url&#39;].loc[df_indices[i+1]]<br>                image = fetch_image_from_url(https://medium.com/img_url)<br>                st.image(image)<br>            with col2:<br>                st.write(&#39;ASIN :&#39;, data[&#39;asin&#39;].loc[df_indices[i+1]])<br>                st.write(&#39;Brand:&#39;, data[&#39;brand&#39;].loc[df_indices[i+1]])<br>                st.write(&#39;Title:&#39;, data[&#39;title&#39;].loc[df_indices[i+1]])<br>            st.write(&#39;=&#39;*88)<br>    else:<br>        st.write(&#39;Please! enter correct input&#39;)</pre><h3>10. Conclusion.</h3><ul><li>Recommender system can help the user to find the right product.</li><li>It increases the user engagement.</li><li>In Amazon, 35% of the products get sold due to recommendation.</li><li>It helps to make the content more personalized.</li></ul><h4>11. Future Work and Improvements.</h4><ul><li>Use some more features like price, reviews, model.</li><li>Use Incpetionv3, Resnet instead of VGG16 model for feature extraction.</li><li>Try some more deep learning techniques.</li></ul><h4>12. References.</h4><ul><li><a href="https://www.kaggle.com/code/saurav9786/recommender-system-using-amazon-reviews">https://www.kaggle.com/code/saurav9786/recommender-system-using-amazon-reviews</a></li><li><a href="https://medium.com/mlearning-ai/amazon-fashion-discovery-engine-content-based-recommendation-19d63563ef01">https://medium.com/mlearning-ai/amazon-fashion-discovery-engine-content-based-recommendation-19d63563ef01</a></li><li><a href="https://towardsdatascience.com/building-a-recommender-system-for-amazon-products-with-python-8e0010ec772c">https://towardsdatascience.com/building-a-recommender-system-for-amazon-products-with-python-8e0010ec772c</a></li></ul><p><strong>The implementation code is available on my GitHub page.</strong></p><p><a href="https://github.com/M-S-ALAM/Amazon-Product-Recommendation">GitHub - M-S-ALAM/Amazon-Product-Recommendation</a></p><blockquote>Feel free to share your feedback and contact me on <a href="https://www.linkedin.com/in/md-shahbaz-alam-0395a6184/">LinkedIn</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b51edf7ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safeguarding Stability: A Guide to Data and Model Drift Monitoring]]></title>
            <link>https://msalamiitd.medium.com/safeguarding-stability-a-guide-to-data-and-model-drift-monitoring-59723a48bb46?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/59723a48bb46</guid>
            <category><![CDATA[drift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[eda]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 13:53:39 GMT</pubDate>
            <atom:updated>2023-12-15T13:53:39.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Content</h3><ul><li>Introduction to Drift</li><li>Why do ML models drift ?</li><li>Types of Drift</li><li>How to detect drift ?</li><li>Solution</li></ul><h3>Introduction to Drift</h3><ul><li>Machine learning models are trained with historical data, but once they are used in the real world, they may become outdated and lose their accuracy over time due to a phenomenon called drift.</li><li>Drift is the change over time in the statistical properties of the data that was used to train a machine learning model. This can cause the model to become less accurate or perform differently than it was designed to.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*8UHI6XXukzcj-gQkNqt5gg.png" /></figure><h3>Why do ML Models drift?</h3><h4>1. Relationship between X and Y changes:</h4><p>If we train the model with data from a stable market, it might do well at first. However, if the market becomes more volatile over time, the model might not be able to accurately predict the stock price anymore because the statistical properties of the data have changed.</p><h4>2. Data distribution changes:</h4><p>The input data distribution of the new data changes from the historical data the model was trained upon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_Mux-TxZdnYlB3S-fm5FQ.png" /></figure><h3>Types of Drift</h3><ol><li>Concept Drift</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*H0tkmgBRdb3ylExN0NO1LA.png" /></figure><p>2. Data Drift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*zBsts1io_1Pr2cfVb5DLZQ.png" /></figure><h3>How to detect drift?</h3><ul><li>Monitor Model Performance metrics — accuracy, recall, F1-Score, ROC-AUC etc.</li><li>Monitor Descriptive Statistics.</li><li>Monitor Distribution changes using Statistical tests</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEKsNKmmlHTad8tJiHDawQ.png" /></figure><h4>Kolmogorov-Smirnov (K-S) test:</h4><ul><li>It is a nonparametric statistical test that is used to determine whether two sets of data come from the same distribution. It is often used to test whether a sample of data comes from a specific population or to compare two samples to determine if they come from the same population.</li><li>The null hypothesis in this test is that the distributions are the same. If this hypothesis is rejected, it suggests that there is a drift in the model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*XUlAJlTGozukP6VBs8JzNQ.png" /></figure><h4>Population Stability Index (PSI)</h4><ul><li>Population stability Index (PSI) is a model monitoring metric that is used to quantify how much the distribution of a continuous response variable has changed between two given samples, typically collected at different points in time.</li><li>A high PSI value indicates that there is a significant difference between the distributions of the variable in the two datasets, which may suggest that there is a drift in the model.</li></ul><p>* PSI &lt; 0.1: No major change, you can continue with the current model.</p><p>* PSI &lt; 0.2: Moderate population change, use your best judgement.</p><p>* PSI &gt;= 0.2: Significant population change, model retraining may be required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTLvZLeAueklyQgXRMc8fw.png" /></figure><h4>Kullback-Leibler Divergence</h4><ul><li>The Kullback-Leibler divergence is a measure of the difference between two probability distributions, with a higher divergence indicating a greater degree of difference between the distributions.</li><li>If the divergence is above a certain threshold, this could indicate that there is a drift in the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdt7gw17qI1WLuCkvQFdzw.png" /></figure><h4>Jensen-Shannon Divergence</h4><ul><li>It is defined as the average of the Kullback-Leibler divergences between the two distributions and a third distribution that is the average of the two.</li><li>The Jensen-Shannon divergence is always non-negative and takes on a value of zero if and only if the two distributions are identical.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*u1yAfoKd0PlAP0D9GL6Lzg.png" /></figure><h4>Wasserstein Distance</h4><ul><li>The Wasserstein distance is a measure of the distance between two probability distributions, with a higher distance indicating a greater degree of difference between the distributions. If the distance is above a certain threshold, this could indicate that there is a drift in the data.</li><li>It is important to note that the Wasserstein distance requires the input data to be one-dimensional and non-negative.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*U9KCrCCWgLlBAT4jYf6w9A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59723a48bb46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfer Learning in Deep Learning: Leveraging Pre-trained Models for Faster and Better Training]]></title>
            <link>https://msalamiitd.medium.com/transfer-learning-in-deep-learning-leveraging-pre-trained-models-for-faster-and-better-training-ca8893b2f41c?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8893b2f41c</guid>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 17:37:22 GMT</pubDate>
            <atom:updated>2023-11-02T17:37:22.812Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Transfer Learning will be the next driver of Machine Learning success. — Andrew Ng”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ZgkGxaMXGgtF0Nrg.jpeg" /></figure><blockquote>Transfer learning in simple words is knowledge transfer.</blockquote><p>Deep learning has revolutionized the field of artificial intelligence, enabling machines to learn and make predictions or decisions from complex data. One of the key techniques that has contributed to the success of deep learning is transfer learning. Transfer learning allows us to leverage knowledge gained from solving one problem and apply it to a different, but related problem. This approach has proven to be invaluable in many domains, including computer vision, natural language processing, and more.</p><h3>Introduction</h3><p>In traditional machine learning, models are trained from scratch on a specific dataset for a specific task. The model learns the underlying patterns and features directly from the data. However, in deep learning, especially for complex tasks and large datasets, training models from scratch can be computationally expensive and time-consuming.</p><p>This is where transfer learning comes in. Instead of starting from scratch, we begin with a pre-trained model that has been trained on a large dataset for a related task. The idea is that the knowledge gained by the model in its previous task can be transferred and applied to the new task, often with minimal fine-tuning.</p><h3>1. Understanding Transfer Learning</h3><h4>a. Pre-training on a Source Task:</h4><ul><li>In the first step, a neural network model, often a deep convolutional neural network (CNN) for computer vision tasks, is trained on a large dataset for a source task. This source task is typically a generic problem like image classification on a large dataset like ImageNet.</li><li>During training, the network learns to extract features from the input data (e.g., images) and uses these features to make predictions for the source task.</li></ul><h4>b. Feature Extraction:</h4><ul><li>After the initial training is complete, the early layers of the network have learned to extract useful and general features from the data, which can be applied to a wide range of related tasks.</li><li>These early layers form a feature extractor, which can be thought of as a powerful tool for understanding the underlying structure of the data.</li></ul><h4>c. Fine-tuning for Target Task:</h4><ul><li>For the target task (which could be a more specific problem), a new dataset is collected. This dataset might be smaller than the original dataset used for pre-training and may be related but not identical in nature.</li><li>Instead of training a neural network from scratch, which would require a large amount of data, the pre-trained model is used as a starting point.</li><li>The layers of the pre-trained network are adjusted (fine-tuned) to make them more specific to the new task. This can involve unfreezing some or all of the layers and allowing them to be updated during training.</li></ul><h4>d. Training on Target Task:</h4><ul><li>The model is then trained on the new dataset for the target task. The fine-tuning process updates the weights in the network to adapt it to the specifics of the new data.</li><li>Since the early layers have already learned useful features, the model can learn task-specific features more efficiently and with less data compared to training from scratch.</li></ul><h4>e. Evaluation and Deployment:</h4><ul><li>Once the fine-tuning is complete, the model is evaluated on a separate test set for the target task to assess its performance.</li><li>If the model meets the desired performance criteria, it can be deployed for making predictions on new, unseen data.</li></ul><h3>2. Benefits of Transfer Learning</h3><h4>a. Faster Training</h4><p>Since the model has already learned general features from the pre-training phase, it requires fewer iterations to adapt to the new task. This significantly reduces the time and computational resources needed for training.</p><h4>b. Less Data Dependency</h4><p>Transfer learning can be particularly advantageous when you have a limited amount of data for your specific task. The pre-trained model has already learned useful features from a large dataset, which can be applied to your smaller dataset.</p><h4>c. Improved Generalization</h4><p>Pre-trained models have learned rich feature representations from diverse data. This means they often have a better understanding of the underlying structures in the data, leading to improved generalization performance on a new task.</p><h3>3. Types of Transfer Learning</h3><h4>a. Feature Extraction:</h4><ul><li>In this approach, the pre-trained model’s convolutional base (or earlier layers) is used as a fixed feature extractor. The weights of these layers are frozen, and a new classifier (often a few dense layers) is added on top.</li><li>The input data is passed through the fixed convolutional layers, and the features learned by these layers are then used as input to train the new classifier for the target task.</li><li>This method is particularly useful when the dataset for the target task is small, as it leverages the general features learned by the pre-trained model.</li></ul><h4>b. Fine-tuning or Fine-tuning All Layers:</h4><ul><li>Unlike feature extraction, in fine-tuning, not only are the new layers added on top, but some or all of the pre-trained layers are unfrozen.</li><li>During training, both the new layers and the unfrozen layers from the pre-trained model are updated with backpropagation using the target task’s data.</li><li>This approach can be beneficial when the target task dataset is larger and more similar to the source task dataset, allowing the model to adapt more effectively to the new task.</li></ul><h4>c. Fine-tuning Some Layers:</h4><ul><li>In this variation of fine-tuning, only a subset of the pre-trained layers is unfrozen, while the rest remain frozen.</li><li>This allows for a more controlled adaptation to the new task, as it limits the number of layers that are updated, preventing overfitting, especially when the source and target tasks are only loosely related.</li></ul><h4>d. Pre-training and Multi-Task Learning:</h4><ul><li>In this approach, a model is pre-trained on a large dataset for a source task. After pre-training, additional task-specific heads (outputs) are added to the model, and the model is then fine-tuned on multiple related tasks simultaneously.</li><li>This allows the model to learn representations that are useful for multiple tasks, potentially improving performance across all tasks.</li></ul><h4>e. Zero-Shot Transfer Learning:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*aJXOnYvdC_dCYZQp.png" /></figure><ul><li>In zero-shot transfer learning, a model is trained on a source task but is evaluated on a completely different target task. The model generalizes its learned features to perform tasks it has never seen before.</li><li>This approach is used to test the ability of a model to learn generic features that are broadly applicable.</li></ul><h4>f. One-Shot Transfer Learning:</h4><ul><li>Similar to zero-shot, in one-shot transfer learning, the model is trained on a source task. However, instead of being evaluated on a completely different task, it is evaluated on a target task with very limited data.</li><li>This is a challenging scenario where the model has to quickly adapt to a new task with very little training data.</li></ul><p>These different types of transfer learning allow practitioners to adapt pre-trained models to a wide range of tasks, from those with similar datasets to tasks that are completely different but can still benefit from the learned representations. The choice of transfer learning approach depends on factors like dataset size, similarity between tasks, and available computational resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8893b2f41c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Pass Image Datasets to CNN Models using Image Data Generations]]></title>
            <link>https://msalamiitd.medium.com/how-to-pass-image-datasets-to-cnn-models-using-image-data-generations-b2d9497c7a35?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d9497c7a35</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 09:31:08 GMT</pubDate>
            <atom:updated>2023-11-02T09:32:32.057Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Data will talk to you if you’re willing to listen.” — Jim Bergeson</blockquote><p>Convolutional Neural Networks (CNNs) have revolutionized the field of computer vision, enabling machines to understand and process visual data. To train a CNN effectively, it’s crucial to prepare and feed high-quality image datasets. In this blog post, we’ll explore how to use the ImageDataGenerator class to efficiently pass image datasets to CNN models.</p><h3>Understanding Image Data Generation</h3><p>ImageDataGenerator is a powerful tool provided by the Keras library that allows for on-the-fly data augmentation during the training of CNN models. Data augmentation involves applying various transformations to the training images, such as rotation, zooming, flipping, and more. This helps the model generalize better to unseen data and reduces the risk of overfitting.</p><h3>ImageDataGenerator methods</h3><h4>(1) Flow_from_directory:</h4><p>The <strong>flow_from_directory()</strong> method allows you to read the images directly from the directory and augment them while the neural network model is learning on the training data.</p><p>The method expects that images belonging to different classes are present in different folders but are inside the same parent folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*2lhuTI2bB-eKDT9u.jpeg" /></figure><p>➊ The root directory contains at least two folders one for train and one for the test.</p><p>➋ The train folder should contain <strong><em>n</em></strong> sub-directories each containing images of respective classes.</p><p>➌ The test folder should contain a single folder, which stores all test images.</p><h3><strong>Steps for Image generation using flow from directory</strong></h3><h4>Step 1: Import the Libraries.</h4><pre>import tensorflow as tf<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator</pre><h4>Step 2: Set Up Your Directory Structure.</h4><p>Organize your image dataset into directories. You should have separate folders for training, validation, and test sets. Each of these folders should contain subfolders for each class.</p><h4>Step 3: Create Image Data Generators.</h4><p>Next, you’ll create instances of ImageDataGenerator for the training, validation, and test sets. You can specify the augmentation techniques you want to apply here.</p><pre>train_datagen = ImageDataGenerator(<br>    rescale=1./255,<br>    rotation_range=40,<br>    width_shift_range=0.2,<br>    height_shift_range=0.2,<br>    shear_range=0.2,<br>    zoom_range=0.2,<br>    horizontal_flip=True,<br>    fill_mode=&#39;nearest&#39;<br>)<br><br>val_datagen = ImageDataGenerator(rescale=1./255)<br><br>test_datagen = ImageDataGenerator(rescale=1./255)</pre><p>In the above code, we’re applying various transformations like rotation, shifting, shearing, zooming, and horizontal flipping to the training data. For validation and test data, we only rescale the images.</p><h4>Step 4: Flow Data From Directories.</h4><p>Now, you’ll use the flow_from_directory method to load the images from the directories and apply the transformations specified by the data generators.</p><pre>train_generator = train_datagen.flow_from_directory(<br>    &#39;dataset/train&#39;,<br>    target_size=(150, 150),<br>    batch_size=32,<br>    class_mode=&#39;binary&#39;<br>)<br><br>val_generator = val_datagen.flow_from_directory(<br>    &#39;dataset/validation&#39;,<br>    target_size=(150, 150),<br>    batch_size=32,<br>    class_mode=&#39;binary&#39;<br>)<br><br>test_generator = test_datagen.flow_from_directory(<br>    &#39;dataset/test&#39;,<br>    target_size=(150, 150),<br>    batch_size=32,<br>    class_mode=&#39;binary&#39;<br>)</pre><p>Ensure that target_size matches the input size expected by your CNN model.</p><h4>Step 5: Train Your CNN Model.</h4><p>With the data generators in place, you can now use them to train your CNN model.</p><pre>model.fit(<br>    train_generator,<br>    epochs=10,<br>    validation_data=val_generator,<br>    verbose=1<br>)</pre><h4>Step 6: Evaluate Your Model.</h4><p>Finally, you can evaluate your model on the test set.</p><pre>test_loss, test_accuracy = model.evaluate(test_generator)<br>print(f&#39;Test accuracy: {test_accuracy}&#39;)</pre><p>By following these steps, you’ve successfully passed image datasets to a CNN model using image data generation using flow from directory. This process not only helps in efficient data handling but also enhances the model’s performance through data augmentation.</p><h4>(2) Flow_from_dataframe:</h4><p>The <strong><em>flow_from_dataframe</em>() </strong>method takes the Pandas DataFrame and the path to a directory and generates batches of augmented/normalized data.The downloaded dataset contains .csv file. we will use this .csv file with <strong><em>flow_from_dataframe() </em></strong>function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dLmjJ_YW0gwIo42e.png" /></figure><h3>Steps for Image generation using flow from dataframe.</h3><h4>Step 1: Import the Libraries</h4><pre>import pandas as pd<br>import tensorflow as tf<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>from tensorflow.keras.preprocessing.image import img_to_array, load_img</pre><h4>Step 2: Load and Process the DataFrame</h4><p>Assuming your DataFrame has two columns: ‘filename’ (containing the file paths of the images) and ‘class’ (containing the corresponding class labels), you can load and process</p><pre>df = pd.read_csv(&#39;image_data.csv&#39;)  # Load your DataFrame<br><br># Process file paths and labels<br>df[&#39;filename&#39;] = &#39;path_to_images/&#39; + df[&#39;filename&#39;]  # Adjust the path to your images<br>df[&#39;class&#39;] = df[&#39;class&#39;].astype(str)  # Make sure &#39;class&#39; is in string format</pre><h4>Step 3: Create an Image Data Generator.</h4><p>Create an instance of ImageDataGenerator with the desired data augmentation settings:</p><pre>datagen = ImageDataGenerator(<br>    rescale=1./255,<br>    rotation_range=40,<br>    width_shift_range=0.2,<br>    height_shift_range=0.2,<br>    shear_range=0.2,<br>    zoom_range=0.2,<br>    horizontal_flip=True,<br>    fill_mode=&#39;nearest&#39;<br>)</pre><h4>Step 4: Flow Data from DataFrame</h4><p>Use the flow_from_dataframe method to load images from the DataFrame:</p><pre>generator = datagen.flow_from_dataframe(<br>    df,<br>    x_col=&#39;filename&#39;,<br>    y_col=&#39;class&#39;,<br>    target_size=(150, 150),  # Adjust to match your model&#39;s input size<br>    batch_size=32,<br>    class_mode=&#39;categorical&#39;,  # Change to &#39;binary&#39; if you have binary classes<br>    shuffle=True<br>)</pre><h4>Step 5: Train Your CNN Model</h4><p>Now, you can use the generator to train your CNN model:</p><pre>model.fit(<br>    generator,<br>    epochs=10,<br>    verbose=1<br>)</pre><h3>Step 6: Evaluate Your Model</h3><p>Finally, evaluate your model</p><pre>test_loss, test_accuracy = model.evaluate(generator)<br>print(f&#39;Test accuracy: {test_accuracy}&#39;)</pre><p>By following these steps, you’ve successfully passed image datasets to a CNN model using image data generation flow from dataframe. This process not only helps in efficient data handling but also enhances the model’s performance through data augmentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d9497c7a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Model Architectures in TensorFlow: A Comprehensive Guide]]></title>
            <link>https://msalamiitd.medium.com/demystifying-model-architectures-in-tensorflow-a-comprehensive-guide-60393d8fa684?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/60393d8fa684</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 18:01:50 GMT</pubDate>
            <atom:updated>2023-11-01T18:05:25.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Model Building in TensorFlow: Sequential vs. Functional vs. Subclassing</h3><p>“Artificial intelligence is the new electricity.” — Andrew Ng</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*bzcC30ctaLeKkoWI.png" /></figure><h4>Introduction:</h4><p>In the world of deep learning, choosing the right architecture for your neural network is crucial for achieving optimal performance. TensorFlow, one of the most popular deep learning libraries, provides several ways to build models, each with its own strengths and use cases. In this blog post, we’ll explore three main approaches: Sequential API, Functional API, and Model Subclassing.</p><h3>1. Sequential API</h3><p>The Sequential API is the simplest and most straightforward way to build neural networks in TensorFlow. It allows you to create models layer by layer, where each layer is added in sequence.</p><h4>Advantages of Sequential API:</h4><ul><li>Simplicity: Ideal for building simple, feedforward networks where layers are stacked sequentially.</li><li>Ease of Use: Intuitive and easy to understand, making it great for beginners.</li><li>Quick Prototyping: Fast prototyping for basic models.</li></ul><h4>Disadvantages of Sequential API:</h4><h4>a. Limited Flexibility:</h4><ul><li>The Sequential API is designed for building straightforward, feedforward architectures. It may not be suitable for more complex models with branching or multiple inputs and outputs.</li></ul><h4>b. Lack of Explicit Data Flow:</h4><ul><li>In a Sequential model, it’s not as explicit how the data flows between layers. This can be a drawback when building models with intricate architectures.</li></ul><h4>c. Inability to Share Layers:</h4><ul><li>It doesn’t easily support the sharing of layers between different parts of the network, which can be important for certain types of models.</li></ul><h4>Sample Code:</h4><pre>import tensorflow as tf<br>from tensorflow.keras import Sequential<br>from tensorflow.keras.layers import Dense<br><br>model = Sequential([<br>    Dense(64, activation=&#39;relu&#39;, input_shape=(input_shape,)),<br>    Dense(32, activation=&#39;relu&#39;),<br>    Dense(10, activation=&#39;softmax&#39;)<br>])</pre><h3>2. Functional API</h3><p>The Functional API in TensorFlow offers more flexibility than the Sequential API. It allows you to build complex models with multiple inputs, multiple outputs, and shared layers.</p><h4>Advantages of Functional API:</h4><ul><li>Flexibility: Suitable for building models with non-sequential architectures, such as multi-input and multi-output networks.</li><li>Reusability: Enables sharing of layers and reusing parts of a model in different configurations.</li><li>Explicit Data Flow: Provides a clear and explicit way to define the flow of data through the model.</li></ul><h4>Disadvantages of Functional API:</h4><h4>a. Steep Learning Curve:</h4><ul><li>Compared to the Sequential API, the Functional API has a steeper learning curve. It requires a deeper understanding of TensorFlow and the underlying computation graph.</li></ul><h4>b. More Complex to Implement:</h4><ul><li>Building models with multiple inputs, multiple outputs, or shared layers can be more challenging and verbose in the Functional API.</li></ul><h4>c. Less Intuitive for Simple Models:</h4><ul><li>For very simple models, the Functional API may introduce unnecessary complexity. In such cases, the Sequential API might be more appropriate.</li></ul><h4>Sample Code:</h4><pre>import tensorflow as tf<br>from tensorflow.keras import Model<br>from tensorflow.keras.layers import Input, Dense<br><br>input_layer = Input(shape=(input_shape,))<br>hidden_layer_1 = Dense(64, activation=&#39;relu&#39;)(input_layer)<br>hidden_layer_2 = Dense(32, activation=&#39;relu&#39;)(hidden_layer_1)<br>output_layer = Dense(10, activation=&#39;softmax&#39;)(hidden_layer_2)<br><br>model = Model(inputs=input_layer, outputs=output_layer)</pre><h3>3. Model Subclassing</h3><p>Model Subclassing is the most customizable approach to building models in TensorFlow. Instead of using a pre-defined API, you create a custom class that inherits from tf.keras.Model and define the forward pass in the call method.</p><h4>Advantages of Model Subclassing:</h4><ul><li>Ultimate Flexibility: Allows for complete customization of the model architecture and training loop.</li><li>Dynamic Behavior: Enables dynamic architecture changes based on conditions or inputs.</li><li>Complex Architectures: Suitable for building highly specialized or research-oriented models.</li></ul><h4>Disadvantages of Model Subclassing:</h4><h4>a. Potential for Error-Prone Code:</h4><ul><li>Model Subclassing involves writing custom Python code for the model architecture. This can be error-prone, especially for those new to TensorFlow.</li></ul><h4>b. Less Transparent Graph Representation:</h4><ul><li>The dynamic nature of Model Subclassing makes it harder to inspect the model’s architecture, as it’s not as easily represented in a static graph.</li></ul><h4>c. Harder Debugging:</h4><ul><li>Debugging models built with Model Subclassing can be more challenging compared to the other APIs due to the custom code involved.</li></ul><h4>d. Limited Serialization:</h4><ul><li>Saving and loading models built using Model Subclassing requires extra care. It’s not as straightforward as with the Sequential or Functional APIs.</li></ul><h4>Sample Code:</h4><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Dense<br><br>class CustomModel(tf.keras.Model):<br>    def __init__(self, num_classes):<br>        super(CustomModel, self).__init__()<br>        self.dense1 = Dense(64, activation=&#39;relu&#39;)<br>        self.dense2 = Dense(32, activation=&#39;relu&#39;)<br>        self.dense3 = Dense(num_classes, activation=&#39;softmax&#39;)<br><br>    def call(self, inputs):<br>        x = self.dense1(inputs)<br>        x = self.dense2(x)<br>        return self.dense3(x)<br><br>model = CustomModel(num_classes=10)</pre><h3>Conclusion</h3><p>Choosing the right model architecture in TensorFlow depends on the complexity of your problem, the structure of your data, and the level of customization you require. The Sequential API, Functional API, and Model Subclassing each offer their own unique benefits, allowing you to select the approach that best suits your specific needs.</p><p>Experimenting with these different approaches will not only enhance your understanding of deep learning but also empower you to build more powerful and efficient models for a wide range of applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60393d8fa684" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Cultural Shifts in a Globalized World.]]></title>
            <link>https://msalamiitd.medium.com/exploring-cultural-shifts-in-a-globalized-world-738ae495e29c?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/738ae495e29c</guid>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[globalization]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 17:00:55 GMT</pubDate>
            <atom:updated>2023-11-01T17:00:55.906Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this interconnected world, understanding and respecting diverse cultures is not just an option, it’s a necessity</blockquote><p><em>India is a vast and diverse country where every 100km to 200km radius has its own unique languages, traditions, and religions. India’s diverse population has created a rich and vibrant culture that is celebrated around the world. If you want to explore this diversity, please visit India.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*-rP8DYKhfF-oq6zX.png" /></figure><p>In an era characterized by unprecedented connectivity, cultural shifts have become a defining feature of our global landscape. The interactions between societies, once limited by geographic boundaries, now transcend borders and span continents. This phenomenon, often referred to as globalization, has given rise to a rich tapestry of cultural exchange, adaptation, and transformation. In this blog, we embark on a journey to explore these shifts, seeking to understand the forces that shape our world and the individuals who navigate its complexities.</p><h4>The Dynamics of Globalization</h4><p>Globalization, in its essence, is the interconnectedness of economies, societies, and cultures on a global scale. It is a multidimensional force that encompasses economic, technological, political, and cultural aspects. Through the lens of cultural shifts, we witness the profound impact of globalization on the way we live, communicate, and relate to one another.</p><h4>Technology as catalyst.</h4><p>In digital era, technology play a vital role for cultural exchange. social medial platforms(like Instagram, fb, youtube…..). Due to this people exploring different country for vaccation, higher study, jobs.</p><h4>Language and Communication</h4><p>Language, a cornerstone of culture, stands at the forefront of this transformation. The prevalence of English as a global lingua franca is emblematic of the evolving linguistic landscape. This shift is not without its challenges, as local languages grapple with the pressures of assimilation or preservation.</p><h4>Cultural Homogenization vs. Diversity</h4><p>One of the most intriguing aspects of cultural shifts is the tension between homogenization and diversity. On one hand, we witness the convergence of certain cultural elements, driven by shared experiences and global trends. On the other, there is an enduring commitment to preserving unique cultural identities, each a vital thread in the global fabric.</p><h4>Migration and Identity</h4><p>As people move across borders, they bring with them their cultural heritage, contributing to the vibrant mosaic of global cultures. This dynamic process of migration reshapes identities, prompting individuals to navigate the delicate balance between preservation of their roots and integration into their adopted homes.</p><h4>The Role of Policy and Governance</h4><p>Governments and international organizations play a pivotal role in shaping cultural shifts. Policies regarding immigration, education, and cultural preservation can either facilitate or hinder the process. Striking the right balance requires a nuanced understanding of the complexities involved.</p><h4>Conclusions</h4><p>As we navigate the ever-evolving landscape of cultural shifts, it is imperative that we approach this phenomenon with open hearts and open minds. Embracing diversity, respecting cultural nuances, and fostering meaningful dialogue are essential steps toward building a more inclusive and harmonious global society. Together, we can celebrate the richness of our global heritage while forging a future that honors both our shared humanity and our unique cultural expressions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738ae495e29c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Sequence-to-Sequence Learning in Machine Translation]]></title>
            <link>https://msalamiitd.medium.com/demystifying-sequence-to-sequence-learning-in-machine-translation-821b61595c8f?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/821b61595c8f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-translation]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 12:15:03 GMT</pubDate>
            <atom:updated>2023-11-01T12:15:03.178Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>“If you talk to a man in a language he understands, that goes to his head. If you talk to him in his own language, that goes to his heart.” — Nelson Mandela</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*xJey9U6PO5uyheT6.jpeg" /></figure><p>Machine Translation (MT) using sequence-to-sequence (seq2seq) learning is a technique in artificial intelligence and natural language processing (NLP) that aims to automatically translate text from one language to another. It’s particularly powerful because it can handle variable-length input and output sequences.</p><h4>Applications of sequence to sequence problems:</h4><ul><li>Machine Translation — An artificial system which translates a sentence from one language to the other.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mSbhHHH3HT5lQxPS.png" /></figure><ul><li>Image Captioning — Automatically creating the descriptions of an image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*fuacX06LtLSh3qo8.png" /></figure><ul><li>Video Captioning — Automatically creating the subtitles of a video for each frame</li><li>Text Summarization — Condensing a piece of text to a shorter version, reducing the size of the initial text while at the same time preserving key informational elements and the meaning of content.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*qeWJx_TI0Uv43bK7.png" /></figure><ul><li>Question Answering — Generating a natural language answer given a natural language question</li><li>Conversational Modeling — Simulating a conversation (or a chat) with a user in natural language through messaging applications, websites, mobile apps or through the telephone.</li><li>Speech Recognition — Converting a speech to text.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*dkkQ6rajh5hkwMJp.png" /></figure><h4>Prerequisites:</h4><ul><li>Numpy, pandas.</li><li>Tensorflow, keras</li><li>Basic idea of NLP,</li><li>RNN(many to one, one to one, many to many),</li></ul><h3>Table of content:</h3><ol><li>Problem Statement.</li><li>Source of Data/Data Extraction.</li><li>Evaluation metrics.</li><li>Exploratory Data Analysis(EDA).</li><li>Data Pre-processing.</li><li>Machine learning model.</li><li>Inference/Deployment.</li><li>Future Work and Improvements.</li><li>References.</li></ol><h3>1. Problem Statement:</h3><p>The goal of this project is to develop an effective language translation system that can seamlessly convert text from one language (Source Language) to another (Target Language). Specifically, we are focusing on translating from Language L1 (e.g., German) to Language L2 (e.g., English) using a sequence-to-sequence learning approach.</p><h3>2. Source of Data/Data Extraction.</h3><p>The Data is provided by <a href="https://data.europa.eu/data/datasets/elrc_41?locale=en">link</a>, which comes in one file: The training file has around 2 lakhs records, The files are in the .csv format and are 35 MB. We break data into a 70:30 ratio for training and testing.</p><h3>3. Evaluation metrics.</h3><p>The success of our translation model heavily depends on the quality and diversity of the training data. We will utilize large parallel corpora of texts in both L1(German) and L2(English). Evaluation will be performed using established metrics like BLEU score and METEOR, supplemented by human assessments to ensure meaningful and accurate translations.</p><h3>4. Exploratory Data Analysis(EDA).</h3><h4>4.1 World Cloud of english and german sentences.</h4><figure><img alt="wordcloud" src="https://cdn-images-1.medium.com/max/1024/1*StuokIYQgyM2mf-kLoDmVQ.png" /><figcaption>wordcloud</figcaption></figure><ul><li>There are so many common words between english and german like: Tom, Maria.</li><li>In English sentence “Know, go, think, going, need, e.t.c” are very common words.</li><li>In German sentence “Ich, habe, Hast, werde, Das, e.t.c” are very common words.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdsaaP0W2P4vlDdQjES6Rw.png" /></figure><ul><li>Most of the sentance contains words less than 100, drop the sentance which contains more than 100 words.</li></ul><h4>4.3 Density plot of sentence for german(input) and english(output)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Dgsf6kdGLnADYCv8AykVw.png" /></figure><ul><li>Most of the sentance contain words between 20 and 40.</li></ul><h3>5. Data Pre-processing.</h3><p>We will do the following data pre-processing steps on the data.</p><h4>① Pre_process text data.</h4><p>The following steps were done for pre-processing the text both english and german.</p><ul><li>Remove emoji sign.</li><li>De-contract the text. For example, can’t -&gt; can not; I’m -&gt; I am; I’ll -&gt; I will</li><li>Remove punctuations and extra spaces</li><li>Remove stop words for item_description.</li></ul><pre>def decontractions(phrase):<br>    &quot;&quot;&quot;decontracted takes text and convert contractions into natural form.<br>     ref: https://stackoverflow.com/questions/19790188/expanding-english-language-contractions-in-python/47091490#47091490&quot;&quot;&quot;<br>    # specific<br>    phrase = re.sub(r&quot;won\&#39;t&quot;, &quot;will not&quot;, phrase)<br>    phrase = re.sub(r&quot;can\&#39;t&quot;, &quot;can not&quot;, phrase)<br>    phrase = re.sub(r&quot;won\’t&quot;, &quot;will not&quot;, phrase)<br>    phrase = re.sub(r&quot;can\’t&quot;, &quot;can not&quot;, phrase)<br><br>    # general<br>    phrase = re.sub(r&quot;n\&#39;t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;re&quot;, &quot; are&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;s&quot;, &quot; is&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;d&quot;, &quot; would&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;ll&quot;, &quot; will&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;ve&quot;, &quot; have&quot;, phrase)<br>    phrase = re.sub(r&quot;\&#39;m&quot;, &quot; am&quot;, phrase)<br><br>    phrase = re.sub(r&quot;n\’t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\’re&quot;, &quot; are&quot;, phrase)<br>    phrase = re.sub(r&quot;\’s&quot;, &quot; is&quot;, phrase)<br>    phrase = re.sub(r&quot;\’d&quot;, &quot; would&quot;, phrase)<br>    phrase = re.sub(r&quot;\’ll&quot;, &quot; will&quot;, phrase)<br>    phrase = re.sub(r&quot;\’t&quot;, &quot; not&quot;, phrase)<br>    phrase = re.sub(r&quot;\’ve&quot;, &quot; have&quot;, phrase)<br>    phrase = re.sub(r&quot;\’m&quot;, &quot; am&quot;, phrase)<br><br>    return phrase<br><br>def preprocess(text):<br>    # convert all the text into lower letters<br>    # use this function to remove the contractions: https://gist.github.com/anandborad/d410a49a493b56dace4f814ab5325bbd<br>    # remove all the spacial characters: except space &#39; &#39;<br>    text = text.lower()<br>    text = decontractions(text)<br>    text = re.sub(&#39;[^A-Za-z0-9 ]+&#39;, &#39;&#39;, text)<br>    return text<br><br>def preprocess_gem(text):<br>    # convert all the text into lower letters<br>    # remove the words betweent brakets ()<br>    # remove these characters: {&#39;$&#39;, &#39;)&#39;, &#39;?&#39;, &#39;&quot;&#39;, &#39;’&#39;, &#39;.&#39;,  &#39;°&#39;, &#39;!&#39;, &#39;;&#39;, &#39;/&#39;, &quot;&#39;&quot;, &#39;€&#39;, &#39;%&#39;, &#39;:&#39;, &#39;,&#39;, &#39;(&#39;}<br>    # replace these spl characters with space: &#39;\u200b&#39;, &#39;\xa0&#39;, &#39;-&#39;, &#39;/&#39;<br>    # we have found these characters after observing the data points, feel free to explore more and see if you can do find more<br>    # you are free to do more proprocessing<br>    # note that the model will learn better with better preprocessed data<br><br>    text = text.lower()<br>    text = decontractions(text)<br>    text = re.sub(&#39;[$)\?&quot;’.°!;\&#39;€%:,(/]&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;\u200b&#39;, &#39; &#39;, text)<br>    text = re.sub(&#39;\xa0&#39;, &#39; &#39;, text)<br>    text = re.sub(&#39;-&#39;, &#39; &#39;, text)<br>    return text<br><br><br>data[&#39;english&#39;] = data[&#39;english&#39;].apply(preprocess)<br>data[&#39;german&#39;] = data[&#39;german&#39;].apply(preprocess_gem)<br>data.head()</pre><p>➁ Most of the sentance contain less than 100 words, remove the sentence which contains more than 100 words for both english and german.</p><pre>data = data[data[&#39;ger_len&#39;] &lt; 100]<br>data = data[data[&#39;eng_len&#39;] &lt; 100]</pre><p>③ Add &lt;start&gt; and &lt;end&gt; token, to start and stop the prediction for inference.</p><pre>data[&#39;english_inp&#39;] = &#39;&lt;start&gt; &#39; + data[&#39;english&#39;].astype(str)<br>data[&#39;english_out&#39;] = data[&#39;english&#39;].astype(str) + &#39; &lt;end&gt;&#39;<br><br>data[&#39;english&#39;] = &#39;&lt;start&gt; &#39; + data[&#39;english&#39;] + &#39; &lt;end&gt;&#39;</pre><h3>6. Machine Learning Model.</h3><h4>a. Teacher Forcing(Encoder Decoder).</h4><p>The Seq2Seq framework relies on the <strong>encoder-decoder</strong> paradigm. The <strong>encoder</strong> <em>encodes</em> the input sequence, while the <strong>decoder</strong> <em>produces</em> the target sequence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41q2v9THHsx67rP3.jpeg" /></figure><h4>Encoder:</h4><p>Our input sequence is how are you. Each word from the input sequence is associated to a vector w∈R^d (via a lookup table). In our case, we have 3 words, thus our input will be transformed into [w0,w1,w2]∈R^{d×3}. Then, we simply run an LSTM over this sequence of vectors and store the last hidden state outputed by the LSTM: this will be our encoder representation e. Let’s write the hidden states [e0,e1,e2] (and thus e=e2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*V0CgY46LzA7HNOxg.png" /></figure><pre>class Encoder(tf.keras.layers.Layer):<br>    def __init__(self, inp_vocab_size, embedding_dim, input_length, enc_units):<br>        super().__init__()<br>        self.vocab_size = inp_vocab_size<br>        self.embedding_dim = embedding_dim<br>        self.enc_units = enc_units<br>        self.input_length = input_length<br><br>        self.embedding = Embedding(input_dim=self.vocab_size, output_dim=self.embedding_dim, input_length=self.input_length,<br>                           mask_zero=True, name=&quot;embedding_layer_encoder&quot;)<br>        self.lstm = LSTM(self.enc_units, return_state=True, name=&quot;Encoder_LSTM&quot;)<br><br>    def call(self,input_sequence,states):<br>        &#39;&#39;&#39;<br>          This function takes a sequence input and the initial states of the encoder.<br>          Pass the input_sequence input to the Embedding layer, Pass the embedding layer ouput to encoder_lstm<br>          returns -- encoder_output, last time step&#39;s hidden and cell state<br>        &#39;&#39;&#39;<br>        X=self.embedding(input_sequence)<br>        output,state_h,state_c=self.lstm(X,initial_state=states)<br>        return output,state_h,state_c<br><br>    def initialize_states(self,batch_size):<br>        &#39;&#39;&#39;<br>         Given a batch size it will return intial hidden state and intial cell state.<br>         If batch size is 32- Hidden state is zeros of size [32,lstm_units], cell state zeros is of size [32,lstm_units]<br>         &#39;&#39;&#39;<br>        state_h=tf.zeros((batch_size,self.enc_units))<br>        state_c=tf.zeros((batch_size,self.enc_units))<br>        return [state_h,state_c]</pre><p>For encoder</p><ul><li>return_sequences=False</li><li>return_state=True</li></ul><h4>Decoder:</h4><p>we have a vector e that captures the meaning of the input sequence, we’ll use it to generate the target sequence word by word. Feed to another LSTM cell: e as hidden state and a special start of sentence vector wsos as input. The LSTM computes the next hidden state h_0∈R^h . Then, we apply some function g:R^h↦R^V so that s_0:=g(h_0)∈R^V is a vector of the same size as the vocabulary.</p><ul><li>h_0=LSTM(e,w_sos)</li><li>s_0=g(h_0)</li><li>p_0=softmax(s_0)</li><li>i_0=argmax(p_0)</li></ul><p>Then, apply a softmax to s_0 to normalize it into a vector of probabilities p_0∈R^V . Now, each entry of p_0 will measure how likely is each word in the vocabulary. Let’s say that the word “comment” has the highest probability (and thus i_0=argmax(p_0) corresponds to the index of “comment”). Get a corresponding vector w_{i_0}=w_comment and repeat the procedure: the LSTM will take h_0 as hidden state and w_comment as input and will output a probability vector p_1 over the second word, etc.</p><ul><li>h_1=LSTM(h_0,w_{i_0})</li><li>s_1=g(h_1)</li><li>p_1=softmax(s_1)</li><li>i_1=argmax(p_1)</li></ul><p>The decoding stops when the predicted word is a special end of sentence token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*VHPzCgC-qmBDuGp7.png" /></figure><blockquote><em>Intuitively, the hidden vector represents the “amount of meaning” that has not been decoded yet.</em></blockquote><p>The above method aims at modelling the distribution of the next word conditionned on the beginning of the sentence</p><ul><li>P[y_{t+1}|y_1,…,y_t,x_0,…,x_n]</li></ul><p>by writing</p><ul><li>P[y_{t+1}|y_t,h_t,e]</li></ul><pre>class Decoder(tf.keras.layers.Layer):<br>    def __init__(self, out_vocab_size, embedding_dim, input_length, dec_units):<br>        super().__init__()<br>        self.vocab_size = out_vocab_size<br>        self.embedding_dim = 300<br>        self.dec_units = dec_units<br>        self.input_length = input_length<br>        # we are using embedding_matrix and not training the embedding layer<br>        self.embedding = Embedding(input_dim=self.vocab_size, output_dim=self.embedding_dim, input_length=self.input_length,<br>                           mask_zero=True, name=&quot;embedding_layer_decoder&quot;)<br>        self.lstm = LSTM(self.dec_units, return_sequences=True, return_state=True, name=&quot;Encoder_LSTM&quot;)<br><br>    def call(self,input_sequence,initial_states):<br>        &#39;&#39;&#39;<br>          This function takes a sequence input and the initial states of the encoder.<br>          Pass the input_sequence input to the Embedding layer, Pass the embedding layer ouput to decoder_lstm<br><br>          returns -- decoder_output,decoder_final_state_h,decoder_final_state_c&#39;&#39;&#39;<br><br>        #output,state_h,state_c =self.encoder(input_sequence,initial_states)<br>        target_embedd= self.embedding(input_sequence)<br>        output,state_h,state_c= self.lstm(target_embedd, initial_state=initial_states)<br>        return output,state_h,state_c</pre><p>For Decoder</p><ul><li>return_sequences=True</li><li>return_state=True</li></ul><blockquote>Achieve Accuracy approx 80% on train data and test_data for 100 epochs of training. If we increase number of epochs most probably accuracy is increases.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqwrCvVrmf-HAeJ7HK4coA.png" /></figure><blockquote>Taking random sample of 1000 datapoints and calulate <strong>Average Bleuscore</strong> get:<strong> 1.467853429074125e-231</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hn2Tz129SEnbVeUIqCUF5Q.png" /><figcaption>sample of results</figcaption></figure><h4>Overview of Seq to Seq Model for Language Translation</h4><ul><li>In our language translation project, we have employed an encoder-decoder architecture for the task of translating from Language L1 (German) to Language L2 (English).</li></ul><h4>Encoder Role</h4><ul><li>The words from Language L1 serve as inputs to the Encoder. The Encoder processes these inputs to create meaningful representations.</li></ul><h4>Decoder Role</h4><ul><li>Simultaneously, the words from Language L2 act as inputs to the Decoder. The Decoder uses these inputs to generate the translated output.</li></ul><h4>Initializing Decoder States</h4><ul><li>To initiate the Decoder, we utilize the final states of the Encoder. These states play a crucial role in setting the starting conditions for the Decoder.</li></ul><h4>Limitations</h4><ul><li>One potential limitation of this approach is that the entire translation process is heavily reliant on the last state vectors. This can result in suboptimal performance when translating longer sequences.</li></ul><h4>Mitigating Length Dependency</h4><ul><li>In seq-to-seq models, we can adopt an alternative strategy by performing operations like average-pooling or max-pooling on all the hidden states of the encoder. This aggregated information is then forwarded as inputs to the decoder. This approach can enhance the model’s ability to handle longer sequences.</li></ul><h4>Future Considerations: Attention Mechanism</h4><ul><li>In our upcoming blog, we will delve into the concept of attention mechanisms, a crucial advancement in improving the performance of seq-to-seq models.</li></ul><h3>7. Inference/Deployment.</h3><p>On process.</p><h3>8. Future Work and Improvements.</h3><ul><li>Use Attention mechanism with Encoder decoder technique.</li></ul><h3>9. References.</h3><ul><li><a href="https://www.kaggle.com/code/kmkarakaya/part-a-introduction-to-seq2seq-learning/notebook">https://www.kaggle.com/code/kmkarakaya/part-a-introduction-to-seq2seq-learning/notebook</a></li><li><a href="https://medium.com/analytics-vidhya/neural-machine-translation-and-the-need-for-attention-mechanism-60f9a39da9a">https://medium.com/analytics-vidhya/neural-machine-translation-and-the-need-for-attention-mechanism-60f9a39da9a</a></li><li><a href="https://medium.com/analytics-vidhya/encoders-decoders-sequence-to-sequence-architecture-5644efbb3392">https://medium.com/analytics-vidhya/encoders-decoders-sequence-to-sequence-architecture-5644efbb3392</a></li><li><a href="https://data.europa.eu/data/datasets/elrc_41?locale=en">https://data.europa.eu/data/datasets/elrc_41?locale=en</a></li><li><a href="https://medium.com/hackernoon/implementing-a-sequence-to-sequence-model-45a6133958ca">https://medium.com/hackernoon/implementing-a-sequence-to-sequence-model-45a6133958ca</a></li><li><a href="https://www.analyticsvidhya.com/blog/2020/08/a-simple-introduction-to-sequence-to-sequence-models/">https://www.analyticsvidhya.com/blog/2020/08/a-simple-introduction-to-sequence-to-sequence-models/</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ip7oMaG6d-icqUh.png" /></figure><h4>LinkedIn profile</h4><p><a href="https://www.linkedin.com/in/md-shahbaz-alam-0395a6184/">https://www.linkedin.com/in/md-shahbaz-alam-0395a6184/</a></p><h4>Github Link</h4><p><a href="https://github.com/M-S-ALAM">M-S-ALAM - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821b61595c8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Journey in South India]]></title>
            <link>https://msalamiitd.medium.com/my-first-journey-in-south-india-3bd6f12ac9f9?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd6f12ac9f9</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 13:24:47 GMT</pubDate>
            <atom:updated>2023-10-31T13:24:47.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*9EqXBW6WhQslmkjD.jpg" /><figcaption>South Indian food</figcaption></figure><p>Upon my initial arrival in South India, I encountered various preconceived notions originating from my North Indian background. These included prevailing beliefs about the exclusive consumption of spicy cuisine and perceived language barriers. It was believed that while South Indian residents possessed a grasp of Hindi, they often feigned ignorance. However, my professional undertaking in this region offered me a fresh perspective. I found the people of South India to be exceptionally courteous and accommodating. Contrary to expectations, a significant portion of the populace did not comprehend Hindi fluently, and the cuisine was not uniformly fiery.</p><p>I developed a profound appreciation for South India, particularly for its picturesque locales such as the beaches of Chennai, Puducherry, and Mahabalipuram. Additionally, I explored numerous other destinations including Bangalore, Kerala, Puducherry, and Rameshwaram. What struck me most was the simplicity in which a majority of the population lived, coupled with a deep-rooted religiosity, often expressed through a preference for vegetarianism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*wDh5R_EEohXCRXDptWcWhw.png" /></figure><p>The cultural diversity within South India is truly captivating. Each state boasts its unique traditions, art forms, and festivals. For instance, Karnataka’s rich heritage is exemplified by its classical dance forms like Bharatanatyam and Kuchipudi, while Kerala is celebrated for its mesmerizing Kathakali performances. Tamil Nadu’s ancient temples, with their intricate architecture and spiritual aura, offer a glimpse into the region’s profound historical legacy.</p><p>Moreover, the natural beauty of South India is nothing short of awe-inspiring. The Western Ghats, a UNESCO World Heritage site, spans across several states in the region, showcasing an extraordinary biodiversity. The lush greenery, mist-covered peaks, and cascading waterfalls paint a picturesque landscape that leaves a lasting impression on visitors.</p><p>South Indian cuisine, contrary to popular belief, is a symphony of flavors and textures, not solely reliant on spice. From the delectable dosas and idlis of Tamil Nadu to the aromatic biryanis of Hyderabad, the culinary offerings are a testament to the region’s culinary prowess. The emphasis on using fresh, locally sourced ingredients adds a distinct charm to every dish.</p><p>The warmth and hospitality of the people in South India are unparalleled. The genuine interest in sharing their culture and traditions with outsiders fosters a sense of belonging, making any visitor feel welcomed and cherished. This hospitality extends beyond personal interactions and is reflected in the overall atmosphere of the region.</p><p>In conclusion, my experience in South India has been a revelation, dispelling stereotypes and revealing a region of immense cultural richness, natural beauty, and warm-hearted people. It has left an indelible mark on my understanding of India as a whole, and I eagerly anticipate further exploration of this diverse and enchanting part of the country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_BHF_4W98xRgDcvVUjqnw.jpeg" /><figcaption>Chennai beach</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd6f12ac9f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Retail Product Self-checkout System-(to cut the queue).]]></title>
            <link>https://msalamiitd.medium.com/a-retail-product-self-checkout-system-to-cut-the-queue-31e38e457dc3?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/31e38e457dc3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[self-checkout-system]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[detectron2]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 11:12:48 GMT</pubDate>
            <atom:updated>2024-06-15T12:25:22.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retail Product Self Checkout System-(to cut the queue).</h3><p>“Where there is data smoke, there is business fire”. — By Thomas Redman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adKKlqn4a4Z8gyUbKcUBqQ.png" /></figure><h3><strong>Introduction:</strong></h3><p>The aim of this project is to develop a comprehensive retail product identification system to enhance the shopping experience for customers. By utilising this system, customers can grab their desired items and proceed with checkout without the need for bar-codes scanning or lengthy wait times only put all the object in table it automatically generate the bill. The system will provide cashier-less stores with an efficient checkout process through automatic product recognition, eliminating the need for bar code scanning and reducing wait times.Additionally, this system will support self-checkout stores in detecting potential fraudulent behaviour, such as the use of false bar codes to manipulate product prices. The implementation of this system will help to maintain the integrity of self-checkout transactions.</p><h4>Table of contents:</h4><ol><li>Business problem.</li><li>Source of Data/Data Extraction.</li><li>Evaluation metrics.</li><li>Mapping the real-world problem.</li><li>Exploratory Data Analysis(EDA).</li><li>Data Engineering.</li><li>Deep Learning Models.</li><li>Deployment.</li><li>Future Work and Improvements.</li><li>References.</li></ol><h3><strong>1. Business Problem:</strong></h3><p>The most essential and difficult aspect of the Data Science journey is comprehending the stated problem statement. We want us to create an algorithm that would automatically give the given shopping list and price, based on images taken by camera with different angles.</p><h4>1.1 Problem Statement:</h4><p>The retail industry sector demands a significant quantity of human labour, with product recognition accounting for a sizable portion of the task. Utilizing image recognition technology to automate product recognition is becoming more and more challenging with the current advancements in computer vision.The automatic checkout (ACO) application scenario, which aims to produce the shopping list from the automatic checkout (ACO) application scenario, serves as the trend’s core user-case. A complete shopping list with the entire price is returned when a consumer places their purchased items on the checkout counter. The system will recognize each item automatically.</p><h4>1.2 <strong>Business Objective &amp; Constraints:</strong></h4><ul><li>The goal is to fix the problem. When a customer puts his/her products on the checkout counter.</li><li>Negligible amount of errors(loss is very high).</li><li>There are latency limitations.</li></ul><h4>1.3 Observation:</h4><ul><li>If any new product is added into SKUs then we have to train the whole model based on old datasets + new datasets.</li><li>In this problem we can’t apply data augmentation.</li></ul><h3>2. <strong>Source of Data/Data Extraction:</strong></h3><p>The file <a href="https://www.kaggle.com/datasets/diyer22/retail-product-checkout-dataset">dataset</a> provided by Kaggle, which comes in six files approx 30GB. Train images, train.json, test images, test.json, validation images and validation.json. Where json files take annotations of images. In this dataset there are 200 retail SKUs(Stock keeping units). The collected SKUs can be divided into 17 meta-categories, i.e., puffed food, dried fruit, instant drink, instant noodles, dessert, drink, alcohol, milk, canned food, chocolate, gum, candy, seasoner, personal hygiene, tissue, stationery.</p><h3>3. Evaluation metrics:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*TTBF42pyTn6IBdVYh4oa5A.png" /></figure><p><strong><em>3.1 Checkout Accuracy(cAcc):-</em></strong></p><p>If the complete product list is accurately predicted, i.e., CDi = 0. Mathematically, this metric can be written as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*wcxZgL75kBXICvxH" /></figure><p>where δ(·) returns 1 if and only if sum(CDi,k) = 0; otherwise, it returns 0. The range of the cAcc score is [0, 1].</p><ul><li>Higher is better.</li></ul><pre>def cAcc(pred_values, label_values, N):<br>    return np.sum(np.all(np.equal(label_values, pred_values), axis=1)) / N</pre><p><strong><em>3.2 Average Counting Distance(ACD):-</em></strong></p><p>Average counting distance measures the average number of errors for each image. Different from cAcc that only cares whether the complete product list is correctly predicted or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*45vLr_uyVFSstZxx" /></figure><ul><li>Lower is better.</li></ul><pre>def ACD(pred_values, label_values, N):<br>    total_cd = np.sum(np.abs(label_values - pred_values), axis=1)<br>    total_gd = np.sum(label_values, axis=1)<br>    return np.sum(np.divide(total_cd, total_gd)) / N</pre><p><strong><em>3.3 Mean Category Counting Distance(mCCD):-</em></strong></p><p>Calculate the average percentage of counting errors for each SKUs(Stock keeping unit) category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*XeM_U7moilyYYibI" /></figure><ul><li>Lower is better.</li></ul><pre>def mCCD(pred_values, label_values, K):<br>    class_cd = np.sum(np.abs(label_values - pred_values), axis=0)<br>    class_gt = np.sum(label_values, axis=0)<br>    return np.sum(np.divide(class_cd, class_gt)) / K</pre><p><strong><em>3.4 Mean Category Intersection of Union(mCIoU):-</em></strong></p><p>Check for consistency between the anticipated shopping list and reality. It is driven by an IOU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*NVSfQeqsBvF7oBP4" /></figure><ul><li>Higher is better.</li></ul><pre>def mCIoU(pred_values, label_values, K):<br>    minimum = np.minimum(pred_values, label_values)<br>    maximum = np.maximum(pred_values, label_values)<br>    class_minimum = np.sum(minimum, axis=0)<br>    class_maximum = np.sum(maximum, axis=0)<br>    return np.sum(np.divide(class_minimum, class_maximum)) / K</pre><h3>4. Mapping the real-world problem.</h3><p>The retail stores often face long queues at the billing counter, especially during peak hours. The customers have to wait for a long time to pay for their products, which results in a poor shopping experience. To provide a seamless shopping experience and reduce the waiting time for customers, the retail store wants to implement a self-checkout system.</p><h4>ML Problem:</h4><p>To implement a self-checkout system, the retail store can use machine learning to automate the billing process. The goal is to build a system that can identify the products in billing desk in one goal and generate bills for the customers.</p><p>The problem can be divided into the following sub-problems:</p><ol><li>Product Recognition: The system needs to recognise the products being scanned by the customers accurately. This can be achieved by training an object detection or image recognition model using deep learning techniques. The model should be trained on a large dataset of product images to recognise various products accurately.</li><li>Quantity Recognition: The system should be able to recognise the number of products being scanned by the customers. This can be achieved by training a model to recognise digits accurately.</li><li>Billing: The system should be able to generate the final bill based on the products and their quantities scanned by the customer. This can be achieved by integrating the product recognition and quantity recognition models and using them to calculate the final bill.</li><li>User Interface: The system should have a user-friendly interface that guides the customers through the scanning and billing process.</li></ol><p>Overall, the ML problem is to build a self-checkout system that can accurately recognise products, their quantities, and generate bills for the customers in a fast and efficient manner.</p><h3>5. Exploratory Data Analysis(EDA):</h3><p>No. of unique image in Train datasets:- 53739</p><p>No. of unique image in Test datasets:- 2400</p><p>No. of unique image in validation datasets: 6000</p><h4>5.1 Categories(SKUs) in dataset.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5AXgOcrhj7Uv669Vd3row.png" /></figure><h4>Observation.</h4><p>● There are 200 products with 17 category(SKUs).</p><p>● stationery category(SKUs) has only 7 different types of items which is minimum.</p><p>● tissue category(SKUs) has only 20different types of items which is maximum.</p><h4>5.2 Levels in dataset.</h4><p>● There are three types of images in datasets.</p><p>a. Easy approx 19%.</p><p>b. Medium approx 47%.</p><p>c. Hard approx 34%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*M8XPmT_9y9iIvkQ46-g6PQ.png" /></figure><h4>5.3 Sample image in train dataset.</h4><p>● In train data image contain single item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*476RosZed9dl_3HSVQt20g.png" /></figure><p>● In train dataset one item has many image of different angles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*uzwTlq-OQLGa5L6p9uoVig.png" /></figure><h4>5.4 Correlation between all the numerical variables.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*26aNuImgcI8I36OmMZT2Dw.png" /></figure><h4>Observation.</h4><p>● There is very high correlation between category_id and shelf.</p><h4>5.5 Sample image in test and validation dataset.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*ZZiZDguejidFmx0P07rwuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*1KO647RStZLI9eKQD0LMLg.png" /><figcaption>\</figcaption></figure><p>● Sample image of test and validation with level easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*uxt3Tyin6Ju9-78Ry9LrsQ.png" /></figure><p>● Sample image of test and validation with level medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*z3cVSH3ROuQbpIDcVRN_mA.png" /></figure><p>● Sample image of test and validation with level hard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*FgDoMoo0PaKUSFtz7U8nmA.png" /></figure><h4>Observation.</h4><p>● In images of the hard level, items are densely packed together, while in images of the easy level, items are more loosely arranged. In images of the medium level, items are moderately packed together.</p><h4>5.6 Which category items occurred more or less in the dataset.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*NpvvTM_SSRV_uN-jVQ9pqg.png" /></figure><h4>Observation.</h4><p>● Stationery items occur approx 7500 times in the dataset.</p><p>● Tissue items occur approx 28000 times in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*JC4r7IEa0qDhr4fTIBPXRw.png" /></figure><p>● Tissue occurred approx 9.4% in the datasets</p><h4>5.6 Which product occurred more or less in the dataset.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*iWZ5NhZxMyYa9HeWqb9pXg.png" /></figure><h4>Observation.</h4><p>● 63_desert item occurred approx 580 times in the dataset.</p><p>●119_canned_food occurred approx 160 times in the dataset.</p><h3><strong>6. Data Engineering.</strong></h3><p>In this type of problem, managing large amounts of data can be a significant challenge. One approach to address this is to utilise data augmentation(e.g- zoom in, zoom out, flip, rotate) techniques to increase the quantity of available data. However, when applying data augmentation, it is essential to update image annotations for each newly generated image, which can pose a significant challenge.</p><p>To tackle this type of scenario we use Cycle GAN.</p><h4><strong>Cycle GAN:</strong></h4><ul><li>Image to Image translation.</li><li>Generating a new synthetic version of a given image with modification.</li><li>It basically captures the characteristics of one image domain and then it figures out how these can be transferred into another image domain.</li></ul><h4><strong>Application of Cycle GAN:</strong></h4><ol><li>Translating night scene into day scene.</li><li>Sunny day into rainy day.</li><li>Photo enhancement.</li><li>Season transfer.</li><li>Image colouring.( That we use in Self checkout model)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*wb5KztzWJhP_WEGs" /><figcaption>Cycle GAN</figcaption></figure><h3><strong>7. Deep Learning Models.</strong></h3><h4>7.1 R-CNN:</h4><p>The R-CNN (Regions with Convolutional Neural Network) architecture is a popular object detection architecture. It consists of three main components:</p><ol><li>Region Proposal Component: This component generates a set of candidate regions (also known as region proposals) that are likely to contain objects. This is usually done using techniques such as Selective Search or Edge Boxes.</li><li>Feature Extraction Component: After generating the region proposals, the next step is to extract features from each region. This is typically done by using a convolutional neural network (CNN) such as AlexNet, VGG, or ResNet.</li><li>Classification and Localization Component: Finally, the extracted features are passed through a fully connected layer to generate class scores and location predictions for each region proposal.</li></ol><ul><li>The R-CNN architecture has a significant computational cost, as it requires running a forward pass of the CNN on each of the region proposals.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*cEPjwZ1cjVfakagU.png" /><figcaption>Low level overview of R-CNN architecture.</figcaption></figure><h4>7.2 Fast R-CNN:</h4><p>The Fast R-CNN architecture is a type of object detection system that uses a two-stage pipeline for object detection. The first stage generates region proposals that may contain an object, while the second stage classifies these regions and predicts their locations in the image.</p><p>The Fast R-CNN architecture consists of three main components:</p><p>(i) Region Proposal Network (RPN): This component generates region proposals by sliding a small network over the feature maps of the input image. The RPN outputs a set of object proposals along with their bounding box coordinates and objectness scores.</p><p>(ii) RoI Pooling: This component takes the region proposals generated by the RPN and extracts features from each region using RoI (Region of Interest) pooling. This allows the system to have a fixed-length feature representation of each region, regardless of its size.</p><p>(iii) Classification and Regression Head: This component uses the RoI-pooled features to predict the class labels of the objects and the bounding box coordinates of each object. The head is typically a fully connected network that outputs class scores and bounding box regression parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tmt5Sv21jUR6cwBb.png" /><figcaption>Low level overview of Fast R-CNN architecture.</figcaption></figure><p>Fast R-CNN is considered to be one of the most accurate object detection systems in terms of both accuracy and speed. Its two-stage pipeline allows it to handle complex object detection tasks, while still maintaining good performance.</p><h4>7.3 Faster R-CNN:</h4><p>Faster R-CNN is an improvement over R-CNN that speeds up the process by using a shared feature map for both the region proposals and the bounding box classification and regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*mXKbu1IHyF0d000C93EbuQ.png" /><figcaption>Low level overview of Faster R-CNN architecture.</figcaption></figure><p>The implementation Faster R-CNN is based on the open-source system Detectron2, which is built on the PyTorch framework. The feature extractor utilised in this model is the Resnet-101 architecture. The model is initialized with pre-trained weights from a reputable object detector. Prior to starting the training process, the model was supplied with pre-trained weights from the Detectron2 Model Zoo. The training process took approximately 4 hours to complete over 10000 iterations on the + dataset. The progress of the training was monitored and evaluated using Tensor-board.</p><p>Upon successful training of the Faster R-CNN model, we were able to extract the following outputs:</p><ul><li>A comprehensive list of bounding boxes.</li><li>A unique identifier assigned to each bounding box</li><li>The likelihood score for each label and corresponding bounding box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*kNIU713aejZaAFgw7afGSw.png" /></figure><p>After training of 12000 epochs it takes approx 3 hours <a href="https://github.com/M-S-ALAM/Self-Checkout/blob/main/Faster_RCNN.ipynb">code is here</a>. we get</p><p>(i) <strong><em>Checkout Accuracy(</em></strong>cAcc): 0.7425</p><p>(ii) <strong><em>Average Counting Distance(</em></strong>ACD): 0.4113</p><p>(iii) <strong><em>Mean Category Counting Distance(</em></strong>mCCD): 0.032</p><p>(iv) <strong><em>Mean Category Intersection of Union(</em></strong>mCIoU): 0.968</p><p>(v) <strong><em>Mean Average Precision 50(mAP50): </em></strong><em>97.3</em></p><p><em>Sample of outputs:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*bbksbTOi0MH1nD3yr7_JKQ.png" /></figure><h4>7.4 Cascade R-CNN:</h4><p>Cascade R-CNN is a modification of faster R-CNN that addresses the problem of detecting small objects. In cascade R-CNN, there are multiple stages of RPNs, each generating region proposals with increasing IOU thresholds. This allow the model to focus on small objects in later stages, after filtering out larger objects in earlier stages.</p><ul><li>Cascade RCNN is a variant of the two-stage object detection architecture, similar to Faster RCNN. The main difference between Cascade RCNN and Faster RCNN is that Cascade RCNN uses multiple stages of object detection, each with increasing accuracy and computational cost.</li><li>In each stage of the Cascade RCNN architecture, the region proposals are filtered using a classifier. The region proposals that are more likely to contain objects are passed on to the next stage for further processing, while the less likely region proposals are discarded. This cascaded filtering process allows for more efficient object detection, as it reduces the number of region proposals that need to be processed by the final detection network.</li><li>Like Faster RCNN, Cascade RCNN uses a shared feature extractor network to extract features from the input image. The feature extractor network can be a pre-trained deep neural network, or it can be trained from scratch.</li></ul><p>Cascade RCNN has shown to be more accurate than Faster RCNN on some object detection tasks, as the cascaded filtering process allows for more fine-grained object proposals. However, the increased accuracy comes at the cost of increased computational cost, as multiple stages of object detection must be processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*HgdSgGmZVx7_rKI_.jpg" /></figure><p>After training of 20000 epochs it takes approx 4.5 hours <a href="https://github.com/M-S-ALAM/Self-Checkout/blob/main/Cascade_RCNN.ipynb">code is here</a>. we get</p><p>(i) <strong><em>Checkout Accuracy(</em></strong>cAcc): 0.774</p><p>(ii) <strong><em>Average Counting Distance(</em></strong>ACD): 0.3053</p><p>(iii) <strong><em>Mean Category Counting Distance(</em></strong>mCCD): 0.0250</p><p>(iv) <strong><em>Mean Category Intersection of Union(</em></strong>mCIoU): 0.974</p><p>(v) <strong><em>Mean Average Precision 50(mAP50): </em></strong>97.163</p><p><em>Sample of outputs:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*ct1sqfMyJMettphKrwhs2Q.png" /></figure><h4>7.5 Mask R-CNN:</h4><p>Mask R-CNN is a variant of the two-stage object detection architecture, similar to Faster R-CNN and Cascade R-CNN. The main difference between Mask R-CNN and the other two-stage architectures is that Mask RCNN adds a third component for instance segmentation.(It adds a branch in the fast R-CNN)</p><p>Instance segmentation is the process of segmenting an object in an image and assigning a unique label to each object instance. In Mask RCNN, the third component is a fully convolutional network that takes the region proposals from the detection network and predicts a mask for each object instance.</p><p>Like Faster RCNN and Cascade RCNN, Mask RCNN uses a shared feature extractor network to extract features from the input image, and a region proposal network (RPN) to generate candidate object locations. The detection network then classifies each region proposal as an object or background, and refines the location of the object within the region.</p><p>The architecture of Mask RCNN is designed to handle object detection and instance segmentation tasks jointly, allowing for improved accuracy on these tasks. The instance segmentation component of the architecture also allows for more fine-grained understanding of the objects in an image, as it can segment and label each object instance individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*WBciKDL72w7Cc1on.png" /></figure><p>After training of 12000 epochs it takes approx 3 hours <a href="https://github.com/M-S-ALAM/Self-Checkout/blob/main/Mask_RCNN.ipynb">code is here</a>. we get</p><p>(i) <strong><em>Checkout Accuracy(</em></strong>cAcc): 0.697</p><p>(ii) <strong><em>Average Counting Distance(</em></strong>ACD): 0.498</p><p>(iii) <strong><em>Mean Category Counting Distance(</em></strong>mCCD): 0.040</p><p>(iv) <strong><em>Mean Category Intersection of Union(</em></strong>mCIoU): 0.9608</p><p>(v) <strong><em>Mean Average Precision 50(mAP50): </em></strong>96.352</p><p><em>Sample of outputs:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*p5vTpCfETMRKjtRW5axw9g.png" /></figure><h4>R-CNN family:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_ve-SnAB8yrHs-kiQOWng.png" /></figure><p>The Best model is Cascade R-CNN.</p><h3>8. Deployment.</h3><p>I used Flask to construct a web app and then deployed the model in my local machine.<br>Here’s a little video of my deployed app in action.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM_eSA_jxzoY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM_eSA_jxzoY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM_eSA_jxzoY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fdc4c0204cc01f9eef373d71410684/href">https://medium.com/media/28fdc4c0204cc01f9eef373d71410684/href</a></iframe><h3>9. Future Work and Improvements.</h3><p>● Use Cycle GAN for data Augmentation.</p><p>● Use Yolo family model for object detection.</p><p>● Use mmdetection library instead of detectron2.</p><p>● Train Cascade R-CNN for more than 20000 epochs.</p><h3><strong>10. References.</strong></h3><ul><li><a href="https://www.kaggle.com/datasets/diyer22/retail-product-checkout-dataset">https://www.kaggle.com/datasets/diyer22/retail-product-checkout-dataset</a></li><li><a href="https://arxiv.org/pdf/1901.07249.pdf">https://arxiv.org/pdf/1901.07249.pdf</a></li><li><a href="https://lilianweng.github.io/posts/2017-12-31-object-recognition-part-3/">https://lilianweng.github.io/posts/2017-12-31-object-recognition-part-3/</a></li><li><a href="https://github.com/facebookresearch/detectron2">https://github.com/facebookresearch/detectron2</a></li><li><a href="https://towardsdatascience.com/object-detection-in-6-steps-using-detectron2-705b92575578">https://towardsdatascience.com/object-detection-in-6-steps-using-detectron2-705b92575578</a></li><li><a href="https://jonathan-hui.medium.com/map-mean-average-precision-for-object-detection-45c121a31173">https://jonathan-hui.medium.com/map-mean-average-precision-for-object-detection-45c121a31173</a></li><li><a href="https://blog.paperspace.com/object-detection-segmentation-with-detectron2-on-paperspace-gradient/">https://blog.paperspace.com/object-detection-segmentation-with-detectron2-on-paperspace-gradient/</a></li><li><a href="https://github.com/open-mmlab/mmdetection">https://github.com/open-mmlab/mmdetection</a></li><li><a href="https://www.sciencealert.com/consumers-have-a-bigger-impact-on-the-environment-than-anything-else-study-finds">https://www.sciencealert.com/consumers-have-a-bigger-impact-on-the-environment-than-anything-else-study-finds</a></li></ul><h3>LinkedIn profile:</h3><p><a href="https://www.linkedin.com/in/md-shahbaz-alam-0395a6184">https://www.linkedin.com/in/md-shahbaz-alam-0395a6184</a></p><h3>Github Link:</h3><p><a href="https://github.com/M-S-ALAM/Sarcastic-Comment-Detection">GitHub - M-S-ALAM/Sarcastic-Comment-Detection: Machine Learning/Deep Learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31e38e457dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M5 Forecasting Accuracy (Estimate the unit sales of Walmart retail goods)]]></title>
            <link>https://msalamiitd.medium.com/m-5-forecasting-accuracy-a363ace1a272?source=rss-eeae2c1b5903------2</link>
            <guid isPermaLink="false">https://medium.com/p/a363ace1a272</guid>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Md Shahbaz Alam]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 13:43:08 GMT</pubDate>
            <atom:updated>2022-12-01T04:43:53.129Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Do we predict the future finally? yes!! but maybe not so precisely.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cSGbTwoGs_NUT7IHzgBKA.jpeg" /></figure><h3><strong>Table of content:</strong></h3><ol><li>Business Problem.</li><li>Source of Data/Data Extraction.</li><li>Evaluation metrics.</li><li>Mapping the real-world problem to an ML problem</li><li>Exploratory Data Analysis(EDA).</li><li>Data Engineering.</li><li>Existing Approaches.</li><li>Machine Learning Models.</li><li>Deep Learning Models.</li><li>Experiments that did not work well.</li><li>Deployment.</li><li>Future Work and Improvements.</li><li>References.</li></ol><h3><strong>1. Business problem:</strong></h3><h4>1.1 What is sales forecasting?</h4><p>The technique of anticipating future sales, either short- or long-term, using previous sales data is known as sales forecasting.</p><h4>1.2 Problem Statement.</h4><p>For instance, investing in new strategies to improve their revenue for their items that may account for poor sales in the future through promotions/discounts e.t.c., forecasting sales is crucial for the companies. Therefore, it becomes crucial for established businesses to make realistic sales projections for the future.</p><h4><strong>1.3 Background of competition.</strong></h4><p>The Makridakis Open Forecasting Center (MOFC) at the University of Nicosia’s carries out cutting-edge forecasting research and offers corporate prediction training. It aids businesses in making precise predictions, estimating levels of uncertainty, averting costly errors, and using optimum forecasting techniques. The first of the MOFC’s Makridakis Competitions took place in the 1980s, and they are well renowned.</p><p>You will anticipate daily sales for the upcoming 28 days in this competition, the fifth version, using hierarchical sales data from Walmart, the largest company in the world by revenue.</p><h4>1.4 Objective.</h4><p>The major goal is to accurately predict point forecasts of unit sales for a variety of products that Walmart sells in the USA, which will enable different Walmart locations enhance their revenue.</p><h4>1.5 Business objectives and constraints.</h4><ol><li>High Interpret ability since we must understand the crucial factor that contributed to good predictions.</li><li>No rigorous low latency is required because we need to forecast sales daily rather than minute by minute or hour by hour.</li></ol><h3>2. Source of Data/Data Extraction.</h3><blockquote>Data for this problem can be downloaded from this <a href="https://www.kaggle.com/competitions/m5-forecasting-accuracy/data">link</a>.</blockquote><h4>2.1 Data overview.</h4><p>It makes use of hierarchical sales data that Walmart kindly made accessible. The data was aggregated over departments, product categories, and stores in three different US states: California, Texas, and Wisconsin. It also contained explanatory factors, such as pricing, promotions, day of the week, and special events, in addition to the time series data.</p><p>In simple,the dataset involves the unit sales of <em>3,049 products, classified into 3 product categories (Hobbies, Foods, and households) and 7 product departments</em>, and products are sold across ten stores, located in three states (CA, TX, and WI).</p><p>Dataset provided had contained sales data for 5 years starting from 29th Jan 2011 to 22th April 2016.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*jRfNGmwRHPt2Dt5odO0E4A.png" /></figure><blockquote>The dataset consists of 4 files.</blockquote><ol><li><strong>Calendar.csv</strong>: Contains information about the dates on which the products are sold.</li></ol><ul><li>date: The date in a “yyyy-mm-dd” format.</li><li>wm_yr_wk: The id of the week the date belongs to.</li><li>weekday: The type of the day (Saturday, Sunday, …, Friday).</li><li>wday: The id of the weekday, starting from Saturday.</li><li>month: The month of the date.</li><li>year: The year of the date.</li><li>event_name_1: If the date includes an event, the name of this event.</li><li>event_type_1: If the date includes an event, the type of this event.</li><li>event_name_2: If the date includes a second event, the name of this event.</li><li>event_type_2: If the date includes a second event, the type of this event.</li><li>snap_CA, snap_TX, and snap_WI: A binary variable (0 or 1) indicating whether the stores of CA, TX or WI allow SNAP purchases on the examined date. 1 indicates that SNAP purchases are allowed.</li></ul><p><strong>2. Sales_train_evaluation.csv</strong>: Contains the historical daily unit sales data per product and store.</p><ul><li>store_id: The id of the store where the product is sold</li><li>item_id: The id of the product.</li><li>wm_yr_wk: The id of the week.</li><li>sell_price: The price of the product for the given week/store. The price is provided per week (average across seven days). If not available, this means that the product was not sold during the examined week. Note that although prices are constant at weekly basis, they may change through time (both training and test set).</li></ul><p><strong>3. Sell_prices.csv</strong>: Contains information about the price of the products sold per store and date.</p><ul><li>item_id: The id of the product.</li><li>dept_id: The id of the department the product belongs to.</li><li>cat_id: The id of the category the product belongs to.</li><li>store_id: The id of the store where the product is sold.</li><li>state_id: The State where the store is located.</li><li>d_1, d_2, …, d_i, … d_1941: The number of units sold at day i, starting from 2011–01–29.</li></ul><p><strong>4. Sample_submission.csv</strong>: The correct format for submissions.</p><blockquote>credits: <a href="https://mk0mcompetitiont8ake.kinstacdn.com/wp-content/uploads/2020/01/M5-Guidelines.pdf">M5 -Guidelines</a></blockquote><h3>3. Evaluation metrics.</h3><p>M5 competition has provided <a href="https://www.kaggle.com/c/m5-forecasting-accuracy/overview/evaluation">Root Mean Square Scaled Error metric</a>, But we take RMSE for model training and testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*WeU_iN5GLMp8t8vn3mwXAw.jpeg" /></figure><p>● Each error is not handled equally by RMSE. The most important errors are given more weight.</p><p>● Therefore, a poor RMSE can be obtained with just one significant error.</p><h3>4. Mapping the real-world problem to an ML problem.</h3><p>The problem we are solving is a time series problem which we can transform it into supervised learning problem by performing Feature engineering on the raw time series data. Then we can use these features as input variables and ‘sales of the item’ as output variable (Real number) and solve the problem of forecasting using Machine learning Regression models.</p><h3>5. Exploratory Data Analysis(EDA).</h3><blockquote>Exploratory data analysis is a crucial method that we must do in order to comprehend the data before we can use machine learning to solve the problem.</blockquote><p>So, first will start with data files(. CVS) contains Nan values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*-qAKE0e1vqNbXG-9oAaO9w.png" /></figure><p>As you can see there are a lot of null values in the event_name_1, event_name_2, event_type_1 and event_type_2 column.</p><blockquote><strong>What is the pattern of overall sales(quantity) across all states and stores on daily basis?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05feis5h3he3ESGZlHT_Yw.png" /></figure><h4>Observations</h4><p>● Total sales(number of units sold) have been trending slightly upward from 2011 to 2016.</p><p>● Every year, the sales pattern is the same, and on January 1st, we see no sales (may be the stores are closed on New year)</p><blockquote><strong>What is the pattern of overall sales(Revenue) across all states and stores on daily basis?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3SMDdEgwqQsNCa-k3E5LA.png" /></figure><h4>Observations</h4><p>● Total sales(revenue) have been trending upward every year.</p><p>● Revenue and overall sales(quantity) day wise follow almost trend.</p><blockquote><strong>What is the pattern of total sales(quantity) for each year separately?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yo2T3j0GDAC_fsd2skFYsg.png" /></figure><h4>Observations</h4><p>● There is similar pattern of overall sales across years and has yearly seasonality</p><p>● From 2012 to 2015 sales we observe each 2 month sales having same pattern and also each year time-series of 2012–2015 is stationary time-series.</p><blockquote><strong>How much change of percentage in total sales(quantity) and revenue for each year separately?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*m2bkHoYcXE7lLHcsTAiCDA.png" /></figure><h4>Observations</h4><p>● Revenue increase 1% to 2% every year.</p><p>● Sales(quantity) increase every year except year 2014.</p><blockquote><strong>What is the Monthly Seasonality of total sales(quantity) across all years over all stores?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*qkNPOYGNa-d_yLCCNlyNng.png" /></figure><h4>Observations</h4><p>● March and November are the months with the highest and lowest sales, respectively.</p><p>● Sales fell off in the middle of the year, recovered, and then fell off again at the conclusion of the year.</p><blockquote><strong>What is the Monthly Seasonality of total sales(Revenue) across all years over all stores?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*LnFF7IeYW_4xPGwxREvWAQ.png" /></figure><h4>Observations</h4><p>● March and June are the months with the highest and lowest revenue, respectively.</p><p>● Revenue and overall sales(quantity) month wise follow almost trend.</p><blockquote><strong>How much change of percentage in total sales(quantity) and revenue for each month separately?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*guyGEZjv4fucpR944L3NMg.png" /></figure><h4>Observations</h4><p>● Monthly sales in quantity is higher in month of march and april.</p><blockquote><strong>What is the Weekly Seasonality of total sales(quantity) across all stores?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*bl8bpREIVqN0JzlMTCpODw.png" /></figure><h4>Observations</h4><p>● Sales are higher on the weekends and fall off throughout the week, but they increase again on Fridays early in the weekend.</p><p>● We notice that consumers tend to shop more during the weekends than during the week, and that overall Sunday sales are lower than those of Saturday.</p><blockquote><strong>What is the Weekly Seasonality of total sales(revenue) across all stores?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*gZGGoilAoR7ObaDN1QWgmg.png" /></figure><h4>Observations</h4><p>● Revenue are higher on the weekends and other days it’s constant.</p><p>● Revenue and overall sales(quantity) weekday wise follow almost trend.</p><blockquote><strong>Given that the data is organised hierarchically, let’s analyse it at each level to provide a clear image of each division, including the state, store, category, and department.</strong></blockquote><h3>4.1 Analysis on State division:</h3><h4>a. Overall sales(quantity) in each state.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*3EjnHhPA1CtzpvYlLWhxjQ.png" /></figure><h4>Observations.</h4><p>● Out of three states California accounts for high percentage of the total sales in quantity.</p><p>● Texas and Wisconsin total sales(quantity) are almost equal.</p><h4>b. Overall sales(revenue) in each state.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*IpJDy0WdbEXyNwjnSEuvng.png" /></figure><h4>Observations.</h4><p>● Out of three states California accounts for high percentage of the Revenue.</p><p>● Texas and Wisconsin revenue are almost equal.</p><h4><strong>c. How much change of percentage in total sales(quantity) and revenue for each state separately?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*DOw2UOA26ZdZSDFopJXLdA.png" /></figure><h4>Observations.</h4><p>● Sales in quantity in California is high than revenue is also high. But in Wisconsin it is totally opposite.</p><h4><strong>d. Daily sales in each state.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxIRVfU70h4ik43DJHDKtw.png" /></figure><h4>Observations.</h4><p>● All three states sales increase each year, and on January 1st, we see no sales (may be the stores are closed on New year)</p><p>● Sales is almost same for state TX and WI.</p><h3><strong>4.2 Analysis on Store division:</strong></h3><h4>a. Overall sales(quantity) in each store.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*aGeumHOeUSr_cwPfCLlDfA.png" /></figure><h4>Observations</h4><p>● Interestingly, despite California State accounting for 43.6% of overall sales, two of its stores’ total sales rank in the bottom four.</p><p>● CA_3 Store has highest sales and CA_4 store has lowest sales.</p><h4>b. Overall sales(revenue) in each store.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*HoHXC4TY7rchxXqKZQHBNg.png" /></figure><h4>c. How much change of percentage in total sales(quantity) and revenue for each store separately?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*GOFj7Naokc7i0TtzXEeFvQ.png" /></figure><h4>Observations.</h4><p>● California State accounting for 43.6% of overall sales.</p><h4>d. Daily sales in each store.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdohGcUo6AwNyUsixbIQOA.png" /></figure><h4>Observations.</h4><p>● Highest sales are from ‘FOODS_3’ department and lowest are from ‘HOBBIES_2’ department. ‘FOOD_3’ department alone has 50% sales proportion and other 6 departments accounts for rest 50%.</p><p>● Even though the total sales from ‘HOBBIES’ category is very less(9.3%), interestingly it’s department ‘HOBBIES_1’ has high number of sales compared to FOODS category’s ‘FOODS_1’ department.</p><h3><strong>4.3 Analysis on Categories division:</strong></h3><h4>a. Overall sales(quantity) in each categories.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*7CBF3kXnXQCa_RDtQ_f3yA.png" /></figure><h4>Observations</h4><p>● Food has the largest sales percentage, while hobbies has the lowest.</p><p>● It is clear that consumers buy more domestic necessities than pastimes, and since food products are necessary, sales are also strong.</p><h4>b. Overall sales(revenue) in each categories.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*48S8BD3jM6yzUea9t2doHg.png" /></figure><h4>Observations.</h4><p>● Household sales in quantity is very low but revenue is very high. that means household product is costly.</p><h4>c. How much change of percentage in total sales(quantity) and revenue for each category separately?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*fXOjii0IYpgNIfXjteB-Tg.png" /></figure><h4>Observations.</h4><h4>d. Daily sales in each categories.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MHGk2OPUrnduLltKHBl6g.png" /></figure><h4>Observations.</h4><p>● Daily total sales of Food category is highest and has trend upwards (sales increasing over the years)</p><p>● Daily total sales of Hobbies category are the least and remain almost constant over the years.</p><p>● Daily total sales of Household category also has trend upwards (sales increasing over the years).</p><h3>4.4 Analysis on Department division:</h3><h4>a. Overall sales(quantity) in each department.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Z0bqJdE0Crirhy-CMcgIfw.png" /></figure><h4>Observations.</h4><p>● FOODS_3 and Hobbies_2 have higher and lower number of sales in quantity respectively.</p><h4>b. Overall sales(revenue) in each department.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*19tsAT8ub_WgYB-vk32WCg.png" /></figure><h4>Observations.</h4><p>● FOODS_3 and Hobbies_2 have higher and lower revenue respectively.</p><h4>c. How much change of percentage in total sales(quantity) and revenue for each department separately?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*GaaWjeagrROFOlCOvw3v3Q.png" /></figure><h4>b. Daily sales in each department.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDH0r7HfmOL_7WKBo4Nmyw.png" /></figure><h4>Observations.</h4><p>● Highest sales are from ‘FOODS_3’ department and lowest are from ‘HOBBIES_2’ department. ‘FOOD_3’ department alone has 50% sales proportion and other 6 departments accounts for rest 50% sales.</p><p>● Even though the total sales from ‘HOBBIES’ category is very less(9.3%), interestingly it’s department ‘HOBBIES_1’ has high number of sales compared to FOODS category’s ‘FOODS_1’ department.</p><h3><strong>4.5 Analysis on item division.</strong></h3><h4>a. Overall sales of 5 items from top.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*eXkz1GlxbXmuUizzBVp1VQ.png" /></figure><h4>Observations.</h4><p>● Highest sales is ‘FOODS_3_090’ are from FOODS department.</p><p>● second Highest sales are ‘FOODS_3_586’ is also from FOODS department.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vntsTRGr1ZLoFZe5FCUIMg.png" /></figure><h4>b. Overall sales of 5 items from down.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Rr9z3MuJj9cYw9ZW2wDjjQ.png" /></figure><h4>Observations.</h4><p>● Lowest sales is ‘HOBBIES_2_119’ are from HOBBIES department.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxDcZxdF3ev_cCkKb809VA.png" /></figure><h3>Sates Vs Product category sales proportion.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*Vvx14w5WhlVh5gN5CEeazg.png" /></figure><h4>Observations.</h4><p>● All the three states has similar proportion of sales for all the three product categories.</p><p>● Food category sales proportion is same for the states Texas and Wisconsin</p><h3>Product Category Vs Sates sales proportion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*ZjSttkfiS-FNDwT2PqZq4Q.png" /></figure><h4>Observations.</h4><p>● Food category accounts for higher sales and hobbies the lowest for all 3 states.</p><p>● Texas and Wisconsin states has similar proportion of sales for Hobbies product category.</p><h3>Price v/s Demand.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*wmGs0zHtMk5k42WNxz0CPg.png" /></figure><blockquote><em>There are many EDA you can check it here.</em></blockquote><h3><strong>6. Data Engineering.</strong></h3><blockquote>Stationary Data:- A stationary time series is one whose properties is not depend on at which the series is observed.</blockquote><p>⭒ Time series with trends or seasonality are not stationary. The trend and seasonality will affect the value of time series at different times.</p><p>To detrend the time series data there are certain transformation techniques used and they are listed as follows.</p><ol><li>For d_id, state_id, store_id, cat_id, dept_id and item_id will directly label encoding.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a64c34342dac5be01d4cada638f6cdfc/href">https://medium.com/media/a64c34342dac5be01d4cada638f6cdfc/href</a></iframe><p>2. Apply average value of all possible combination. because item, store, categories, state, e.t.c are correlated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*bFe_Lvx_sDk-hxbLD8kNEw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa5ce36c4548bdc2788c87eb37132b92/href">https://medium.com/media/aa5ce36c4548bdc2788c87eb37132b92/href</a></iframe><p>3. In EDA, I discovered that while we cannot find periodicity in months or years, we can find it in weeks. In that regard, one method to capture periodicity is to “lag” information. where our target value is demand(quantity).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07053b636bff9a6569a250b487630104/href">https://medium.com/media/07053b636bff9a6569a250b487630104/href</a></iframe><p>4. <strong>Rolling: </strong>taking rolling mean and rolling standard deviation with shift of 28 days.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/523d94673f06531668c16c28e99f27d9/href">https://medium.com/media/523d94673f06531668c16c28e99f27d9/href</a></iframe><p>5. Deal with the missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*spRIVOsVjmmWsPPq1l-xbg.png" /></figure><p>fill the missing value with mean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44317e626cc2d755161c9c8f014f30b/href">https://medium.com/media/d44317e626cc2d755161c9c8f014f30b/href</a></iframe><h4>Notebook of Feature Engineering is<a href="https://github.com/M-S-ALAM/M5-Forecasting-Accuracy/blob/main/Data_preprocessing_final.ipynb"> here</a>.</h4><h3><strong>7. </strong>Existing Approaches<strong>.</strong></h3><h4><a href="https://www.artefact.com/news/sales-forecasting-in-retail-what-we-learned-from-the-m5-competition-published-in-medium-tech-blog/"><strong>Solution 1</strong></a><strong>:</strong></h4><p>a. A data scientist, summarises his findings from the M5 sales forecasting competition in this article, which involved estimating future sales in multiple Walmart locations. He talked about the answer and how the machine learning model performed the task the best.</p><p>b. In this tournament, he mentions two measure challenges, namely:</p><ul><li>Long stretches of time with no sales in a row are referred to as intermittent values.</li><li>Extended prediction horizon: Competitors must produce projections for a 4-week period in addition to the upcoming week.</li></ul><p>c. He also talks about the feature engineering portion. He advised us to look for traits that would enable us to acquire the following three pieces of data:</p><h4>● Seasonality</h4><h4>● Trends</h4><h4>● Pricing</h4><p>d. Tweedie loss to handle intermittent values.</p><h4><a href="https://github.com/Mcompetitions/M5-methods">Solution 2:</a></h4><p>a. He uses a combination of different LightGBM models, each equally weighted.</p><p>b. Gathering data from each store (10 models), each store category (30 models), and each store department, train a model to generate projections for the product store series (70 models).</p><p>c. Both in a recursive and a non-recursive structure, the models took into account different IDs, calendar-related data, special events, promotions, prices, and unit sales data.</p><p>d. The approach was improved by assessing the mean and standard deviation of the errors generated by the individual models and their combinations, as well as the last four 28-day.</p><h3>8. Machine Learning Models.</h3><h4>Option (i) :- One model for all the stores and weeks.</h4><ul><li>Data was taken after 1500 days (d 1500) to facilitate rapid processing.</li><li>Divide data into Train, Test, Validation.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b32264610775bc9f537aad22e2db18b3/href">https://medium.com/media/b32264610775bc9f537aad22e2db18b3/href</a></iframe><h3>ⓐ Linear Regression.</h3><p>Linear Regression is a machine learning algorithm. which is based on supervised learning, that finds the linear relationships between the target and one or more predictors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*0-RDadDNpBcDs_biPrJHBQ.png" /><figcaption>Linear Regression Model</figcaption></figure><p>● RMSE Score=0.00264</p><p><strong><em>Important Features in Linear Regression Model.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*0t-M9UaqY75iwNUt-Xo5EQ.png" /></figure><h3>ⓑ <strong>XGBoost Regressor.</strong></h3><p>The ensemble machine learning algorithm XGBoost, which is based on decision trees, makes use of the gradient boosting framework.</p><ul><li>After apply hyperparmeter tuning best learning_rate = 0.0451, max_leaves = 80, and min_child_weight = 36 which gives RMSE value of 0.1637.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ae62b352a3598aef44f89f4ba4a917/href">https://medium.com/media/66ae62b352a3598aef44f89f4ba4a917/href</a></iframe><p>● RMSE Score=0.1637</p><p><strong><em>Important Features in XGBoost Regressor Model.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*TqyAscmUudUGekBZFLOsHA.png" /></figure><h3>ⓒ LGBM Regressor.</h3><p>This is a light version of the Gradient Boosting Model. It is a tree-based ensemble model.</p><ul><li>After apply hyperparmeter tuning best learning_rate = 0.0355, max_depth = 135, and num_leaves = 54 which gives RMSE value of 0.1637.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deaeca4081bda3da96b093b14cfd6c3c/href">https://medium.com/media/deaeca4081bda3da96b093b14cfd6c3c/href</a></iframe><p>● RMSE Score=0.1080</p><p><strong><em>Important Features in LGBM Regressor Model.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*EiBa2sii57q_E6tuWP4AGA.png" /></figure><h3>ⓓ Cat Boost Regressor.</h3><p>Gradient boosting is the basis of Cat Boost. In order to reduce prediction time, which is crucial in low latency situations, Cat Boost uses symmetric trees.</p><ul><li>After apply hyperparmeter tuning best learning_rate = 0.0291, depth = 4, and num_leaves = 199 which gives RMSE value of 0.0471.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4b73f3d1dfaf842d988fc7ccf4b006e/href">https://medium.com/media/b4b73f3d1dfaf842d988fc7ccf4b006e/href</a></iframe><p>● RMSE Score=0.0471</p><p><strong><em>Important Features in Cat Boost Regressor Model.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*u3B3OphF870wRwTi9p4wHw.png" /></figure><h3>ⓔ Decision Tree Regressor.</h3><p>In using decision tree regression, properties of an object are observed, and a model is trained using a tree’s structure to forecast data in the future and create useful continuous output.</p><ul><li>After apply hyperparmeter tuning best max_depth=52, min_samples_split= 25, and min_samples_leaf = 293 which gives RMSE value of 0.0080.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4072ead68e26ec2dba214e1617e7b557/href">https://medium.com/media/4072ead68e26ec2dba214e1617e7b557/href</a></iframe><p>● RMSE Score=0.0080</p><p><strong><em>Important Features in Decision Tree Regressor Model.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*GXVHubd2VHP1t_otI226gA.png" /></figure><h4><strong>● We apply the model for all combination.</strong></h4><ol><li>Store wise Model .</li><li>Store, Category wise Model.</li><li>Store, Department wise Model.</li></ol><h4>Option (ii) : One model for each stores for all the weeks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PrvxxZkRP77AHULm1ww4nQ.jpeg" /></figure><p>The most obvious choice is the first one. It entails applying the same model to forecast data across the whole forecasting horizon.</p><h3>LGBM Regressor.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3663b6e58bf626f796e84bdc4fad99/href">https://medium.com/media/0e3663b6e58bf626f796e84bdc4fad99/href</a></iframe><p>● Average RMSE Score across all the stores 0.292 and 0.22 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*enqe-sOAAc3k1tyOkUAaXg.png" /></figure><h3>CatBoost Regessor</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acaa006dcba9ed5c6c6c3af7ca828033/href">https://medium.com/media/acaa006dcba9ed5c6c6c3af7ca828033/href</a></iframe><p>● Average RMSE Score across all the stores 0.050 and 0.02907 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*RZNjFdvxh0ZklAzIgiF7Pw.png" /></figure><h3>XGBoost Regressor</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49470ff717365083cf8c447d56a17d92/href">https://medium.com/media/49470ff717365083cf8c447d56a17d92/href</a></iframe><p>● Average RMSE Score across all the stores 0.1218 and 0.041 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*3HfAnqxm_sOckpXxuMldtQ.png" /></figure><blockquote><em>The best model in store wise prediction is LGBM Regressor.</em></blockquote><h3>Store Category wise monthly model:-</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28b746b483c3ef8bcc61e2e8478e986f/href">https://medium.com/media/28b746b483c3ef8bcc61e2e8478e986f/href</a></iframe><p>● Average RMSE Score across all the stores, category wise 0.118 and 0.021 for training and validation respectively.</p><figure><img alt="Store, category wise model." src="https://cdn-images-1.medium.com/max/568/1*us28bzPb7tawfMkNdEBdDg.png" /></figure><h3>Store, Department wise monthly model.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d51a30a6cac10a65de9374a81225231/href">https://medium.com/media/8d51a30a6cac10a65de9374a81225231/href</a></iframe><p>● Average RMSE Score across all the stores, department wise 0.28 and 0.16 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*GPFUaFSIllZEx3VDjkY4-g.png" /></figure><h4>Option (iii): One model for every weeks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zte5Fw3G5FM8P5twLzsbBA.jpeg" /></figure><h3>Store wise weekly model.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/881040aff27eb4416773fe73fe886b63/href">https://medium.com/media/881040aff27eb4416773fe73fe886b63/href</a></iframe><p>● Average RMSE Score across all the stores wise weekly 0.028 and 0.056 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*9bzpF69Zcpi2tgj0sISTvw.png" /></figure><h3>Store, Category wise weekly model:-</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c05f48d1cbc17bfd643e6df6d99c26c1/href">https://medium.com/media/c05f48d1cbc17bfd643e6df6d99c26c1/href</a></iframe><p>● Average RMSE Score across all the stores, categories weekly 0.0592 and 0.064 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*OFd9lJT8_O-ICoB52Kglog.png" /></figure><h3>Store, Department wise weekly model:-</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9676fb94953d56c4fe5ec0deca710eae/href">https://medium.com/media/9676fb94953d56c4fe5ec0deca710eae/href</a></iframe><p>● Average RMSE Score across all the stores, department weekly 0.042 and 0.026 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*8TOf5LWro1pTRPOfsTpV9A.png" /></figure><h4>Option (iv): Recursive modelling.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qbFwMZJWmXCD6d8nwqiIlA.jpeg" /></figure><h3>Store wise recursive model.</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5469659653dd85ccb950b6828fa5595e/href">https://medium.com/media/5469659653dd85ccb950b6828fa5595e/href</a></iframe><p>● Average RMSE Score across all the stores recursively 0.0892 and 0.026 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*ky86muw3HeG4Tt-YXFEYLA.png" /></figure><h3>Store, Category wise recursive model:-</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d69756e61745ad8665ee60bf331af9b/href">https://medium.com/media/4d69756e61745ad8665ee60bf331af9b/href</a></iframe><p>● Average RMSE Score across all the stores, categories and week recursively 0.098 and 0.026 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*ZxCNikb9j2a7eSp9pWn_PQ.png" /></figure><h3>Store, Department wise recursive model:-</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95802e25e70454fb35d5bb6aeceb9a7f/href">https://medium.com/media/95802e25e70454fb35d5bb6aeceb9a7f/href</a></iframe><p>● Average RMSE Score across all the stores, department and week recursively 0.052 and 0.026 for training and validation respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*nrWcaB6aV1Ce-Lqkg5747g.png" /></figure><h3><strong>9. Deep Learning Models.</strong></h3><p>“Life is really simple, but we insist on making it complicated” — Confucius</p><p>After experimenting with these complex machine learning, I decided to try a very simple Deep learning model with only a few LSTM, Dense, Dropout layers</p><blockquote><strong>One model for all the stores and weeks.</strong></blockquote><h4>Model a:- 4 LSTM layers and 1 Dense layer.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*mCGtnZnR4ffcHLXIGorHMA.png" /></figure><h4>● RMSE Score 0.0935 and 0.0332 for training and validation respectively.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1vpBJRkDw8fYWIDDNV_eA.png" /></figure><h4>Model b:- 2 LSTM, 2 Conv1D and 3 Dense layers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*6zCzAJRQBJt272MJ752wlg.png" /></figure><h4>● RMSE Score 0.192 and 0.36 for training and validation respectively.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJ4-2vP-Hy-YGKmw5zSL6Q.png" /></figure><h4>Model c:- 3LSTM, 2 Conv1D and 5Dense layers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*syNJlS69Fufjed77u3JtWw.png" /></figure><h4>● RMSE Score 0.362 and 0.302 for training and validation respectively.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SSURrYAt0B_xE7I5-P3kA.png" /></figure><h3><strong>10. Experiments that did not work well.</strong></h3><ul><li>Complex Deep Learning model with LSTM for each store.</li><li>Deep Learning model for each Store, Category wise Model.</li><li>Deep Learning model for each Store, Category wise Model.</li><li>ARIMA and friends.</li></ul><h3><strong>11. Deployment.</strong></h3><h3><strong>12. Future Work and Improvements.</strong></h3><p>● Ensemble model with stacking (uses predictions from multiple models to build a new model which is further used for making predictions on the test set)</p><p>● Use some more complex models and Hyper parameter tuning.</p><p>● Use GRU and Bidirectional LSTM instead of LSTM.</p><h3><strong>13. References.</strong></h3><p>● <a href="https://www.artefact.com/blog/sales-forecasting-in-retail-what-we-learned-from-the-m5-competition-published-in-medium-tech-blog/">https://www.artefact.com/blog/sales-forecasting-in-retail-what-we-learned-from-the-m5-competition-published-in-medium-tech-blog/</a></p><p>● <a href="https://dipanshurana.medium.com/m5-forecasting-accuracy-1b5a10218fcf">https://dipanshurana.medium.com/m5-forecasting-accuracy-1b5a10218fcf</a></p><p>● <a href="https://github.com/Mcompetitions/M5-methods">https://github.com/Mcompetitions/M5-methods</a></p><p>● <a href="https://medium.com/thecyphy/m5-forecasting-accuracy-af6c45fb7d58">https://medium.com/thecyphy/m5-forecasting-accuracy-af6c45fb7d58</a></p><p>Complete Project is available on<strong> </strong><a href="https://github.com/M-S-ALAM/M5-Forecasting-Accuracy"><strong>Github</strong></a>. For any queries regarding project contact me on <a href="https://www.linkedin.com/in/md-shahbaz-alam-0395a6184/"><strong>Linkedin</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a363ace1a272" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>