<?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 Aditya Bhakta on Medium]]></title>
        <description><![CDATA[Stories by Aditya Bhakta on Medium]]></description>
        <link>https://medium.com/@aditya.bhakta?source=rss-5ed08e921701------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7V6rSjnQPlZXXx_S.jpg</url>
            <title>Stories by Aditya Bhakta on Medium</title>
            <link>https://medium.com/@aditya.bhakta?source=rss-5ed08e921701------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:53:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aditya.bhakta/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 Food Recommendations using Graph Methods — Part 2]]></title>
            <link>https://medium.com/swiggy-bytes/enhancing-food-recommendations-using-graph-methods-part-2-9a9655c748b1?source=rss-5ed08e921701------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9655c748b1</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[graph-algorithms]]></category>
            <category><![CDATA[swiggy-data-science]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Aditya Bhakta]]></dc:creator>
            <pubDate>Wed, 05 May 2021 12:54:20 GMT</pubDate>
            <atom:updated>2021-05-06T06:55:47.014Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Food Recommendations using Graph Methods — Part 2</h3><p>As part of the 2 part series on using graphs for food recommendations, this article picks up the discussion from the first part published <a href="https://bytes.swiggy.com/enhancing-food-recommendations-using-graph-methods-part-1-344dd489b74d">here</a>. In particular, we’ll discuss using heterogeneous graph embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7k2RNXYpWMQoKHLCVZD3mQ.jpeg" /><figcaption>Food vector created by <a href="https://www.freepik.com/vectors/food">macrovector </a>— <a href="http://www.freepik.com/">www.freepik.com</a></figcaption></figure><h3>Random Walk based Embeddings</h3><p>We observed that random walk based embedding techniques (naive and node2vec) offer a way to improve food recommendations to customers. But there are a few limitations. Primarily, these are embeddings for a static graph. To learn embeddings for new nodes of the graph, the models need to be retrained. For new interactions (customers ordering from new restaurants in the following weeks/months) also, relearning needs to happen. Else, content-based similarity has to be used to infer for new nodes of the graph. This however is less accurate and requires content information that may not always be available (for example non-signed-in new users). Another challenge is scaling these 2 methods for a million scale graph.</p><p>For these aspects, we next examined non-random walk based approaches that scale to larger graphs. We also explored a method to leverage information from the food graph. Next, we moved to explore inductive methods, namely Graph Neural Networks, to end the effort with learning embeddings for heterogeneous graphs with node metadata. We compare these methods for predicting preferences at the item levels (instead of the L3-dish food graph level) which translates to a larger and more sparse graph.</p><h3>Non-Random Walk based Embeddings</h3><p>The Structural Deep Network Embedding (<a href="https://dl.acm.org/doi/10.1145/2939672.2939753">SDNE</a>) method was one of the first Deep Learning approaches (not using random walks and word2vec construct) to learn embeddings. The paper argues that, if embeddings are learned to preserve both 1st and 2nd order proximities of a node, the embedding quality is better. The authors also demonstrate that SDNE outperforms DeepWalk (and other methods) consistently on varied graphs. The SDNE learns embeddings so as to minimize 3 components of the loss function. In comparison to the earlier random walk methods — here we have a specific task to optimize and learn embeddings towards it. The first component is the unsupervised component and this has an encoder-decoder network architecture, which reconstructs the input signal. This reconstruction apparently preserves the 2nd order proximity of a network because the input to it is an adjacency matrix — so inputs for say 2 vertices i and j carry information about their common neighbors. The supervised component is the 2nd component of the loss function and this will preserve the 1st order proximity of the graph. The 3rd and final component is a regularization term. Similar to the random walk approaches, this model does not provide embeddings for new nodes but it scales well for large graphs as it leverages the standard deep learning libraries. There are many hyperparameters in the architecture and the authors present the case for optimizing these for arriving at the best model and this also is our experience. Again, we made the homogeneity assumption here, and in essence, the embeddings that we learned encoded the 1st order proximity (user prefers an item) and the 2nd order proximity (two users are similar for choosing the same item). Overall, like for random-walks methods, what the embeddings learn (either semantics or user behavior-based similarity) is not properly understood.</p><p>The next approach that was explored is <a href="https://arxiv.org/abs/1905.04413">KGNN-LS</a> (Knowledge-aware Graph Neural Networks with Label-Smoothness regularization). A few reasons to explore this were that this is task-specific and developed for recommender systems. When compared to more sophisticated GNN methods that are designed for homogeneous bipartite graphs or user/item-similarity graphs, here the authors investigate GNNs for heterogeneous KGs. The main attractiveness of this algorithm for us was that it offered a way to integrate a knowledge graph for item-level recommendations. As explained in the paper, the objective of this algorithm is that given an interaction matrix in the user-item domain AND a knowledge graph, predict if a user u will have an interest in an item v with which he/she did not interact earlier. To summarize the approach in short: as a first step, the adjacency matrix of the knowledge graph is updated for every user using a GNN like feed-forward approach to give item embeddings. And in the second step, the user embeddings and item embeddings from the first step are combined to get the predicted user-item engagement probability. To implement this algorithm we used the FI (food intelligence) attributes of L3-dish and L8-dish to construct the food knowledge graph for the item entities. Starting with the 3-month training window the<em> user → (number of orders) → item</em> information formed our ratings data. The knowledge graph had 2 relations. First (relation 0) is item_id → fi_L3-dish_id and the second (relation 1) is item_id → fi_L8-dish_id. A schematic of this graph is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eSet0EuPrIv5IP3U" /></figure><h3>GNN based Inductive Embeddings</h3><p>The first inductive model we tried for our use case was GraphSage. Up until now, the models tried and explained in the sections above did not offer any way to generate embeddings for new nodes in an evolving graph without requiring retraining — and this in our case was a shortcoming. The <a href="http://papers.nips.cc/paper/6703-inductive-representation-learning-on-large-graphs.pdf">GraphSAGE</a> algorithm was proposed to address these. The authors, however, do not explicitly suggest if GraphSage can be used for a heterogeneous graph. But since this model can be applied even to graphs that do not have node features, we could extend its use within the homogeneity assumption as explained earlier. The main idea is to transfer the features of neighborhood nodes (like in a Graph Convolution Network) using a stack of layers. For implementation the pytorch model provided within <a href="https://docs.dgl.ai/">DGL</a> was used. So the first step is to translate neighborhood node information which is done via a fully connected deep learning layer with activation and then the next step is to aggregate these transformed features. We can stack more such layers to capture n-hop neighbors. The problem was posed as a link prediction formulation. Once the stacked layers gave features for each node, we minimized the loss to learn the network parameters such that positive samples (connected nodes) were closer in the embedding space and negative samples were further apart in the embedding space. Here node features were not used as they do not make sense under the homogeneity assumption — i.e. the customer and item features are not the same unless any common feature like say FI attributes can be used. Hence we mimic the input features for nodes using an embedding layer with Xavier initialization, whose parameters are also learned along with the other model parameters. The objective function used is such that during training, the embeddings for nodes from positive samples are placed closer and the nodes from negative samples are placed further apart. Negative samples are sampled as node connections that do not exist in the original graph and the negative sample size (size of negative samples per node to consider) was a hyperparameter. This model scales well to large graphs due to sampling during minibatch training.</p><p>The final model included for comparison was the Graph Convolutional Matrix Completion (<a href="https://arxiv.org/abs/1706.02263">GCMC</a>) algorithm — which is a true heterogeneous graph embedding model that also uses node metadata as features when building the inductive model. In this algorithm, we learn embeddings of the same dimensional size for the users and items, i.e. in a common space — and the preference of a user to an item can be computed as the dot product between user and item embeddings. More specifically, for each user, we can assign a learnable vector <strong>𝑢𝑖</strong>, and for each item, we can assign another learnable vector <strong>𝑣𝑗</strong>. Additionally, we also learn a bias for each user 𝛽𝑖 and each item 𝛾𝑗, representing the baseline rating of each user and item. Preference prediction is expressed as:</p><p>𝑟̂ 𝑖,𝑗 = 𝑢⊤𝑖𝑣𝑗 + 𝛽𝑖 + 𝛾𝑗</p><p>For explicit feedback datasets, which is the case when we’re considering the orders data, we try to minimize the difference between prediction and ground truth 𝑟𝑖,𝑗 for all user-item interactions:</p><p>min𝑢,𝑣 ∑(𝑖,𝑗)∈D (𝑟̂𝑖,𝑗 − 𝑟𝑖,𝑗)2</p><p>This is set up via the GNN formulation of stacked graph convolutional layers to compute the embeddings. For applying GCMC to our food domain, 2 aspects were important. First, the node features were transformed in the usual way — i.e. categorical variables were one-hot encoded and continuous variables were normalized. Here, the cardinality of the input features needs to be carefully considered when one-hot encoding as these will influence the batch-size and epochs during training. Secondly, the orders data were considered as an implicit signal for customer preference. That is, the items that a user did not order in the training window did not necessarily constitute the set that the user disliked. Likewise for the items that the user did order — probably the customer only tried out that dish. Hence, we trained the model to consider positive and negative edges in the customer x item graph. This offered a way to predict the ‘likeness’ (or ‘dislikeness’) of an item. This formulation in DGL requires defining a minibatch sampler. For each user-item pair (𝑖,𝑗) that appeared as an interaction (called positive example), we corrupted the item with a randomly-sampled item 𝑗′ (called negative example). The model was trained to distinguish whether the user-item pair was positive or negative using a hinge loss. T</p><h3>Performance Comparisons</h3><p>For demonstration, this section presents a comparison of all the approaches discussed thus far, for one city-wide graph for recommending items to a customer. The need to use this subgraph was because node2vec did not scale well for a larger domain. The metrics comparison in a chart is as shown in the image below. A good way to compare different variants is to look at bars belonging to the same color space (i.e. compare all blues, or compare the greens, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OEXwlS4OixdhWsBw" /></figure><p>For item predictions, the baseline suggests that performance can increase if a larger set of options (say 20 vs 3) are provided. But, a longer list can be available only if the customer has a rich order history. Using the embeddings-based approach then helps generate an expanded set and this is indicative of the possibilities to explore. When compared to L3-dish performances used earlier, the node2vec performance is closer to baseline. The KGNN-LS requires expanding on previous order items and is seen to marginally beat the baseline. When tested with the approach used for node2vec (to find a high bin user and use that user’s preference), the KGNN-LS model is not useful — similar to SDNE. This was because non-random walk based embedding methods gave pure explore options. Hence for these, we used item node embeddings to find similar items for baseline suggestions and expand the prediction list. Our observation with these sets of experiments is that the KGNN-LS model is the most scalable. The graphSAGE and GCMC models are scalable as well, and compared to others they offer better suggestions. The GNN based inductive models have an enhanced capability to also generate suggestions for new nodes. As an estimate, there are around 15 to 20% new nodes on a week-on-week basis, and the GNN methods help increase recommendation coverage to this cohort.</p><p>To conclude, as highlighted in this series of blogs, graph embedding methods present a valuable approach for food recommendation with an explore capability, and their performance levels are close to current models for revisiting customers. The GNN based inductive embeddings also allow for recommending when no prior ordering history is available. We continue to experiment with graph methods for various use cases like search and listing with encouraging results.</p><p><em>Authored by </em><a href="https://www.linkedin.com/in/adityabhakta/"><em>Aditya Bhakta</em></a><em><br>Thanks to Krishna Medikonda, Mohammed Safique, and Jairaj Sathyanarayana for inputs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9655c748b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/enhancing-food-recommendations-using-graph-methods-part-2-9a9655c748b1">Enhancing Food Recommendations using Graph Methods — Part 2</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Food Recommendations using Graph Methods — Part 1]]></title>
            <link>https://medium.com/swiggy-bytes/enhancing-food-recommendations-using-graph-methods-part-1-344dd489b74d?source=rss-5ed08e921701------2</link>
            <guid isPermaLink="false">https://medium.com/p/344dd489b74d</guid>
            <category><![CDATA[graph-algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[swiggy-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aditya Bhakta]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 06:24:29 GMT</pubDate>
            <atom:updated>2021-04-29T06:24:29.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Food Recommendations using Graph Methods — Part 1</h3><p>Swiggy has been developing Food Intelligence (FI) to better understand our catalog, relevant to our consumers. In continuation of an <a href="https://bytes.swiggy.com/decoding-food-intelligence-at-swiggy-5011e21dbc86">earlier blog</a>, we present a series of 2 articles on using FI for recommending food to customers. In this first installment, the problem is explained, and using random walk based graph embedding methods is presented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wz7_7yJxY5FnEvYk1XeLlw.jpeg" /><figcaption><a href="https://www.freepik.com/vectors/food">Food vector created by macrovector</a> — <a href="http://www.freepik.com/">www.freepik.com</a></figcaption></figure><h3>Personalizing Food Recommendation</h3><p>Food discovery, ordering, and delivery is a complex ecosystem considering the high intent and immediacy of the customer demand — her food. How machine learning methods enhance the customer experience define today’s business models. Associating food with its distinctive characteristics helps to personalize for a user with idiosyncratic taste preferences.</p><p>Item recommendations are inherently different in the food domain when compared to familiar instances like movie or book recommendations. Customers having watched and rated a movie or book are rarely interested in seeing the same item recommendation again. With food, however, it is observed that many customers prefer sticking to items they previously ordered and liked. They are at the same time also open to suggestions on similar items. Based on prior ordering history, a user profile can be created to glean what items the user orders. As an obvious approach, the most preferred items can be suggested (our baseline). An improvement over this will be when items similar to these can then be suggested. A pertinent question following this line of thinking then is, how many orders before a user preference is evident? What is the confidence level when a user is new to the platform and has only a few orders to learn from?</p><p>One proposed way to understand consumer behavior is as follows. Consider a 3-month ordering window. Based on the customer orders we can quantify the number of times the customer ordered an item (say, <em>customer A</em> ordered <em>paneer biryani</em> 25 times). Based on this support of every item, a percentile score can be assigned as a proxy to the customer’s preference for this item. A higher score suggests a strong preference by the customer for this item. A strong separation (higher deviation) means higher confidence in using this score (the higher percentile scored item) as a proxy for preference. But if the customer prefers many items equally (say, <em>customer B</em> with a sweet tooth, likes <em>chocolate sundae</em> and <em>chocolate fudge</em> and ordered these 12 times each), these scores will be closer leading to a lower deviation. Customer behavior however differs depending on the total orders. This inference is difficult in the item domain, and so we leverage FI classification to the level-3 of the <a href="https://bytes.swiggy.com/decoding-food-intelligence-at-swiggy-5011e21dbc86">food taxonomy</a> where customer behavior is more deterministic. A representative plot is shown below. Here on the x-axis we have customer orders in the 3-month ordering window and the y-axis for <em>figure a</em> is the standard deviation of preference scores and for <em>figure b</em> it is the unique level-4 selections made by customers. What we can infer from these figures is that customers who order a lot (say 50 orders) prefer between 5 &amp; 10 level-3 items and their score variation is tighter than customers who order less (say 20 orders). The deviation itself varies and if considering the low ordering customer bin, there are many customers who explore a variety of items (and hence lower <em>std</em> score), but there also exist many customers who prefer a particular item (and hence higher <em>std </em>score).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ct_qEh-gvs5i-A3G" /></figure><p>Such consumer behavior essentially makes establishing preferences a difficult task — especially for the segment that does not order frequently. This is also corroborated by the fact that Swiggy’s listing algorithms’ AUC (a feature-driven GBDT) trends linearly with ordering quantity. In this backdrop, approaches that can be used for personalizing food recommendations are discussed in the coming sections</p><p>The problem is formalized as follows. We’ll use the ordering history of the customers in the food taxonomy level-3 (L3) space within a 3-month window as our training set to establish the top-k L3 preferences. Then for a 2-week observation window, we’ll measure the percentage of customers who ordered at least once from their L3 preferences. The endeavor is to understand how graph methods perform for such personalization.</p><h3>The Baseline Model</h3><p>A simple solution is a frequentist one — to identify the L3 dishes that the user would’ve ordered the most and create a user taste profile of, say, the top k dishes. This is a heavy exploit approach as we identify preferences based on the user’s ordering history. This is done for both the train window and test window. Since we’re using an offline evaluation, the frequentist profile for the test window is assumed to be the ground truth and all approaches are measured against it. The main performance metric is the percentage of users in the 2-week test window who ordered from the train window preferences. To ascertain whether the user has indeed ordered, we check for the intersection of the top-k train preferences and top-k test preferences. This is referred to as the hit-rate@k metric.</p><h3>Graph Approaches</h3><p>Considering the above problem formulation, we can probe a different line of thinking whereby we move away from exploiting the customer orders and take a broader view of all the transactions with items on the app in totality. Three main approaches that typically help solve this are collaborative filtering (CF), content-based filtering, and the hybrid method. The hybrid method overcomes the limitations of the other two methods when recommending. This is done using content information about the users and items in the CF-based setup. What content to use is then all about feature engineering. Knowledge graphs also provide a way to generate such content information. At the scale of the problem we’re considering we’ll probe graph methods. The network structure of the ordering ecosystem is evident here. A user U orders an item I. Many other users may also be ordering this item I. These other users may also have ordered from a different set of restaurants and possibly our user U may like those items Ik. But there could be another group of restaurants that serve similar items but none of these users (connected by the thread of item I) ever ordered it. Our user U may still explore such items. Graph methods offer an intuitive capability to model such behaviors at scale.</p><p>Published literature on many approaches to work with graphs exists. A good survey of these is available in <a href="https://arxiv.org/abs/1709.07604">Cai et. al.</a> and <a href="https://arxiv.org/abs/1705.02801">Goyal et. al</a>. These specifically talk about graph embeddings as a way to encode and preserve the structure of the graph in a low dimension. The network described in the food domain above is essentially a heterogeneous graph with nodes and entities of different kinds coexisting. The challenge when embedding the nodes in heterogeneous graphs is how to preserve the global consistency between different types of objects. Should nodes showing similarity of connectivity structure within the same type of node object be embedded together or can different node types be embedded closer than homogenous nodes? Deep learning methods have been proven to be robust and effective and hence widely used for node embeddings — albeit for homogenous graphs.</p><p>To start with then, we make assumptions for our heterogeneous directed graph to be treated as a homogenous undirected graph. Our graph has precisely 2 node types: customer and L3-dish. The edge type is directed: a user [orders] an L3-dish. However, we’ll assume the nodes to be of the same type; and the connection to be undirected. This has implications in the fact that only the structure of the graph is preserved. Other ‘behavior’ of having different types of nodes, and directionality of the edge, and/or other properties (like the price of the order, etc.) are ignored. This is the simplest formulation, we start with embedding using random walks as input to a deep learning model. The following section elaborates on different such approaches.</p><h4>Naive Graph Embedding</h4><p>For a graph, a <em>naive</em> random walk starts at any node, then uses any connected edge (at random) to move to the next node and then steps further till we decide to stop. Thus a random walk starts at a node and has specified steps. A highly connected node can feature in many such walks. Pertaining to our food graph, if the customer nodes to be denoted C and L3-dish nodes to be denoted F, a random walk of say 6 steps of these kinds mostly exists: C1-F1-C1-F2-C2-F3-C3. Analogous to learning word embeddings in a <a href="https://arxiv.org/abs/1301.3781">word2vec</a> formulation, these random walks can be considered as documents to learn from. With a big random walk corpus of 1 MM walks and then tokenizing the nodes, a word2vec model was used to train a 100 dimension vector.</p><p>Unlike with learning word embeddings, here there is not much semantics to the embeddings learned — at least nothing that is tractable. These embeddings can be used in various ways to establish customer preference. The nearest cosine-distance L3 nodes could be 1 way. The approach that worked best though was to transfer preferences in the user space. This is done as follows. We define a high-bin as a user group with 3-month orders &gt;= some order threshold. Say we pick 80 orders. Then the high-bin is a set of all users who ordered more than 80 orders. Now, for every test user, the closest user in the high bin is identified. The approximate nearest neighbor methods are good to use for this scale. The baseline L3-dish preference of this closest high bin user is used as the L3-dish preference for the test user. The rationale to do this is twofold. Firstly, finding nearest nodes in the common space does not inject the explore behavior (because we’re learning embeddings on data for items that the user already ordered and those will be placed closer in the word2vec embedding space). Secondly, the frequentist baseline preference is better performant for the high bin.</p><h4>node2vec Embedding</h4><p>From literature in other domains, we know that <a href="https://arxiv.org/abs/1607.00653">node2vec</a> outperforms other approaches especially in the node classification tasks on many different datasets. Node2vec approach creates a corpus of random walks on a graph by internalizing the flexibility for Depth First Search or Breadth First Search for random walks using 2 hyperparameters — the p &amp; q parameters. Setting these parameters appropriately will help encode the local or global structures of the graph. Node2vec generates a smartly sampled corpus which is then used as inputs for a word2vec model to learn embeddings.</p><h3>Performance comparisons</h3><p>This section shows a few comparisons of the above approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jnDgP9kHqCvlgqk4" /></figure><p><em>Figure a</em> shows a comparison of the hit-rate@3 metric for the 2-week customer cohort for various variants. Along with the baseline, a popularity model is also included. Here the top 3 ordered L3-dishes across users in the train set are considered as the suggestion for each user. Other models include variations of the node2vec around hyperparameters like walk-length (16, 32, 64), train epochs (10, 20, 30), and word2vec context (5, 10, 50). The p and q parameters for node2vec were fixed at the default of 1. It is observed that the performance is dependent on the hyperparameter optimization of node2vec parameters but none of the variants beat the baseline. This is possibly due to the inability of node2vec to suggest exploit options. To test this hypothesis we include 3 more comparisons (the last 3 bars in the figure) where we compare hit rate@6. In two of these variants, we use the 3 baseline L3 suggestions as seed and find in the L3-dish embedding space from the best node2vec variant, the nearby 1 or 2 L3-dish and use those for recommendations. Though this still does not beat the baseline, it narrows the difference. <em>Figure b </em>shows the performance of the models in different customer bins. The naive and node2vec models perform similar to each other but on complementary user groups. Hence here an ensemble of the best node2vec variant and the naive embedding model can outperform the baseline.</p><h3>Conclusion</h3><p>To summarize the discussion till now, we argue that an ensemble of graph embedding models can potentially give better customer food preferences. This would require a better trained node2vec model (hyperparameter optimized) and/or seed preferences from the frequentist approach and/or a better random walk generator (possibly not a fixed p &amp; q parameter for the entire graph as in node2vec). Also, the random walk based training for embeddings is in no way connected to the end task of recommending an L3-dish, so another idea could be to train for a task-relevant loss (something that Graph Neural Networks offer). We continue exploring some of these ideas in our next part.</p><p><em>Authored by Aditya Bhakta<br>Thanks to Krishna Medikonda, Mohammed Safique, and Jairaj Sathyanarayana for inputs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344dd489b74d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/enhancing-food-recommendations-using-graph-methods-part-1-344dd489b74d">Enhancing Food Recommendations using Graph Methods — Part 1</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Food Intelligence at Swiggy]]></title>
            <link>https://medium.com/swiggy-bytes/decoding-food-intelligence-at-swiggy-5011e21dbc86?source=rss-5ed08e921701------2</link>
            <guid isPermaLink="false">https://medium.com/p/5011e21dbc86</guid>
            <category><![CDATA[swiggy-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[foodtech]]></category>
            <category><![CDATA[intelligence]]></category>
            <category><![CDATA[taxonomy]]></category>
            <dc:creator><![CDATA[Aditya Bhakta]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 10:05:16 GMT</pubDate>
            <atom:updated>2020-09-30T18:05:46.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="&lt;a href=”https://www.freepik.com/vectors/food&quot;&gt;Food vector created by katemangostar — www.freepik.com&lt;/a&gt;" src="https://cdn-images-1.medium.com/max/1024/1*tyJ8k8VxK87eMhRBR_5TYA.jpeg" /><figcaption><em>Image credits: </em><a href="https://www.freepik.com/vectors/food"><em>Food vector created by katemangostar</em></a></figcaption></figure><p><em>Co-authored by </em><a href="https://www.linkedin.com/in/krishnamedikonda/"><em>Krishna Medikonda</em></a><em>, Aditya Bhakta, and Mohammed Safique. <br>Special thanks to </em><a href="https://www.linkedin.com/in/jairajs/"><em>Jairaj Sathyanarayana</em></a><em>, </em><a href="https://www.linkedin.com/in/shubhan/"><em>Shubha N</em></a><em>, Mayank Sinha and </em><a href="https://www.linkedin.com/in/mohammed-sufiyan-v-s-b4689a1b8"><em>Sufiyan VS</em></a><em> for inputs and guidance.</em></p><p>Swiggy has been developing Food Intelligence (FI) to better understand our catalog, relevant to our consumers. This article focuses on the basic, building blocks of FI — the<em> taxonomy</em> and<em> item classification</em> — that have helped unlock richer insights on search and personalization.</p><h3>A brief history of our Food Intelligence journey</h3><p>With a pan-India penetration, the current Swiggy menu catalog offers a spread of millions of food items/dishes from thousands of restaurants around the country. Given the unique, personalized, and intimate nature of food, — each item (represented by an item ID), unique to a given restaurant in terms of its preparation style, portion size, serving technique, ingredient mix, spice level, local variation, price, etc. — we treat item IDs as the most atomic element of our catalog. However, from a customer experience POV, it makes more sense to provide and operate at a certain level of abstraction. For instance, in search and recommendations, it is easier to navigate if we organized items at, say, a cuisine level (Mughlai vs. Hyderabadi biryani), or by preparation styles (<em>handi</em> vs. regular), or by course of the meal (starters vs. main-course), etc. To do this, we need to meaningfully understand the contents and attributes of each and every dish and organize this data in a standardized structure.</p><p>When we started, we came across a variety of approaches taken by other organizations and labs in this space. <em>Recipe1M</em>, for example, offers a compilation of over a million web-scraped recipes and images, each classified to standardized food categories and metadata provided in a structured form. ML models can be trained on these to power applications like image captioning, recipe retrieval, etc. Another approach is to create a Food Knowledge Graph (FKG) as undertaken by the <em>Foodome</em> project. All these however over-index on Western dishes and have limited applicability to an Indian food catalog — the likes of what Swiggy deals with. So, we decided to take a ground-up approach to this problem.</p><h3>The Food Taxonomy</h3><p>The first step towards understanding a large catalog is to identify a standardized lexicon — the organization of food. A restaurant’s menu already provides a hierarchical, skeletal taxonomy. For instance, a menu is typically split into categories (like starters, main-course; or breakfast, lunch, dinner, etc.) and subcategories (like rice, breads, etc.). Our idea is to standardize and build on this.</p><p>To map this, here is an example from e-commerce. Consider a top-level category ‘<em>Beauty’</em> (Level-1) which has (among others) two subcategories (Level-2) ‘<em>Hair Care’ </em>and ‘<em>Fragrance’</em>. ‘<em>Hair Care’ </em>has further subcategories (Level-3) like ‘<em>Shampoo’</em>, ‘<em>Conditioners’,</em> and ‘<em>Hair Colors’</em>. These six entities would be the <em>nodes</em> of the taxonomy; and when any product in the catalog is assigned relevant nodes, the levels are called <em>attributes</em> of this product.</p><p>Knowledge from food experts, consultants, chefs and others was required to finalize the granularity of these <em>nodes</em> and <em>attributes</em>. To map, say, a dish called <em>‘pesara pappu payasam</em>‘ one needs the domain knowledge that ‘<em>pesara pappu</em>’ (Telugu for ‘<em>moong dal</em>’) is an ingredient. Attributes that were identified as necessary to describe a dish, like cuisine, preparation style, ingredients were included. Nodes were added to the taxonomy by codifying the knowledge of experts into rules. As an example (Figure-1), nodes ∈ Level-4 could be created based on the key ingredient that identified a dish.</p><p>To better scale this and to ensure objectivity, we set up and evolved an SOP for taxonomy level-creation and annotation. In summary, the FI Ops team takes <em>stratified samples</em> of catalog items (stratified because we want to ensure we cover ‘head’ items that account for a large percentage of sales before dipping into the long-tail of our catalog). Then creates/refines dish nodes in the taxonomy at each attribute level. This is followed by a moderation step to review with chefs and domain experts to address any questions. Currently, we have tens of thousands of dish nodes distributed across various hierarchical attribute levels in the taxonomy. For the sake of simplicity, let’s denote our base dish attributes as <em>Level-3, Level-4, Level-5, and Level-6 </em>(we have more intriguing names internally). The below image shows a snippet of the hierarchical taxonomy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2s7IOPDRwVVUD5gr" /><figcaption>Figure 1. Snippet of the Taxonomy (illustrative only)</figcaption></figure><p>Our objective is to have <em>all</em> the items in our catalog <em>placed</em> into this taxonomy. We use a combination of heuristics and ML models for achieving this. We pose this as a multi-label, multi-class classification problem. We train on the annotated data created by the FI Ops team. The models assign taxonomy nodes to all items with a confidence value. Low confidence predictions are mapped to an ‘<em>others’</em> class. Because the taxonomy is never quite complete, we hope to re-classify these during ongoing iterations.</p><h3>Mapping catalog items to the taxonomy</h3><p>The modeling pipeline to predict labels for a given item consists of several sub-modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2y6LpS-RcAFx_85tmhJrdQ.png" /><figcaption>Figure 2. Inferencing pipeline</figcaption></figure><h4>Pre-processing</h4><p>All items in the catalog have a name, a lot of them have a description and metadata like category (breakfast, main course, desserts, etc.) and subcategory (rice, bread, shakes, etc.). These text fields are usually short texts, on an average of five words in length. These serve as input features. As this textual data is noisy, the first step is preprocessing. Outside of the usual methods (casing, spaces, etc.), we highlight two components below.</p><p>Many food items go by different names in various parts of our country. For example, <em>‘Chicken biryani’</em> is <em>‘kodi biryani’</em> in Andhra/Telangana, <em>‘kozhi biryani’</em> in Tamil Nadu/Kerala and <em>‘murgh biryani’</em> in Hindi speaking states. To capture this regional variation in names we used a corpus of synonyms and typos. In addition to manual seeding, we used Word2Vec models trained on name and descriptions to harvest synonyms (top k nearest words) and typos (with a two edit-distance constraint). These were manually screened for high precision. For example, <em>‘vegg’</em> should not be considered a typo for <em>‘egg’</em>.</p><p>Secondly, special processing to handle <em>‘combo’</em> items was required. For instance, a combo of <em>‘Chicken dum biryani + mutton kebab’</em> with a description <em>‘freshly prepared biryani in basmati rice served with mint raita and mirchi ka salan’</em>, contains mentions of multiple Level-3 nodes. We used regular expressions to extract relevant <em>‘entities’</em> from such text and pass each entity for training/gaining inferences.</p><p>The next step is to convert preprocessed text fields for entities into vectorial input features for the model.</p><h4>Embeddings</h4><p>The initial step to training embeddings is to build the corpus intelligently. Consider that for an item we choose text features — name (<em>t1</em>), description (<em>t2</em>), category (<em>t3</em>), sub-category (<em>t4</em>). A single training document <em>t1+t2+t3+t4 </em>can be used to train embeddings. But we observed that such a combined document had limited capacity to capture relationships between words from features like <em>t1&amp;t3</em> or <em>t1&amp;t4</em>. Based on experimentation, we landed on documents of the form<em> t1+t2, t1+t3, t1+t4, t1+t2+t3+t4</em> as features for each item.</p><p>We then train a skip-gram based FastText model and obtain embeddings for <em>each</em> feature as follows. If <em>(e1, e2, e3, ……, en) ∈ E</em> are the embeddings of the words <em>(w1, w2, w3,….., wn) ∈ W</em> in the feature <em>i </em>with frequencies of words <em>(f1, f2, f3, ……, fn) ∈ F</em>, then the feature embedding is calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*D3gUGgMjJDR8Dx5RB6n7xA.png" /></figure><p>At the end of this step, we have each of the input features as 100-dimensional dense vectors.</p><h4>Models (ML and deterministic)</h4><p>After experimenting with a few architectures, we landed on a shallow NN with four inputs (each 100-d), fully-connected hidden layers and an output layer with softmax activation. We found that <em>not</em> collapsing the four 100-d input vectors into a single 100-d vector (by averaging or otherwise) led to an 11% improvement in F1-score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fLyfNtjl_rC6nk06" /><figcaption>Figure 3. Neural network architecture</figcaption></figure><p>To further improve model performance metrics, we also used hierarchical information as a post-processing step. This helps if any of the models are not able to produce high-quality predictions. For example, if the Level-3 model predictions (say, soup, <em>Figure-1</em>) are with a low probability (say, 0.4) and the Level-4 model predictions (say, chicken soup, Figure-1) with a high probability (say, 0.9) then using the hierarchy where Level-4 is a granular level to level-3, we can assign the Level-3 with higher confidence.</p><p>For a few attributes, we learn a single model to predict the least possible sub-attribute for an item. If Taxonomy attribute Level-8 has ‘x’ nodes, its sub-attribute B (level-9) has ‘y’ nodes and B’s sub-attribute (level-10) has ‘z’ nodes, then we trained a single ML model for ‘x+y+z’ classes, using training samples with the target as the most granular level. For example in Figure-1, the item ‘<em>chicken cream soup’</em> which maps as a ‘<em>non-veg’</em> with the ‘<em>poultry’</em> component being ‘<em>chicken’</em>, we learn a model to predict ‘<em>chicken’</em> as the target class.</p><p>Lastly, for long-tail classes, we typically don’t have enough annotated data in the initial iterations of sampling. In such scenarios, we use <em>deterministic rules</em>. This works on a greedy fuzzy word match in the features passed to the model. For example, for an item <em>‘wheat cheese crackers’</em>, the outputs are — <em>‘crackers’</em>, <em>‘cheese crackers’</em>, <em>‘wheat crackers’</em>, <em>‘wheat cheese crackers’</em>, <em>‘wheat, cheese’</em>.</p><p>The final inference is based on an ensemble of deterministic rules and ML models.</p><h3>Metrics</h3><p>We use coverage (how many items get a non-<em>others</em> prediction) and weighted F1-score to measure the goodness of models. Since the distribution of classes is not uniform and since many of our downstream applications demand high precision, we use the (sample) weighted F1-score.</p><p>The table below shows a representative snapshot of F1-score metrics at the head/torso/tail level grouping of items. This grouping is based on the contribution of items to sales on the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WIlEU1eitNdwVxwS1qwRA.png" /><figcaption>Table 1. A sample snapshot of model metrics</figcaption></figure><h3>Future work — What’s under the cloche</h3><p>We continue to explore approaches like NER, multi-task learning and graph embeddings to improve classification performance while adding more nodes and relationships to the taxonomy. Concurrently, we are also working on using the existing data and relationships to power a Food Knowledge Graph that can power a variety of downstream use-cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5011e21dbc86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/decoding-food-intelligence-at-swiggy-5011e21dbc86">Decoding Food Intelligence at Swiggy</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>