<?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 William Scott on Medium]]></title>
        <description><![CDATA[Stories by William Scott on Medium]]></description>
        <link>https://medium.com/@williamscott701?source=rss-992ed32cb583------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U05XrU32S5QcZ_s2cjUFsQ.jpeg</url>
            <title>Stories by William Scott on Medium</title>
            <link>https://medium.com/@williamscott701?source=rss-992ed32cb583------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:23:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@williamscott701/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[The Exit Poll Puzzle: Insights into Variations in 2024 India Elections]]></title>
            <link>https://williamscott701.medium.com/the-exit-poll-puzzle-insights-into-variations-in-2024-india-elections-191ed3ff36d2?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/191ed3ff36d2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-sampling]]></category>
            <category><![CDATA[bias]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 19:37:03 GMT</pubDate>
            <atom:updated>2024-06-06T19:37:03.204Z</atom:updated>
            <content:encoded><![CDATA[<p>The 2024 Indian general elections were a striking example of exit polls varying significantly from the final results. Exit polls projected a landslide victory for the incumbent Bharatiya Janata Party (BJP) with estimates of 350–370 seats. However, the actual results saw the opposition performing much stronger, with the BJP failing to secure a majority on its own. This disparity begs the question: why do exit polls often differ so much from final election results? Let’s explore this from a statistics perspective, focusing on the challenges and intricacies of exit polling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waGGZTanDRBkZm9s" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>several factors introduce variability and potential bias.</blockquote><h3>Understanding Exit Polls: Methodology and Challenges</h3><p>Exit polls are surveys conducted immediately after voters leave polling stations. The methodology involves sampling a subset of voters to predict the broader voting trends. In theory, this approach should yield accurate predictions, but in practice, several factors introduce variability and potential bias.</p><h3>Margin of Error and Response Rates</h3><p>Like all opinion polls, exit polls inherently include a margin of error. The 1992 UK General Election is a notable example where exit polls incorrectly predicted a hung parliament due to inadequate demographic data and differential response rates, often referred to as the “Shy Tory Factor”.</p><h4>The Shy Voter Phenomenon</h4><p>Some voters may be reluctant to reveal their true voting intention, either due to social desirability bias or fear of judgment. This phenomenon can lead to significant discrepancies between exit polls and actual results.</p><h3>The Indian Context: 2024 Elections</h3><p>In the 2024 Indian general elections, exit polls predicted a dominant victory for the BJP, but the actual results were different. Several factors could have contributed to this discrepancy:</p><ol><li><strong>Demographic Shifts</strong>: Exit polls may have missed shifts in voter demographics and preferences, particularly among younger or first-time voters who might have different priorities.</li><li><strong>Regional Variations</strong>: India’s diverse electorate means that regional variations can significantly impact results. Exit polls might not adequately capture these nuances.</li><li><strong>Postal and Absentee Voting</strong>: Exit polls often miss voters who use postal ballots or other forms of absentee voting. These voters can swing the final results, as seen in other global examples like the 2016 Austrian presidential election.</li></ol><h3>The Distribution Dilemma: A Data Balancing Act</h3><p>In data science, ensuring a balanced distribution of data across various factors is crucial for accurate predictions. In the context of exit polls, this means ensuring that the sample accurately reflects the electorate’s demographic, geographic, and socio-economic diversity.</p><h4>Sampling and Representation</h4><p>Exit polls rely on selecting a representative sample of polling stations and times. Pollsters typically return to the same locations used in previous elections to track changes in voting patterns (swing) and turnout. This method helps in estimating national trends, but it has limitations:</p><ol><li><strong>Sampling Bias</strong>: The chosen polling stations may not perfectly represent the entire electorate. For instance, minority voters in a mixed precinct may behave differently than those in predominantly minority precincts.</li><li><strong>Temporal Variability</strong>: Voting behavior can vary at different times of the day. Early voters might have different preferences compared to those voting later, adding another layer of complexity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1eqQlhYzdvZXZq2_" /><figcaption>Photo by <a href="https://unsplash.com/@hharritt?utm_source=medium&amp;utm_medium=referral">Hunter Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Demographic Distribution</h4><p>Exit polls must account for varying demographics such as age, gender, income, education level, and ethnicity. Each of these factors can significantly influence voting behavior.</p><ul><li><strong>Age</strong>: Younger voters might lean towards progressive candidates, while older voters might prefer conservative options.</li><li><strong>Income and Education</strong>: These factors often correlate with political preferences, with higher income and education levels potentially favoring different candidates than lower income and education levels.</li></ul><h4>Geographic Distribution</h4><p>Urban, suburban, and rural areas often have distinct political leanings. For instance, urban areas might favor more progressive policies, while rural areas might lean towards conservative candidates.</p><h4>Socio-Economic Factors</h4><p>Factors such as employment status, economic stability, and social issues play a crucial role in shaping voter preferences. Exit polls need to capture a cross-section of voters that represents these varying conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lrfJP84zMFPiqflb" /><figcaption>Photo by <a href="https://unsplash.com/@rcsalbum?utm_source=medium&amp;utm_medium=referral">Debashis RC Biswas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Challenge of Balancing Distribution</h3><p>Balancing these distributions in exit polls is a formidable challenge. Pollsters use statistical techniques like weighting to adjust for overrepresented or underrepresented groups. However, these adjustments can introduce their own errors if not done correctly.</p><h4>Simplifying the Complexity</h4><p>Balancing the distribution in exit polls involves:</p><ol><li><strong>Identifying Key Variables</strong>: Determine the key factors that need to be represented accurately.</li><li><strong>Stratified Sampling</strong>: Use stratified sampling techniques to ensure each subgroup is adequately represented.</li><li><strong>Weighting Adjustments</strong>: Apply weighting to adjust for any imbalances in the sample. This involves giving more weight to underrepresented groups and less weight to overrepresented ones.</li><li><strong>Validation</strong>: Continuously validate the sample against known population demographics to ensure accuracy.</li></ol><h4>Technological Interventions</h4><p>Advancements in data collection methods, such as using mobile technology and social media analytics, offer new avenues to enhance the accuracy of exit polls. Machine learning algorithms can help in better weighting and aggregating data, potentially reducing biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jow_mxRP_bRPccci" /><figcaption>Photo by <a href="https://unsplash.com/@eyesofmuk?utm_source=medium&amp;utm_medium=referral">Mukul Kumar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Conclusion: Navigating the Exit Poll Maze</h3><p>Exit polls are invaluable tools for gauging public sentiment during elections, but their accuracy is heavily dependent on the meticulous application of statistical principles. Sampling and response biases, along with the challenges of maintaining balanced distributions, contribute to the variances between exit polls and final results.</p><p>While perfect accuracy may be unattainable, a deeper understanding of these factors can significantly enhance the reliability of exit polls, providing a clearer picture of electoral outcomes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191ed3ff36d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What did Jesus' Parable of Great Banquet mean?]]></title>
            <link>https://williamscott701.medium.com/what-did-jesus-parable-of-great-banquet-mean-682316608233?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/682316608233</guid>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 08:01:48 GMT</pubDate>
            <atom:updated>2022-11-28T08:01:48.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lyx2PhbSwx2Tovo_" /><figcaption>Photo by <a href="https://unsplash.com/@spencerdavis?utm_source=medium&amp;utm_medium=referral">Spencer Davis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>‘I tell you, not one of those who were invited will get a taste of my banquet.’</p><p>Luke records the Parable of the Great Banquet said by Jesus which can be found in the Gospel of Luke 14:15–24. The same parable is recorded by Mattew found in the Gospel of Matthew 12, with drastic differences.</p><p>Although both the written records might be highly accurate, the differences that we find are probably due to the following reasons:</p><ul><li>Firstly, the author’s intention and the intended audience for Matthew and Luke to write their respective gospels are totally different. Matthew wrote his gospel clearly to the Jewish audience being the most Jewish of all the disciples. Whereas Luke has written the gospels Luke and Acts to a person called Theophilus who is assumed to hold a high position in society.</li><li>The intention of Matthew to write the gospel is to explain the ruthless reality to Jews and the intention of Luke while writing the Gospel of Luke is to bring Theophilus who he cares about and respects dearly, to come close to Christ.</li><li>Simply put, Luke and Matthew would have written only parts of what Jesus would have spoken with a pinch of their literary style keeping in mind their agenda.</li></ul><p>This parable according to Luke takes place when Jesus goes to Pharisee’s house to eat. Jesus had all eyes on him (Matthew 14:1) and seeing it as an opportunity to teach them, Jesus healed a sick person on the Sabbath and asks everyone questions to make them think. Then Jesus starts talking about humbleness and serving others, during which he mentions if you serve others, who are poor, crippled, lame and blind, ‘you will be repaid at the resurrection of the righteous’ (Matthew 14:14).</p><p>Catching that exact phrase of Jesus, the person who speaks to Jesus in Matthew 14:15 says that the people attending the banquet in the kingdom of God are blessed (Because they are now giving a banquet for which they intend to be rewarded back in heaven). We need to note here that most of the people in the banquet and the person who spoke to Jesus are Jews. And with their understanding that Jews are the chosen people of God, the person spoke in such a manner. Jesus then says this Parable of Great Banquet to explain about salvation and the chosen people.</p><p>The parable goes as follows: A certain man arranges a banquet for lots of invited guests, and when the banquet is ready, he sent his servants to call the invited guests to the banquet and the invited guests give excuses saying that they have other urgent things to take care of.</p><p>Hearing this, the master got angry and told his servants to bring the people who are blind, crippled, poor and lame, and even wanted his servants to compel others to come and fill the banquet. And the parable ends with the master saying ‘I tell you, not one of those who were invited will get a taste of my banquet.’</p><p>Jesus as in most of his parables is speaking in a metaphorical form. And with the surrounding parables, he is majorly focusing on the teaching about the Kingdom of God.</p><p>So to bring this parable into perspective, the master is God and the banquet is the kingdom of God and the invited guests to the banquet are the chosen people of God — Jews.</p><p>What Jesus is trying to communicate through this parable, to the statement raised by the person in Matthew 14:14 is, it is true that Jews are the ones that are the chosen people of God. But when God sent his Son to them, they rejected him.</p><p>As mentioned in the scriptures ‘His own did not receive Him.’ In this scripture, His own stands for Jews. When Jesus came down to this world and went to His chosen people (Jews) they rejected him to be the Messiah. This rejection is the excuse the invited guests made when they are invited to the banquet when it’s ready.</p><p>Also, the excuses given by the guests are laughable and not realistic. One person says he wants to see the land he bought, how can anyone buy land without seeing it? And who buys oxen without riding it first, and which married couple do not attend public gatherings?</p><p>This shows that even though Jews had all the reasons to believe in the Messiah, they simply chose not to, due to their dependence on worldly things.</p><p>In the end, the master of the house invites all that are not even invited to his banquet. With this illustration, Jesus talks about the extended salvation of God, in which salvation is open to all due to the rejection by Jews (Romans 3:23–24).</p><p>This is simply a prophecy fulfilled mentioned in <em>Hosea 2:23 “I will show my love to the one I called ‘Not my loved one.’ I will say to those called ‘Not my people’, You are my people and they will say, ‘You are my God.’”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=682316608233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PinSage: How Pinterest improved their recommendation system?]]></title>
            <link>https://williamscott701.medium.com/pinsage-how-pinterest-improved-their-recommendation-system-149cb35fdfa5?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/149cb35fdfa5</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pinterest]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 01:34:57 GMT</pubDate>
            <atom:updated>2019-03-25T01:34:57.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>Graph Convolutional Neural Networks for Web-Scale Recommender Systems</h4><p>So finally Pinterest has deployed PinSage as their recommender system and everyone is really excited about the change and the shift in paradigm. But what is it really and how is it related to GraphSAGE?</p><p>If we look at PinSage title it reads as follows</p><blockquote>Graph Convolutional Neural Networks for Web-Scale Recommender Systems</blockquote><p>What are they mentioning in their title? Let me break down the title down into three main keywords</p><ul><li>Graph Convolutional Neural Networks</li><li>Web-Scale</li><li>Recommender System</li></ul><h4>Graph Convolutional Neural Networks</h4><p>Short for GCN, is a model in which both Graphs and Neural Networks comes into picture, already this is getting exciting right? GCN are basically useful for feature representation of nodes in a graph using Neural Networks by taking into consideration of neighbours on k-hops. The convolution mentioned here is not a normal convolution that we see in Deep Learning with images, but the concept is same.</p><h4>Web-Scale Recommender System</h4><p>This is saying that they are developing a GCN for web-scale which means for a large graph and also that it is a recommender system, which means that they are trying to generate some kind of representation of nodes in which they train on one and then they use the trained representation for recommending tasks for unseen nodes.</p><h3>PinSage</h3><p>Let me give a small intro on what PinSage is. PinSage is a Recommender System which is built on top of GraphSAGE, and this develops <strong>high quality node embeddings </strong>using the graph structure and the node feature information. And this model is currently deployed in Pinterest.</p><p>Let me pick a small paragraph from PinSage paper, it reads as follows</p><blockquote>GraphSAGE is an inductive variant of GCNs that we modify to avoid operating on the entire<strong> graph Laplacian. </strong>We fundamentally improve upon GraphSAGE by removing the limitation that the whole graph be stored in GPU memory, using low-latency <strong>random walks </strong>to sample graph neighbourhoods in a <strong>producer-consumer</strong> architecture. — PinSage</blockquote><p>From the above statement what they are saying is that they are just modifying the GraphSAGE which is a variant of GCN and they are modifying in such a way that they need not work on the whole <strong>graph Laplacian</strong>. Laplacian matrix is a matrix in which we take the whole graph into consideration and this is computed by subtracting the degree matrix with the adjacency matrix. And they are also removing the limitation of the whole graph being stored in GPU which happens in the case of GraphSAGE, and to do this they are using a producer consumer architecture which we will discuss below.</p><p>Laplacian Matrix = Degree Matrix — Adjacency Matrix</p><h3>GraphSAGE</h3><p>As they are talking on and on about GraphSAGE let me just give a small into on it.</p><ul><li><strong>Unsupervised Algorithm: </strong>for starters, graphSage is an unsupervised algorithm, which means we don’t have any sort of labels.</li><li><strong>Sampling Neighbours: </strong>when computing for a particular node u, we need to also consider the set of its neighbours. When all the neighbours are considered, there’s a chance that we are retrieving a lot of nodes which just is computationally very expensive. So to avoid this, only the top t neighbours are sampled from the neighbourhood.</li><li><strong>Aggregator: </strong>We got all of the neighbours in the above step, what an aggregator does is that it will aggregate all of the sampled neighbourhood information to a particular one dimensional embedding.</li><li><strong>Unseen Data:</strong> GraphSAGE is mainly motived to work on unseen data, and for any unseen data they take in attributes such as text, node profile information, node degrees to generate the initial embeddings.</li><li><strong>Activation:</strong> Sigmoid. No comments!</li></ul><h4>Algorithm</h4><p>Now that we saw few of the important points, let us go through their algorithm a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48ON2Zu-5TVAW2xq1fkJGg.png" /></figure><p>Fret not! i will explain the algorithm in as simple terms as possible. But just follow the notations i highlight.</p><p><strong><em>V</em></strong><em> </em>is a collection of all nodes that are there. <strong><em>x(v)</em> </strong>is the initial input embedding that we generate for every node (unseen). <strong><em>h(v)</em></strong> is always considered as the current embedding, but as we have different layers in this module, so <strong><em>h(v) </em></strong>is going to be <strong><em>h(v, k) </em></strong>where k is the layers.</p><p>In line 1, we take all the nodes representation <strong><em>x(v) </em></strong>for all nodes <strong><em>v </em></strong>in collection <strong><em>V</em></strong>, then we iterate over all the layers (depth) in the next step.</p><p>We Iterate for all nodes <strong><em>v</em></strong> (line 3), and we aggregate (we are going to discuss later on what kind of aggregation function they are using) all of the nodes information (line 4) and pass them along to a Layer in the neural network which will generate the embeddings. We repeat this for all the depths<strong><em> K</em></strong>. Here depth came into picture because, when we take only the one-hop of a nodes, we just consider the immediate neighbours. If we consider two-hops of a nodes, we gain the information of node <strong>neighbours</strong> and <strong>neighbours</strong> neighbours. In this way when we do k-hops, we get all the k depth nodes information embedded by the aggregator gaining more neighbourhood information. At the end of the for loop, there is normalisation so that it will be better for computation in the neural network layer. Finally, the embeddings will be in the final layer <strong><em>h(v, K)</em></strong>, and this is copied to the vector representation.</p><p>If you clearly see the steps 1 and 3, they are computing on the whole set of nodes that they have, and this is the exact thing that PinSage is trying to avoid.</p><h4>Loss Function:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNjmw9edIWBT0lRSsDpeHw.png" /></figure><p>Again follow my notations clearly. <strong><em>z(u)</em></strong> is the current embedding of node for which we are computing the loss function. <strong><em>z(v) </em></strong>are the relevant examples and <strong><em>z(vn)</em></strong> are the non relevant examples. and <strong><em>Q</em></strong> is the number of the non relevant examples.</p><p>Whoooaaah… hang on! we just discussed that this is <strong>unsupervised</strong> data right? then from where on earth did we get the relevant and non relevant information? Let me explain, they used a concept called <strong>Random Walk. </strong>Its a technique in which a random walk takes place from the node u for a particular depth k, and all of the nodes that appear in the random walk are <strong>considered</strong> to be closer to u, and they are taken as relevant examples and the rest as the non relevant examples.</p><h3>PinSage</h3><p>Now that we know GraphSAGE a bit, we can understand PinSage much easier as this is very similar to GraphSAGE.</p><ul><li>PinSage is a <strong>Supervised</strong> algorithm.</li><li><strong>Convolution:</strong> This module is same as aggregator in GraphSage, this gets the neighbourhood information into a single column vector representation.</li><li><strong>Stacking Convolutions:</strong> Just like GraphSAGE, this also goes on for multiple hops (depths), by going deeper the node learning becomes better by gaining more information from neighbours and their neighbours</li><li>Pinterest is a platform in which they Share and Organise images. Images are considered as <strong>Pins</strong>. And users can stack a collection of images in albums, which is considered as a board. Users are assumed to stack similar images in albums (<strong>boards</strong>). Finally, PinSage does a very smart thing to simplify the graph here, they form a <strong>Bipartite Graph of pins — boards</strong>. this works for this situation because there is no pin — pin and board — board relation.</li><li>There are almost 2 billion pins and 1 billion boards, and both of those are considered as node, so totally <strong>3 billion nodes</strong> and there are around <strong>18 billion edges.</strong></li></ul><h4>Challenges</h4><p>Although GraphSAGE algorithm would have worked in this scenario too, but they will have to compute on the whole graph Laplacian which is computationally very expensive, and Pinterst has billions of nodes and edges, and also they need to do some kinds of optimisations during the run time, for faster computations.</p><h4>Insights</h4><ul><li><strong>On-the-fly convolutions: </strong>They are sampling the neighbourhood of nodes on demand.</li><li><strong>Producer consumer mini-batch construction: </strong>Making use of CPU and GPU efficiently by assigning them different tasks.</li><li><strong>Efficient MapReduce Inference:</strong> During computation of convolutions (aggregations) we may have to compute the convolutions repeatedly, and this repetition of multiple tasks are minimised by the MapReduce.</li><li><strong>Random Walks:</strong> They use a random walk process to sample the neighbourhood</li><li><strong>Importance Pooling:</strong> They are computing an importance score of each and every neighbour, with the help of random walk. (not done by GraphSAGE)</li><li><strong>Curriculum Training:</strong> They feed harder and harder examples each time to the model to make it more robust and generalise for hard-negative examples. (not done by GraphSAGE)</li></ul><h4>Algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8V6HwNSHsij0j8tu8W4VqA.png" /></figure><p>Nothing to worry, as always, just follow my notations.<strong><em> h(v)</em></strong> is always the current embeddings, <strong><em>N(u)</em></strong> gives the sampled neighbourhood of <strong><em>u</em></strong>, <strong><em>alpha</em></strong> is importance factor of all of the neighbours which we compute during the random walk. <strong><em>gamma</em></strong> is an aggregator function. <strong><em>n(u)</em></strong> in first line holds the neighbourhood information of <strong><em>u</em></strong>. <strong><em>W</em></strong>, <strong><em>Q</em></strong> are Weights, and <strong><em>w</em></strong>, <strong><em>q</em></strong> are bias.</p><p>If you are clear with the notations, you can go head. In line 1, we are getting all of the neighbourhood information into <strong><em>n(u)</em></strong>. We take all of the neighbours embeddings <strong><em>h(v)</em></strong> and pass it to a layer in the neural network and then apply the importance factor <strong><em>alpha</em></strong>, and aggregate the whole matrix by taking column wise average or mean. Now <strong><em>n(u) </em></strong>in line one has the whole neighbourhood information. In line 2, we concatenate the neighbourhood information with the current representation <strong><em>z(u)</em></strong>. The concatenation is done instead of average or mean just due to the computational efficiency.<strong><em> z(u)</em></strong> is same as <strong><em>h(u)</em></strong> as both are current node embeddings of <strong><em>u</em></strong>. After concatenation, this is again sent to another layer in the neural network. and the output will be the new embeddings of <strong><em>u</em></strong>. In the third line, later we normalise the data using l2 normalisation just so that it will help in the neural network computation. I will explain the above algorithm along with the dimensions in the below section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLrrnAeUHIrONpY-hhc_WQ.gif" /></figure><p>Each node is considered to be a dimension of the m. It’s mentioned in the paper that they want same number of neurons <strong><em>(d)</em></strong> for all the hidden layers for simplicity. But we can consider this as m, as we will be passing the output as the input in the next iteration.</p><p>Now coming to dimensions, every node in the graph has an embedding size of <strong><em>m</em></strong>. So from <strong><em>n</em></strong> neighbours of our node <strong><em>u</em></strong>, we are going to sample <strong><em>t</em></strong> nodes (select <strong><em>t</em></strong> nodes from <strong><em>n</em></strong> such that <strong><em>t&lt;n</em></strong>) now we know the dimension of each node which is <strong><em>m</em></strong>. So the dimension of one neighbour is <strong><em>1*m</em></strong>. And if there are <strong><em>t</em></strong> such neighbours, the dimension of the whole neighbours is considered as <strong><em>t*m</em></strong>. Now we are sending this to a layer in the neural network with weights <strong><em>Q</em></strong> and bias <strong><em>q</em></strong>. It is mentioned in the paper that all the layers in the neural network are fixed to have the same number of neurons <strong><em>d</em></strong>. And we also consider that we will be sending the output dimensions of the layers as input again. So We can conclude that each layer can have <strong><em>m</em></strong> dimension instead. The number of parameters that will be there for the <strong><em>Q</em></strong> matrix will be <strong><em>m*m</em></strong> as we will have to multiply <strong><em>t*m</em></strong> and <strong><em>m*1</em></strong> matrices. And the final output dimensional vector is <strong><em>t*m</em></strong> which is the whole neighbourhood processed matrix. Now we will be sending this to the aggregator function which will take the mean or average of all the columns of the neighbourhood processed matrix. We also have an importance factor for each matrix using which we will multiply the corresponding row value (embedding) of the neighbourhood matrix. Now after applying the aggregating function along with the importance score alpha, we will get <strong><em>nu</em></strong> which is the whole neighbourhood representation, and this will be of dimension <strong><em>1*m</em></strong>.</p><p>Now, the neighbourhood representation is concatenated with the current embedding of <strong><em>u</em></strong>. The current embedding is always <strong><em>hu</em></strong> but as we are considering <strong><em>zu</em></strong> here, that also is the same. The concatenation is done instead of aggregation function only to save little computation. After the concatenation, the output dimension will be <strong><em>1*2m</em></strong>, as we will be concatenation the neighbourhood which is of <strong><em>1*m</em></strong> and the current representation which is of <strong><em>1*m </em></strong><em>dimensions respectively</em>.</p><p>This concatenated value is now sent to another layer in the neural network <strong><em>W</em></strong> with the number of neurons <strong><em>m</em></strong>. So the number of parameters that this will have is <strong><em>2m*m</em></strong>. And after the layer computation we will get an output embedding <strong><em>1*m</em></strong>, which is the new embedding of <strong><em>u</em></strong>. This is just normalised using l2 normalisation so that it could help in the computation and so that it won’t let the neural network values explode.</p><h3>Neighbourhood sampling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*MpVUSeILstLzh8Z2r3QUlw.gif" /></figure><p>We were discussing in the above section that we want to sample the neighbourhood of <strong><em>u</em></strong>. But how do we do it?</p><p>We simply consider the neighbourhood nodes which has high influence on <strong><em>u</em></strong>. Again how do we decide this?</p><p>We perform random walks on <strong><em>u</em></strong>. And during this random walk process, we will take the visit count of each node and normalise using the l1 normalisations and from this we will take top <strong><em>t</em></strong> valued nodes. Fixing that number of sampling <strong><em>t</em></strong>, helps during the computation and also helps in estimating the computational resource needed on an estimate.</p><h3>Calculating Importance Factor</h3><p>We know that alpha is the importance factor. How do we calculate it?</p><p>Remember the random walk we did above to find the importance of a neighbour to <strong><em>u</em></strong>? We take the similarity in the random walk. For the above given example, importance of the neighbour is taken as the intersection of the parent random walk and the neighbour random walk. Assuming that the red colour is the random walk of u and black is the random walk of neighbour n1, we take their intersection part of the ellipses.</p><h3>Stacking Convolutions</h3><p>What does this even mean? Just now we have learnt what a convolution is. A single convolution learns the information from its neighbours. But when we stack such convolutions together, the model will tend to learn the information of its <strong>neighbours</strong> and the information of <strong>neighbours</strong> neighbours. Doing this will make the model gain more information by looking at its neighbours. And each layer of convolution always depends on its previous layer. So <strong><em>k</em></strong> always depends on <strong><em>k-1</em></strong> where as <strong><em>k</em></strong> is the depth. Each layer has two hidden layers of Neural Network, all the layers in the same same depth share weights and bias. <strong><em>W, w, Q, q</em></strong> is shared among nodes but differ among layers. So they can be rewritten as <strong><em>W(k), w(k), Q(k), q(k)</em></strong> finally after the final output from the convolution, there is another common layer in the architecture and this layer of neurons share parameters throughout the model.</p><h3>Minibatch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*VZsjCliUfgRM7lWxDyHRVQ.png" /></figure><p>This algorithm gives the over all picture of how the training happens. As always parameters first. <strong><em>V</em></strong> is the set of all nodes.<strong><em> M</em></strong> is the subset nodes of <strong><em>V</em></strong>. <strong><em>S</em></strong> is the set of samples of nodes (the selected nodes from the neighbourhood). <strong><em>K</em></strong> is the depth. <strong><em>x(u)</em></strong> is the initial embedding of <strong><em>u</em></strong>.</p><p>There are two major parts for this algorithm, first is where it samples the neighbourhood, and second is where it computes the new embedding by convolutions. <strong><em>S</em></strong> holds the nodes, not their embeddings. In the first line, the the subset nodes <strong><em>M</em></strong> from <strong><em>V</em></strong> is copied to <strong><em>S(K)</em></strong>, this is the last layer of sampling. Now we iterate in the decreasing order of depth, during this loop for every depth <strong><em>S(k)</em></strong> we copy the nodes <strong><em>S(k-1)</em></strong>and their neighbourhoods <strong><em>N(u)</em></strong> nodes from their next layer. In line 3, we copy the nodes to layer <strong><em>k-1</em></strong> and in line 5 we copy the neighbours information also to layer k-1. Finally <strong><em>S(0)</em></strong> will hold the nodes of <strong><em>M</em></strong> and its neighbours till <strong>k-hop</strong>.</p><p>For all the nodes which are in <strong><em>S(0)</em></strong>, we take the initial embeddings and store them in <strong><em>h(u,0)</em></strong>. Now iterating in an increasing order, for every node in layer <strong><em>S(k)</em></strong> (line 10), we sample the nodes from the previous layer which are neighbours of <strong><em>v</em></strong> (line 11). Now we perform the convolve operation (the algorithm we saw first) on the neighbourhood nodes and the current representation of <strong><em>u</em></strong> in its previous layer, which gives the current embeddings of <strong><em>h(u, k)</em></strong> node <strong><em>u</em></strong> and depth <strong><em>k</em></strong>. Finally, we will have all of the embeddings in the Final Layer of <strong><em>h(u, K)</em></strong>. We pass this through another layer of neural network which shares parameters <strong><em>G2</em></strong>, <strong><em>G1</em></strong>, <strong><em>g</em></strong>. where <strong><em>G1, g</em></strong> are weights and bias respectively.</p><h4>Loss Function</h4><p>As we discussed earlier, PinSage is a supervised algorithm. So it assumes labelled data <strong><em>(q, i) -&gt; L</em></strong> query item pair, relating to label<strong><em> L</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_OncwWqjr4K4LHjxHX7VQ.png" /></figure><p>This is a maximum margin loss. <strong><em>z(q)</em></strong> is the embedding of q<strong><em>, z(i)</em></strong> are the relevant examples and <strong><em>z(nk)</em></strong> are the non relevant examples. delta is the hyper parameter for the margin. This loss function maximises the inner product of positive examples. If <strong><em>z(nk)</em></strong> is more, then there will be a positive value, and taking the max will return a positive vale denoting that the loss is high. And if <strong><em>z(i)</em></strong> is high, then the value will be negative and taking the max will return 0 denoting that there is no loss.</p><h4>Sampling Negative Items</h4><p>In the above section we discussed that <strong><em>z(nk)</em></strong> are negative items. Now how do we take the non negative items? If we take all of the non relevant as negative samples, then the model will not generalise and wont predict the near correct results (results which are close enough).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkzSwlS1wkY_TseHXp2K-g.png" /></figure><p>500 negative examples are sampled from each mini-batch. Have a look at the above image, <strong><em>Query</em></strong> is the query that they give and<strong><em> positive example</em></strong> is the positive results that they get from the model, and <strong><em>Random Negative</em></strong> is the negative example that is selected from non positive items, <strong><em>Hard Negative</em></strong> is the negative example which is not completely positive but not completely negative. So instead, they ranked the similarity of results and pick few negatives from the rank 2000–5000 and again trained on those examples so that the model will generalise better for near correct results. This is called curriculum training, in which they train on harder and harder examples in each instance.</p><h4>How do we decide the First Embeddings?</h4><p>Image and Annotations information is considered for every pin. Every image is passed to VGG16 and the embeddings from the 10th layer is extracted which gives 4096 dimensional embeddings. And word2vec is used to generate word embeddings. They merge both the embeddings to generate the initial embeddings.</p><h4>Final Notes</h4><ul><li>To make the computations better, they split data to multiple mini-bathes and send them to different GPU and take back the output from them and fuse together. Doing this, multiple GPU’s can used simultaneously reducing the runtime.</li><li><strong>Producer Consumer:</strong> All of the graph is stored in CPU, and whenever GPU needs a nodes information and node’s neighbours, GPU instructs the CPU, and CPU generates the information of neighbourhood embeddings and then GPU will do the Convolution operation. This kind of architecture helps the maximum utilisation of both CPU and GPU</li><li>CPU — (extracting features, re-indexing, negative sampling)</li><li>GPU — (Model Computations)</li><li>For finding similarity of two embeddings, they perform KNN which is K-Nearest Neighbours.</li></ul><h4>Evaluation</h4><ul><li>Offline Metrics — MRR (Mean Reciprocal Rank): Rank which will be reciprocated and taken mean of.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*Ffogcv11rQosZTDpHXdWfw.png" /></figure><ul><li>Controlled User Studies: Show the outputs to experts to judge if the generated recommendation are relevant or not.</li><li>A/B Test: Show 50% of Pinterest users the recommendations from model A, and another 50% from model B for the same query. They then check the user interactions or activities on it. A and B are the models that generate the embeddings which produce slightly different results. This is checked by actually deploying in Pinterest.</li></ul><h4>Results</h4><p>From the results table in the paper, it is considered a win, if user selects the recommendation fo PinSage and a loose if the user selects the opponent and draw if none is selected. And the fraction of wins is among the wins-lose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*uRKiJ-eT8DCGMMhXZrCQFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*cHfkC9q-0AHeu0--hrM_9Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=149cb35fdfa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network observations wit]]></title>
            <link>https://williamscott701.medium.com/neural-network-observations-wit-e16ac56fe1b?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/e16ac56fe1b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 00:46:41 GMT</pubDate>
            <atom:updated>2019-03-01T00:46:41.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>Neural Network observations with change in parameters</h3><p>Implementing Neural Networks and checking how the accuracy changes upon the change of parameters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mtJwNNV0ALYVbYqg" /><figcaption>Photo by <a href="https://unsplash.com/@the_roaming_platypus?utm_source=medium&amp;utm_medium=referral">The Roaming Platypus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>find the code <a href="https://github.com/williamscott701/Machine-Learning/tree/master/3.%20Neural%20Networks">here</a>.</p><h3><strong>Question 1</strong></h3><h4>Self-Implemented NN:</h4><p>Accuracy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*rfhPoaOio6vxEw13a9StpA.png" /></figure><p><strong>Parameter Values used for sigmoid:</strong></p><p>_lambda = 0.01</p><p>lr = 1</p><p><strong>Parameter values used for relu:</strong></p><p>_lambda = 1</p><p>lr = 0.01</p><p>for relu, the most problematic things are that the values tend to go to nan, due to 2 main reasons</p><ul><li>-1 in exponential value</li><li>0 divided by zero in sigmoid</li></ul><p>to handle this,</p><ul><li>I used a little normalization in softmax by subtracting the max value with the whole array.</li><li>And divided the whole randomly generated weight matrix with the square root of the dimensions.</li></ul><h4>Architecture:</h4><ul><li>The notations are followed from Andrew NG in his youtube videos.</li><li>the input is considered as the output from the first layer</li><li>and then at every layer there are two different processes that has to be done</li><li>calculating the hypothesis</li><li>passing through the activation function</li><li>the output from the activation is considered as the output of that particular layer</li><li>the activation functions used are relu and sigmoid</li><li>softmax is the last layer of the architecture</li><li>I used cross entropy and its derivative for calculating the losses</li></ul><h4>Overfit and Underfit:</h4><ul><li>We say that there is overfitting when the performance on test set is much lower than the performance on train set</li><li>But in this case the overfit doesn’t seem to happen</li><li>We always have an option of early stopping in which, we can stop the iterations when the error seems to reduce.</li><li>Underfit seems to happene for few plots, in which the accuracy continues to reduce</li></ul><h4><strong>Sigmoid (1 Hidden Layer)</strong></h4><p>Train — (2500 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*yHFXb9uNuqGyeV_48gU2Gw.png" /></figure><h4><strong>Sigmoid (1 Hidden Layer)</strong></h4><p>Test — (2500 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*tVE0nI8sNBkcqjOLKTpe5w.png" /></figure><p><strong>Observations:</strong></p><ul><li>The accuracy was pretty impressive.</li><li>More number of iterations are chosen by reducing the learning rate.</li><li>This is done to avoid the nan values</li><li>Stable softmax is used to normalize the values</li><li>I implemented preprocessing by sklearn for the values to normalize a little.</li><li>The last layer is considered to be softmax</li><li>Used sigmoid as the activation funciton</li></ul><h4><strong>Sigmoid (3 Hidden Layer)</strong></h4><p>Train — (1000 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*Xjf-auPYelZfCCG9G7QI_g.png" /></figure><h4><strong>Sigmoid (3 Hidden Layer)</strong></h4><p>Test — (1000 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*KQahWQCIj-7Po562LGQKCA.png" /></figure><p><strong>Observations</strong></p><ul><li>This seems to be a case of vanishing gradient.</li><li>The values tend to be constant, which changes from 43 to 51 respectively.</li><li>No actual learning is done in this case</li><li>In the three hidden layer, the last layer is considered as softmax</li></ul><h4><strong>Relu (1 Hidden Layer)</strong></h4><p>Train — (4000 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*oEo7kdC83DErJazhNVomGA.png" /></figure><h4><strong>Relu (1 Hidden Layer)</strong></h4><p>Test — (4000 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*87F5cYXZJ36Q-faWKgHa6Q.png" /></figure><p><strong>Observations</strong>:</p><ul><li>Relu seems to perform same as the softmax for 1 hidden layer</li><li>The activation function is used as relu.</li><li>In the back propogation, we used the derivative of the relu</li></ul><h4><strong>Relu (3 Hidden Layer)</strong></h4><p>Train — (2500 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*JgcfZ-NYPuk5ue3J4bhMUQ.png" /></figure><h4><strong>Relu (3 Hidden Layer)</strong></h4><p>Test — (2500 Iterations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*vD45OVe7U48rw4PnrSMH4w.png" /></figure><p><strong>Observations</strong>:</p><ul><li>3 hidden layers again seems to be the case of vanishing gradient, as the accuracy is not above average on both training and testing.</li><li>Initially the value is totally 0, and then from there the value raises to a constant value</li></ul><h3><strong>1 (d): NN using sklearn</strong></h3><p>Classifier:</p><p>MLPClassifier(activation=’logistic’, solver=’lbfgs’, alpha=1e-5, hidden_layer_sizes=(100), random_state=44)</p><p>Train test split: (size=0.33, random_state=42)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*-6sFk-A0AvxEAb_gzVL71A.png" /></figure><p><strong>Observations</strong>:</p><ul><li>Using lbfgs solver the accuracy is pretty good, but sgd is not good for 3 hidden layers</li><li>The number of iterations needed are very less 3 or 5</li></ul><h3><strong>Question 2:</strong></h3><p><strong>Observations</strong>:</p><ul><li>The given images are RBG valued images and we have to extract the features from it so that we can feed it to the SVM</li><li>I tried using PCA so that I can reduce the dimensionally</li><li>The given data is a pre-trained data</li><li>The last layer will return 1000 features which we will use for the training process</li></ul><p><strong>Train Accuracy:</strong></p><p>For 300–0.65%, For 1000–83%</p><p><strong>Test Accuracy:</strong></p><p>For 300–0.65%, For 1000–83%</p><p><strong>Confusion Matrix (300):</strong></p><p>[[ 54, 95],</p><p>[ 4, 147]]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*RLHABFKQ6HhBdVj4sqX_Ug.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e16ac56fe1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree vs Random Forest]]></title>
            <link>https://williamscott701.medium.com/decision-tree-vs-random-forest-dcc71f523867?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcc71f523867</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 00:30:53 GMT</pubDate>
            <atom:updated>2019-03-01T00:30:53.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8oxJkqU0RZCdkP3j" /><figcaption>Photo by <a href="https://unsplash.com/@dinoseus?utm_source=medium&amp;utm_medium=referral">Aldino Hartan Putra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This blog is about the results and observations of the works in Decision Tree and Random Forest.</p><p><a href="https://github.com/williamscott701/Machine-Learning/blob/master/4.%20Decision%20Tree%20%26%20Random%20Forest/Decision%20Tree%20and%20Random%20Forest.ipynb">Click here</a> to check the code and the problem statement.</p><h3><strong><em>Part A:</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*s5cKeL_TxIdhm20j6RiJFg.png" /></figure><p>The accuracies of both the models seem to be pretty close. But the accuracy on the random forest is little better than the decision tree. The speed on the decision tree seems to be little better as the random forest has to calculate for multiple trees.</p><h3><strong><em>Part B:</em></strong></h3><p>Mode of Selection of values:</p><p>The values are selected just at the point where the train accuracy increases and test accuracy is decreasing. This is shows overfit and I tried to use the values that doesn’t make the model overfit.</p><p><strong>DecisionTreeClassifier(min_samples_split=0.1, min_samples_leaf=19, max_depth=5)</strong></p><p><strong>max_depth:</strong> range(1, 50)</p><p><strong>selected:</strong> 5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*ccBnqQSyjCOSsTAeJaZ-Pw.png" /></figure><p><strong>min_samples_leaf:</strong> range(1, 50)</p><p><strong>selected:</strong> 19</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*QBT0UctJKipBl9-eZDZ8Hw.png" /></figure><p><strong>min_samples_split:</strong> [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]</p><p><strong>selected: </strong>0.1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*63aAQzzRXsVJ2KB6uL7UzA.png" /></figure><p><strong>RandomForestClassifier( n_estimators=8 , min_samples_leaf = 3, max_depth = 10, random_state = None)</strong></p><p><strong>max_depth:</strong> range(1, 50)</p><p><strong>selected:</strong> 10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*95BkuVVED7xUSvlDmKbrGg.png" /></figure><p><strong>n_estimators:</strong> range(1, 50)</p><p><strong>selected</strong>: 8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*isuf0YXYf352VNHm1nvjnw.png" /></figure><p><strong>min_samples_leaf:</strong> range(1, 50)</p><p><strong>selected:</strong> 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*ugH_SYEc8-PnTDmefZM7eQ.png" /></figure><p><strong>max_features:</strong> range(1, 20)</p><p><strong>selected:</strong> None</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*PpCvObElJwED85VHEglsIA.png" /></figure><p><strong>min_samples_split:</strong> np.linspace(0.1,0.9,11)</p><p><strong>selected:</strong> None (Not necessary for this)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*P1ibgw3fSACchEZKrn1eZQ.png" /></figure><h3><strong><em>Part C:</em></strong></h3><h4><strong>Decision Tree:</strong></h4><p>I used cross-validation on the dataset and found that there is not much variance in the results compared to my original model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*p3owkfc-aAn53YGPoaOL1g.png" /></figure><h4><strong>Random Forest:</strong></h4><p>I used cross-validation on the dataset and found that there is not much variance in the results compared to my original model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*vLBKWxYoc1X1im35IxUd7g.png" /></figure><h3><strong><em>Part D:</em></strong></h3><p>KFold is used to generate 5 folds and for each fold the error on the validation is stored along with the model. And I am testing the variance of both decision tree and random forest. And as shown in the last the variance of decision tree is greater than that of random forest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*hgtbImlXO15lQact5rskZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*IEyjok7qJjd--KuetyMaPw.png" /></figure><h3><strong><em>Part E:</em></strong></h3><p>I loaded the serialised data using joblib and I used the same random state to get the same split on the dataset for test and train. And I predicted the results with the test. The results are same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*OVTMG3vVYMZ_xLVnDzRpew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcc71f523867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TF-IDF for Document Ranking from scratch in python on real world dataset.]]></title>
            <link>https://medium.com/data-science/tf-idf-for-document-ranking-from-scratch-in-python-on-real-world-dataset-796d339a4089?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/796d339a4089</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 10:01:18 GMT</pubDate>
            <atom:updated>2021-09-26T19:15:07.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>TF-IDF from scratch in python on a real-world dataset.</h3><h3>Table of Contents:</h3><ul><li>What is TF-IDF?</li><li>Preprocessing data.</li><li>Weights to title and body.</li><li>Document retrieval using TF-IDF <strong>matching score.</strong></li><li>Document retrieval using TF-IDF <strong>cosine similarity.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WapTyrci2fL-8_um" /><figcaption>Photo by <a href="https://unsplash.com/@sanwaldeen_sink?utm_source=medium&amp;utm_medium=referral">Sanwal Deen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction: TF-IDF</h3><p>TF-IDF stands for <strong>“Term Frequency — Inverse Document Frequency”</strong>. This is a technique to quantify words in a set of documents. We generally compute a score for each word to signify its importance in the document and corpus. This method is a widely used technique in Information Retrieval and Text Mining.</p><p>If I give you a sentence for example “This building is so tall”. It&#39;s easy for us to understand the sentence as we know the semantics of the words and the sentence. But how can any program (eg: python) interpret this sentence? It is easier for any programming language to understand textual data in the form of numerical value. So, for this reason, we need to vectorize all of the text so that it is better represented.</p><p>By vectorizing the documents we can further perform multiple tasks such as finding the relevant documents, ranking, clustering, etc. This exact technique is used when you perform a google search (now they are updated to newer transformer techniques). The web pages are called documents and the search text with which you search is called a query. The search engine maintains a fixed representation of all the documents. When you search with a query, the search engine will find the relevance of the query with all of the documents, ranks them in the order of relevance and shows you the top k documents. All of this process is done using the vectorized form of query and documents.</p><p>Now coming back to our TF-IDF,</p><p>TF-IDF = Term Frequency (TF) * Inverse Document Frequency (IDF)</p><h4>Terminology</h4><ul><li>t — term (word)</li><li>d — document (set of words)</li><li>N — count of corpus</li><li>corpus — the total document set</li></ul><h4><strong>Term Frequency</strong></h4><p>This measures the frequency of a word in a document. This highly depends on the length of the document and the generality of the word, for example, a very common word such as “was”<strong> </strong>can appear multiple times in a document. But if we take two documents with 100 words and 10,000 words respectively, there is a high probability that the common word “was” is present more in the 10,000 worded document. But we cannot say that the longer document is more important than the shorter document. For this exact reason, we perform normalization on the frequency value, we divide the frequency with the total number of words in the document.</p><p>Recall that we need to finally vectorize the document. When we plan to vectorize documents, we cannot just consider the words that are present in that particular document. If we do that, then the vector length will be different for both the documents, and it will not be feasible to compute the similarity. So, what we do is that we vectorize the documents on the <strong>vocab</strong>. Vocab is the list of all possible worlds in the corpus.</p><p>We need the word counts of all the vocab words and the length of the document to compute TF. In case the term doesn’t exist in a particular document, that particular TF value will be 0 for that particular document. In an extreme case, if all the words in the document are the same, then TF will be 1. The final value of the normalised TF value will be in the range of [0 to 1]. 0, 1 inclusive.</p><p>TF is individual to each document and word, hence we can formulate TF as follows:</p><blockquote>tf(t,d) = count of t in d / number of words in d</blockquote><p>If we already computed the TF value and if this produces a vectorized form of the document, why not use just TF to find the relevance between documents? Why do we need IDF?</p><p>Let me explain, words which are most common such as ‘is’, ‘are’ will have very high values, giving those words very high importance. But using these words to compute the relevance produces bad results. These kinds of common words are called stop-words. Although we will remove the stop words later in the preprocessing step, finding the presence of the word across the documents and somehow reduce their weightage is more ideal.</p><h4><strong>Document Frequency</strong></h4><p>This<strong> </strong>measures the importance of documents in a whole set of the corpus. This is very similar to TF but the only difference is that TF is the frequency counter for a term t in document d, whereas DF is the count of <strong>occurrences</strong> of term t in the document set N. In other words, DF is the number of documents in which the word is present. We consider one occurrence if the term is present in the document at least once, we do not need to know the number of times the term is present.</p><blockquote>df(t) = occurrence of t in N documents</blockquote><p>To keep this also in a range, we normalize by dividing by the total number of documents. Our main goal is to know the informativeness of a term, and DF is the exact inverse of it. that is why we inverse the DF</p><h4><strong>Inverse Document Frequency</strong></h4><p>IDF is the inverse of the document frequency which measures the informativeness of term t. When we calculate IDF, it will be very low for the most occurring words such as stop words (because they are present in almost all of the documents, and N/df will give a very low value to that word). This finally gives what we want, a relative weightage.</p><blockquote>idf(t) = N/df</blockquote><p>Now there are few other problems with the IDF, when we have a large corpus size say N=10000, the IDF value explodes. So to dampen the effect we take the log of IDF.</p><p>At query time, when the word is not present in is not in the vocab, it will simply be ignored. But in few cases, we use a fixed vocab and few words of the vocab might be absent in the document, in such cases, the df will be 0. As we cannot divide by 0, we smoothen the value by adding 1 to the denominator.</p><blockquote>idf(t) = log(N/(df + 1))</blockquote><p>Finally, by taking a multiplicative value of TF and IDF, we get the TF-IDF score. There are many different variations of TF-IDF but for now, let us concentrate on this basic version.</p><blockquote>tf-idf(t, d) = tf(t, d) * log(N/(df + 1))</blockquote><h3>About Me:</h3><p>I’m a Senior Data Scientist and AI researcher in the field of NLP and DL.<br>Connect with me: <a href="https://twitter.com/PWilliamScott">Twitter</a>, <a href="https://www.linkedin.com/in/williamscottp/">LinkedIn</a>.</p><h3>Implementing on a real-world dataset</h3><p>Now that we learnt what is TF-IDF let us compute the similarity score on a dataset.</p><p>The dataset we are going to use are archives of few stories, this dataset has lots of documents in different formats. Download the dataset and open your notebooks, Jupyter Notebooks I mean 😜.</p><p>Dataset Link: <a href="http://archives.textfiles.com/stories.zip">http://archives.textfiles.com/stories.zip</a></p><h4>Step 1: Analysing Dataset</h4><p>The first step in any of the Machine Learning tasks is to analyse the data. So if we look at the dataset, at first glance, we see all the documents with words in English. Each document has different names and there are two folders in it.</p><p>Now one of the important tasks is to identify the title in the body, if we analyse the documents, there are different patterns of alignment of title. But most of the titles are centre aligned. Now we need to figure out a way to extract the title. But before we get all pumped up and start coding, let us analyse the dataset little deep.</p><p>Take few minutes to analyse the dataset yourself. Try to explore…</p><p>Upon more inspection, we can notice that there’s an index.html in each folder (including the root), which contains all the document names and their titles. So, let us consider ourselves lucky as the titles are given to us, without exhaustively extracting titles from each document.</p><h4>Step 2: Extracting Title &amp; Body:</h4><p>There is no specific way to do this, this totally depends on the problem statement at hand and on the analysis, we do on the dataset.</p><p>As we have already found that the titles and the document names are in the index.html, we need to extract those names and titles. We are lucky that index.html has tags that we can use as patterns to extract our required content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*FzVgRqUI93BYWTeYpH_mjA.png" /></figure><p>Before we start extracting the titles and file names, as we have different folders, first let’s crawl the folders to later read all the index.html files at once.</p><pre>[x[0] for x in os.walk(str(os.getcwd())+’/stories/’)]</pre><p>os.walk gives us the files in the directory, os.getcwd gives us the current directory and title and we are going to search in the current directory + stories folder as our data files are in the stories folder.</p><blockquote>Always <strong>assume</strong> that you are dealing with a huge dataset, this helps in automating the code.</blockquote><p>Now we can find that <strong>folders</strong> give extra <strong>/</strong> for the root folder, so we are going to remove it.</p><pre>folders[0] = folders[0][:len(folders[0])-1]</pre><p>The above code removes the last character for the 0th index in folders, which is the root folder</p><p>Now, let’s crawl through all the index.html to extract their titles. To do that we need to find a pattern to take out the title. As this is in html, our job will be a little simpler.</p><p>let’s see…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*CPUina17fnWY7likaWrK2Q.png" /></figure><p>We can clearly observe that each file name is enclosed between (<strong>&gt;&lt;A HREF=”</strong>) and (<strong>”</strong>)<strong> </strong>and each title is between<strong> </strong>(<strong>&lt;BR&gt;&lt;TD&gt;</strong>) and (<strong>\n</strong>)</p><p>We will use simple regular expressions to retrieve the name and title. The following code gives the list of all the values that match that pattern. so names and titles variables have the list of all names and titles.</p><pre>names = re.findall(‘&gt;&lt;A HREF=”(.*)”&gt;’, text)<br>titles = re.findall(‘&lt;BR&gt;&lt;TD&gt; (.*)\n’, text)</pre><p>Now that we have code to retrieve the values from the index, we just need to iterate to all the folders and get the title and file name from all the index.html files</p><blockquote>- read the file from index files</blockquote><blockquote>- extract title and names</blockquote><blockquote>- iterate to next folder</blockquote><pre>dataset = []</pre><pre>for i in folders:<br>    file = open(i+&quot;/index.html&quot;, &#39;r&#39;)<br>    text = file.read().strip()<br>    file.close()</pre><pre>    file_name = re.findall(&#39;&gt;&lt;A HREF=&quot;(.*)&quot;&gt;&#39;, text)<br>    file_title = re.findall(&#39;&lt;BR&gt;&lt;TD&gt; (.*)\n&#39;, text)<br>    <br>    for j in range(len(file_name)):<br>        dataset.append((str(i) + str(file_name[j]), file_title[j]))</pre><p>This prepares the indexes of the dataset, which is a tuple of the location of the file and its title. There is a small issue, the root folder index.html also has folders and its links, we need to remove those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Le7cOSkXe93zFPFTmC56KQ.png" /></figure><p>simply use a conditional checker to remove it.</p><pre>if c == False:<br>    file_name = file_name[2:]<br>    c = True</pre><h3>Step 3: Preprocessing</h3><p>Preprocessing is one of the major steps when we are dealing with any kind of text model. During this stage, we have to look at the distribution of our data, what techniques are needed and how deep we should clean.</p><p>This step never has a one-hot rule, and totally depends on the problem statement. Few mandatory preprocessing are: converting to lowercase, removing punctuation, removing stop words and lemmatization/stemming. In our problem statement, it seems like the basic preprocessing steps will be sufficient.</p><h4>Lowercase</h4><p>During the text processing, each sentence is split into words and each word is considered as a token after preprocessing. Programming languages consider textual data as sensitive, which means that <strong>The</strong> is different from <strong>the.</strong> we humans know that those both belong to the same token but due to the character encoding those are considered as different tokens. Converting to lowercase is a very mandatory preprocessing step. As we have all our data in the list, numpy has a method that can convert the list of lists to lowercase at once.</p><pre>np.char.lower(data)</pre><h4>Stop words</h4><p>Stop words are the most commonly occurring words that don’t give any additional value to the document vector. in-fact removing these will increase computation and space efficiency. nltk library has a method to download the stopwords, so instead of explicitly mentioning all the stopwords ourselves we can just use the nltk library and iterate over all the words and remove the stop words. There are many efficient ways to do this, but ill just give a simple method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*d3iD7b4YXHa0Ybjlgnrh6A.png" /></figure><p>we are going to iterate over all the stop words and not append them to the list if it’s a stop word</p><pre>new_text = &quot;&quot;<br>for word in words:<br>    if word not in stop_words:<br>        new_text = new_text + &quot; &quot; + word</pre><h4>Punctuation</h4><p>Punctuation is the set of unnecessary symbols that are in our corpus documents. We should be a little careful with what we are doing with this, there might be few problems such as U.S — us “United Stated” being converted to “us” after the preprocessing. hyphen and should usually be dealt with little care. But for this problem statement, we are just going to remove these</p><pre>symbols = &quot;!\&quot;#$%&amp;()*+-./:;&lt;=&gt;?@[\]^_`{|}~\n&quot;<br>for i in symbols:<br>    data = np.char.replace(data, i, &#39; &#39;)</pre><p>We are going to store all our symbols in a variable and iterate that variable removing that particular symbol in the whole dataset. we are using numpy here because our data is stored in a list of lists, and numpy is our best bet.</p><h4>Apostrophe</h4><p>Note that there is no ‘ apostrophe in the punctuation symbols. Because when we remove punctuation first it will convert don’t to dont, and it is a stop word that won&#39;t be removed. What we will do instead, is removing the stop words first followed by symbols and then finally repeat stopword removal as few words might still have an apostrophe that are not stopwords.</p><pre>return np.char.replace(data, &quot;&#39;&quot;, &quot;&quot;)</pre><h4>Single Characters</h4><p>Single characters are not much useful in knowing the importance of the document and few final single characters might be irrelevant symbols, so it is always good to remove the single characters.</p><pre>new_text = &quot;&quot;<br>for w in words:<br>    if len(w) &gt; 1:<br>       new_text = new_text + &quot; &quot; + w</pre><p>We just need to iterate to all the words and not append the word if the length is not greater than 1.</p><h4>Stemming</h4><p>This is the final and most important part of the preprocessing. stemming converts words to their stem.</p><p>For example, <strong>playing and played</strong> are the same type of words that basically indicate an action <strong>play. </strong>Stemmer does exactly this, it reduces the word to its stem. we are going to use a library called porter-stemmer which is a rule-based stemmer. Porter-Stemmer identifies and removes the suffix or affix of a word. The words given by the stemmer need not be meaningful few times, but it will be identified as a single token for the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*gwPsPUq2yS9hlql5qBoTkQ.png" /></figure><h4>Lemmatisation</h4><p>Lemmatisation is a way to reduce the word to the root synonym of a word. Unlike Stemming, Lemmatisation makes sure that the reduced word is again a dictionary word (word present in the same language). WordNetLemmatizer can be used to lemmatize any word.</p><h4>Stemming vs Lemmatization</h4><p>stemming — need not be a dictionary word, removes prefix and affix based on few rules</p><p>lemmatization — will be a dictionary word. reduces to a root synonym.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*uVgEZI7UFLMjHqemI_MzGA.png" /></figure><p>A better efficient way to proceed is to first lemmatise and then stem, but stemming alone is also fine for few problems statements, here we will not lemmatise.</p><h4>Converting Numbers</h4><p>When a user gives a query such as <strong>100 dollars </strong>or<strong> hundred dollars.</strong> For the user, both those search terms are the same. but our IR model treats them separately, as we are storing 100, dollars, hundred as different tokens. So to make our IR mode a little better we need to convert 100 to hundred. To achieve this we are going to use a library called <strong>num2word</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*VPLWTb0cbjaMsj40r87q5w.png" /></figure><p>If we look a little close to the above output, it is giving us few symbols and sentences such as “one hundred <strong><em>and</em></strong> two”, but damn we just cleaned our data, then how do we handle this? No worries, we will just run the punctuation and stop words again after converting numbers to words.</p><h4>Preprocessing</h4><p>Finally, we are going to put in all those preprocessing methods above in another method and we will call that preprocess method.</p><pre>def preprocess(data):<br>    data = convert_lower_case(data)<br>    data = remove_punctuation(data)<br>    data = remove_apostrophe(data)<br>    data = remove_single_characters(data)<br>    data = convert_numbers(data)<br>    data = remove_stop_words(data)<br>    data = stemming(data)<br>    data = remove_punctuation(data)<br>    data = convert_numbers(data)</pre><p>If you look closely, a few of the preprocessing methods are repeated again. As discussed, this just helps clean the data little deep. Now we need to read the documents and store their title and the body separately as we are going to use them later. In our problem statement, we have very different types of documents, this can cause few errors in reading the documents due to encoding compatibility. to resolve this, just use encoding=”utf8&quot;, errors=’ignore’ in the open() method.</p><h4>Step 3: Calculating TF-IDF</h4><p>Recall that we need to give different weights to title and body. Now how are we going to handle that issue? how will the calculation of TF-IDF work in this case?</p><p>Giving different weights to title and body is a very common approach. We just need to consider the document as body + title, using this we can find the vocab. And we need to give different weights to words in the title and different weights to the words in the body. To better explain this, let us consider an example.</p><p>title = “This is a novel paper”</p><p>body = “This paper consists of survey of many papers”</p><p>Now, we need to calculate the TF-IDF for body and for the title. For the time being let us consider only the word <strong>paper</strong>, and forget about removing stop words.</p><p>What is the TF of word <strong>paper</strong> in the title? 1/4?</p><p>No, it’s 3/13. How? word paper appears in title and body 3 times and the total number of words in title and body is 13. As I mentioned before, we just <strong>consider </strong>the word in the title to have different weights, but still, we consider the whole document when calculating TF-IDF.</p><p>Then the TF of <strong>paper</strong> in both title and body is the same? Yes, it’s the same! it’s just the difference in weights that we are going to give. If the word is present in both title and body, then there wouldn&#39;t be any reduction in the TF-IDF value. If the word is present only in the title, then the weight of the body for that particular word will not add to the TF of that word, and vice versa.</p><blockquote>document = body + title</blockquote><blockquote>TF-IDF(document) = TF-IDF(title) * alpha + TF-IDF(body) * (1-alpha)</blockquote><h4>Calculating DF</h4><p>Let us be smart and calculate DF beforehand. We need to iterate through all the words in all the documents and store the document id’s for each word. For this, we will use a dictionary as we can use the word as the key and a set of documents as the value. I mentioned set because, even if we are trying to add the document multiple times, a set will not just take duplicate values.</p><pre>DF = {}<br>for i in range(len(processed_text)):<br>    tokens = processed_text[i]<br>    for w in tokens:<br>        try:<br>            DF[w].add(i)<br>        except:<br>            DF[w] = {i}</pre><p>We are going to create a set if the word doesn’t have a set yet else add it to the set. This condition is checked by the try block. Here processed_text is the body of the document, and we are going to repeat the same for the title as well, as we need to consider the DF of the whole document.</p><blockquote>len(DF) will give the unique words</blockquote><p>DF will have the word as the key and the list of doc id’s as the value. but for DF we don’t actually need the list of docs, we just need the count. so we are going to replace the list with its count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*izuc05xNS0ii3tID-9_TpA.png" /></figure><p>There we have it, the count we need for all the words. To find the total unique words in our vocabulary, we need to take all the keys of DF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*Zu8CxAxcU4qhI9X0M4KuHg.png" /></figure><h4>Calculating TF-IDF</h4><p>Recall that we need to maintain different weights for title and body. To calculate TF-IDF of body or title we need to consider both the title and body. To make our job a little easier, let’s use a dictionary with<em> (document, token)</em> pair as key and any TF-IDF score as the value. We just need to iterate over all the documents, we can use the Coutner which can give us the frequency of the tokens, calculate tf and idf and finally store as a (doc, token) pair in tf_idf. tf_idf dictionary is for the body, we will use the same logic to build a dictionary tf_idf_title for the words in the title.</p><pre>tf_idf = {}<br>for i in range(N):<br>    tokens = processed_text[i]<br>    counter = Counter(tokens + processed_title[i])<br>    for token in np.unique(tokens):<br>        tf = counter[token]/words_count<br>        df = doc_freq(token)<br>        idf = np.log(N/(df+1))<br>        tf_idf[doc, token] = tf*idf</pre><p>Coming to the calculation of different weights. Firstly, we need to maintain a value alpha, which is the weight for the body, then obviously 1-alpha will be the weight for the title. Now let us delve into a little math, we discussed that TF-IDF value of a word will be the same for both body and title if the word is present in both places. We will maintain two different tf-idf dictionaries, one for the body and one for the title.</p><p>What we are going to do is a little smart, we will calculate TF-IDF for the body; multiply the whole body TF-IDF values with alpha; iterate the tokens in the title; replace the title TF-IDF value in the body TF-IDF value of the (document, token) pair exists. Take some time to process this :P</p><blockquote>Flow:</blockquote><blockquote>- Calculate TF-IDF for Body for all docs</blockquote><blockquote>- Calculate TF-IDF for title for all docs</blockquote><blockquote>- multiply the Body TF-IDF with alpha</blockquote><blockquote>- Iterate Title IF-IDF for every (doc, token)</blockquote><blockquote>— if token is in body, replace the Body(doc, token) value with the value in Title(doc, token)</blockquote><p>I know this is not easy at first to understand, but still let me explain why the above flow works, as we know that the tf-idf for body and title will be the same if the token is in both places, The weights that we use for body and title sum up to one</p><p>TF-IDF = body_tf-idf * body_weight + title_tf-idf*title_weight</p><p>body_weight + title_weight = 1</p><p>When a token is in both places, then the final TF-IDF will be the same as taking either body or title tf_idf. That is exactly what we are doing in the above flow. So, finally, we have a dictionary tf_idf which has the values as a (doc, token) pair.</p><h3>Step 4: Ranking using Matching Score</h3><p>Matching score is the simplest way to calculate the similarity, in this method, we <strong>add tf_idf values of the tokens that are in query for every document</strong>. For example, for the query “hello world”, we need to check in every document if these words exist and if the word exists, then the tf_idf value is added to the matching score of that particular doc_id. In the end, we will sort and take the top k documents.</p><p>Mentioned above is the theoretical concept, but as we are using a dictionary to hold our dataset, what we are going to do is we will iterate over all of the values in the dictionary and check if the value is present in the token. As our dictionary is a (document, token) key, when we find a token that is in the query we will add the document id to another dictionary along with the tf-idf value. Finally, we will just take the top k documents again.</p><pre>def matching_score(query):<br>    query_weights = {}<br>    for key in tf_idf: <br>        if key[1] in tokens:<br>            query_weights[key[0]] += tf_idf[key]</pre><p>key[0] is the documentid, key[1] is the token.</p><h3>Step 5: Ranking using Cosine Similarity</h3><p>When we have a perfectly working <strong>Matching Score</strong>, why do we need cosine similarity again? though <strong>Matching Score</strong> gives relevant documents, it quite fails when we give long queries, it will not be able to rank them properly. What cosine similarly does is that it will mark all the documents as vectors of tf-idf tokens and measures the similarity in cosine space (the angle between the vectors. Few times the query length would be small but it might be closely related to the document in such cases cosine similarity is the best to find relevance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*OGD_U_lnYFDdlQRXuOZ9vQ.png" /></figure><p>Observe the above plot, the blue vectors are the documents and the red vector is the query, as we can clearly see, though the manhattan distance (green line) is very high for document d1, the query is still close to document d1. In such cases, cosine similarity would be better as it considers the angle between those two vectors. But Matching Score will return document d3 but that is not very closely related.</p><blockquote>Matching Score computes manhattan distance (straight line from tips)<br>Cosine score considers the angle of the vectors.</blockquote><h4>Vectorization</h4><p>To compute any of the above, the simplest way is to convert everything to a vector and then compute the cosine similarity. So, let’s convert the query and documents to vectors. We are going to use total_vocab variable which has all the list of unique tokens to generate an index for each token, and we will use numpy of shape (docs, total_vocab) to store the document vectors.</p><pre># Document Vectorization<br>D = np.zeros((N, total_vocab_size))<br>for i in tf_idf:<br>    ind = total_vocab.index(i[1])<br>    D[i[0]][ind] = tf_idf[i]</pre><p>For vector, we need to calculate the TF-IDF values, TF we can calculate from the query itself, and we can make use of DF that we created for the document frequency. Finally, we will store in a (1,vocab_size) numpy array to store the tf-idf values, index of the token will be decided from the total_voab list</p><pre>Q = np.zeros((len(total_vocab)))<br>counter = Counter(tokens)<br>words_count = len(tokens)<br>query_weights = {}<br>for token in np.unique(tokens):<br>    tf = counter[token]/words_count<br>    df = doc_freq(token)<br>    idf = math.log((N+1)/(df+1))</pre><p>Now, all we have to do is calculate the cosine similarity for all the documents and return the maximum k documents. Cosine similarity is defined as follows.</p><blockquote>np.dot(a, b)/(norm(a)*norm(b))</blockquote><h3>Analysis</h3><p>I took the text from doc_id <strong>200</strong> (for me) and pasted some content with long query and short query in both matching score and cosine similarity.</p><h4>Short Query</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*BXE8ZNAswuZOzaFAq-364w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*BJq-umHQSMp9byAM-QeGFg.png" /></figure><h4>Long Query</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*vV5IQY96PJnXvr594yFQzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*JLbgOAL7nfweeEBcCUvaqA.png" /></figure><p>As we can see from the above document 200 is always highly rated in the cosine method than the matching method, this is because cosine similarity learns the context more.</p><h4>About Me:</h4><p>I’m a Senior Data Scientist and AI researcher in the field of NLP and DL.<br>Would love to connect: <a href="https://twitter.com/PWilliamScott">Twitter</a>, <a href="https://www.linkedin.com/in/williamscottp/">LinkedIn</a>.</p><h4>Try out yourself. <a href="https://github.com/williamscott701/Information-Retrieval/blob/master/2.%20TF-IDF%20Ranking%20-%20Cosine%20Similarity%2C%20Matching%20Score/TF-IDF.ipynb">Click here</a> for git repo.</h4><h4>Libraries Used</h4><ul><li>nltk, numpy, re, mat, num2words</li></ul><h3>Information Retrieval Series:</h3><ul><li><a href="https://medium.com/@williamscott701/introduction-to-information-retrieval-series-436082826197">1. Introduction</a></li><li><a href="https://medium.com/@williamscott701/information-retrieval-unigram-postings-and-positional-postings-a28b907c4e8">2. Unigram Indexing &amp; Positional Indexing</a></li><li>3. TF-IDF</li><li>More to come…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=796d339a4089" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tf-idf-for-document-ranking-from-scratch-in-python-on-real-world-dataset-796d339a4089">TF-IDF for Document Ranking from scratch in python on real world dataset.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Information Retrieval Series]]></title>
            <link>https://williamscott701.medium.com/introduction-to-information-retrieval-series-436082826197?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/436082826197</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Sun, 03 Feb 2019 12:49:07 GMT</pubDate>
            <atom:updated>2019-02-12T08:30:08.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Information Retrieval</h3><p>This is a series on Information Retrieval techniques with implementation basic concepts and easily understandable examples.</p><p>For those who are highly interested, i suggest the book “Introduction to Information Retrieval” book by Manning</p><blockquote><a href="https://github.com/williamscott701/Information-Retrieval"><strong>Click here</strong></a> to checkout the git repo.</blockquote><h3>Information Retrieval Series:</h3><ul><li><a href="https://medium.com/@williamscott701/introduction-to-information-retrieval-series-436082826197">1. Introduction</a></li><li><a href="https://medium.com/@williamscott701/information-retrieval-unigram-postings-and-positional-postings-a28b907c4e8">2. Unigram Indexing &amp; Positional Indexing</a></li><li>3. TF-IDF</li><li>More to come…</li></ul><h3>What is Information Retrieval?</h3><p>Information Retrieval, just as the name suggests is retrieval of information. What we basically do in this is refine the retrieval of information just so that we can satisfy an information need.</p><p>so, we can sum up information retrieval as</p><blockquote>Finding relevant materials to satisfy an information need.</blockquote><p>Few points to be noted here is that when we say we want to find <strong>materials</strong> we basically mean <strong>documents</strong>, specifically <strong>text documents</strong>. And the text in those documents are highly unstructured. If you are still not sure what a text document could be, just think of it as a website, for the time being.</p><blockquote>So what an IR system does is, it takes the query from user, understands it, searches it in its corpus and sends the results of the relevant documents.</blockquote><h3>Why cant we do ctrl+f?</h3><p>we are saying that we want to find and find, so why not just build a program to search for a query, if it exists in document or not? we could do that but it need not work. the reasons are as follows</p><ul><li><strong>Synonyms:</strong> There are many words which have alternative words. for example, when a user is trying to get a haircut, his search query could be “salon” or “barber”. we cannot just show him the documents which have barber and which doesn’t have salon. because they both mean the same thing. More general examples are Mom — Mother, Hat — Cap.</li><li><strong>Homographs:</strong> These are the words which have the same spelling but have different meaning in different sentences. we do not basically deal with the pronunciation of words here. Lie — can be lying on bed, or lying to another person. tear — could be tearing a paper, or having tears (as in crying). Apple — Could be a company or a fruit.</li></ul><p>so due to these above problems, we need to build an intelligent IR model which can understand the query of the user and give the relevant documents. do not worry about the above problems, we will basically deal with them later, just as a gist, we deal with this by going through a important stage called, preprocessing, where the information is turned into a more general form which can help us relate the words much better.</p><h3><strong>Intelligent IR</strong></h3><p>When we are trying to retrieve relevant documents, we need to first define relevance. are we going to retrieve the latest documents? or are we going to retrieve the documents which match the subject?</p><p>An Intelligent IR model do not just depend on one factor to find out relevance, <strong>metadata</strong>, <strong>authoritativeness</strong>, type of<strong> information need</strong>, <strong>meaning</strong> of the query, meaning of the sentence in the document and many such factors are considered.</p><h3>Basic Terminology:</h3><ul><li><strong>Collection / Corpus:</strong> collection of documents</li><li><strong>Query:</strong> Information need</li><li><strong>Token:</strong> An individual entity as word / set of characters</li><li><strong>Rank:</strong> Relevance of a document in some measure.</li></ul><h3>Information Retrieval Series:</h3><ul><li><a href="https://medium.com/@williamscott701/introduction-to-information-retrieval-series-436082826197">1. Introduction</a></li><li><a href="https://medium.com/@williamscott701/information-retrieval-unigram-postings-and-positional-postings-a28b907c4e8">2. Unigram Indexing &amp; Positional Indexing</a></li><li>3. TF-IDF</li><li>More to come…</li></ul><h3>Resources:</h3><p>Introduction to Information Retrieval — Manning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436082826197" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence: 6. Q Learning and SARS on Maze in OpenAI]]></title>
            <link>https://williamscott701.medium.com/artificial-intelligence-6-q-learning-and-sars-on-maze-in-openai-552a8926b4ab?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/552a8926b4ab</guid>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[sars]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 19:55:22 GMT</pubDate>
            <atom:updated>2019-01-27T20:00:58.511Z</atom:updated>
            <content:encoded><![CDATA[<p>Code: <a href="https://github.com/williamscott701/Artificial-Intelligence/tree/master/6.%20Q%20Learning%20and%20SARS%20on%20Maze%20in%20OpenAI">GitRepo</a></p><p><strong>Hyperparameters Used:</strong></p><p>- Learning Rate</p><p>- Discount Rate</p><p>- Exploration Rate</p><p><strong>Learning Rate [0, 1]:</strong></p><p>Learning rate is the rate of learning or the amount of information that we are taking from the current iteration into the Q-table.</p><p><strong>Discount Rate [0, 1]:</strong></p><p>Discount rate is the amount of discount we are giving to the q’(s’, a’) during the update rule</p><p><strong>Exploration Rate [0, 1]:</strong></p><p>Normally we should take the maximum valued action at a given state. But to avoid going to a local-maxima instead of global-maxima we take few random actions few times even though that action is not a max action. This helps to diversify and look every place possible. And the amount of exploration is decided by exploration rate.</p><p><strong>Q-Learning:</strong></p><p><em>Q[s, a] += learning_rate * (reward + (discount * q’) — Q[s, a)</em></p><p>Here we maintain a q-table which helps us decide the action to be taken from a particular given state. We maintain q-values in the Q-table. Each cell is denoted by q(s, a). where s is the state and a is action. The q table will be of size (s x a)</p><p><strong>Note:</strong></p><p>- All the changes of the hyperparameters are done on the same environment for evaluation of the changes in results.</p><p>- Global maxima is the shortest distance possible in the maze. Local-maxima is a near short distance but not the shortest.</p><p><strong>Convergence Condition:</strong></p><p>- Convergence is assumed when we have the same reward for 8 consecutive iterations.</p><p><strong>Part 3:</strong></p><p>Environment: 5x5</p><p>Observation:</p><p>- As the exploration rate is high, random actions are taken instead of the better suited actions</p><p>Observation:</p><p>- With both learning rate and exploration rate high, the same issue as above happens. The model learns but still takes a random choice 80% of the time</p><p>Observation:</p><p>- With less learning rate and exploration rate, the learning takes time but is not at constant as the model tends to be unconfident.</p><p>Observation:</p><p>- Without discount factor the model just doesn’t work. And the update on the q values doesn’t make sense</p><p>Observation:</p><p>- With less exploration rate and 80% learning rate and total discount rate, the learning wobbles a bit but becomes constant in the end.</p><p>Observation:</p><p>- With learning rate full and discount as 80%, the model tends to be perfectly aligned but little different in each iteration. Constant path is not maintained.</p><p>Observation:</p><p>- With 0 exploration rate, the model reaches to a perfect shorter path very quickly and it constantly goes through that path only.</p><p>- This is a drawback as the path might be a near shorter path instead of the shortest path available.</p><p>- Pre-mature convergence is highly possible.</p><p>Best Hyperparameters:</p><p>Exploration Rate:0.1 | Learning Rate: 0.3 | Discount: 0.8</p><p>Best method to run with hyperparameters:</p><p>- We can actually set the hyperparameters manually and check the performance but the best way to set the hyperparameters is to gradually change according to the number of iterations</p><p>- In the beginning the exploration rate should be little high and then should reduce to 0.01</p><p>- Learning rate also should decrease from 0.9 to 0.4</p><p>- Discount rate can stay constant.</p><p><strong>Note:</strong></p><p>Time taken is directly proportional to the number of iterations. So, did not mention the time taken.</p><p><strong>Part 3c:</strong></p><p>- If there is equal probability in the initial state, then also the learning is not worrisome and the convergence is almost same with a little +- few iterations.</p><p><strong>Part 3e:</strong></p><p>- On observation of the values of two separate intermediate states, the q-values increase for the states where the state is desired and it reduces for the states where it is not desired. Basically, the positive and negative reward comes into effect here.</p><p><strong>Part 4:</strong></p><p>- Extracted the q values from the previous trained model.</p><p>- Applying those q values to a new environment.</p><p><strong>Code to apply q values to new model:</strong></p><p><strong>Output:</strong></p><p><strong>Observation:</strong></p><p>- This will definitely won’t work as the model is trained on a different maze.</p><p>- The pointer in the maze gets struck at different positions. As the q values are not designed for this maze.</p><p><strong>SARSA:</strong></p><p><strong><em>a’ = get_second_action()</em></strong></p><p><strong><em>q’ = Q(s’, a’)</em></strong></p><p><em>Q(s, a) += learning_rate * (reward + (discount * q’) — Q(s, a))</em></p><p>In SARSA, we take another action from the first action and then take the q value of that new action with that new state.</p><p>The lower maze is solved by both Q-learning and SARSA algorithm to compare the performance</p><p><strong>Q-Learning:</strong></p><p>Converged in 60 Iterations</p><p><strong>SARSA:</strong></p><p>Converged in 33 Iterations</p><p><strong>Observation:</strong></p><p>- SARSA is a greedy policy, as the policy it relies on is from a’ from another action.</p><p>- Q-learning directly learns the optimal value. While SARSA learns the near optimal policy with a little exploration.</p><p>- Q-Learning takes little more iterations to converge than SARSA.</p><p>- On more analysis, the few times the Q-learning is better than SARSA. Maybe the variance is due to the change in maze.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=552a8926b4ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence: 5. Ant Colony Optimisation (ACO) on TSP]]></title>
            <link>https://williamscott701.medium.com/artificial-intelligence-5-ant-colony-optimisation-aco-on-tsp-b70dfb70f300?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/b70dfb70f300</guid>
            <category><![CDATA[travelling-salesman]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ant-colony-optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 19:53:45 GMT</pubDate>
            <atom:updated>2019-01-27T20:00:23.683Z</atom:updated>
            <content:encoded><![CDATA[<p>Code: <a href="https://github.com/williamscott701/Artificial-Intelligence/tree/master/5.%20Ant%20Colony%20Optimization%20(ACO)%20on%20TSP">GitRepo</a></p><p><strong>Assumptions:</strong></p><p>- Termination condition is assumed to be “similarity of path taken by all the ants”</p><p>- The count of ants is taken as twice the count of cities, by default</p><p>- Other than these, ACO is implement as per the algorithm</p><p>- Alpha is the influence on pheromone level</p><p>- Beta is the influence of favorability of distance</p><p><strong>Methodology:</strong></p><p>- We initialize the cities at random coordinates and generate a distance matrix, which basically tells us the distance of a city with each other cities</p><p>- Now, we just have nodes on the graph which are waiting to be connected</p><p>- Here, connection refers to an ant choosing that edge during its travel</p><p>- Now we place the ants in initial city ‘zero’</p><p>o We tell the ant to take all the paths that are not visited and return back</p><p>o During the travel we store the total distance travelled and the path taken by the ant</p><p>o We do this loop for all ants</p><p>o During this process the ant will be depositing some amount of phenome in the path which will help the other ants to choose a path when multiple paths are available</p><p>o And choosing of a city is done according to a probability which has a calculated amount of pheromone and the distance</p><p>- We have a pheromone evaporation level which tells us how much f the pheromone is evaporated during each iteration</p><p>- At a certain point all the ants will be taking the same path, this is considered as convergence</p><p>- The ants tend to find the shortest path with the probability selection of path on the pheromone</p><p><strong>Algorithm:</strong></p><p>- Generate cities and ants</p><p>- Place ants in the initial city</p><p>- Repeat until convergence: (all ants take same path)</p><p>o For every ant:</p><p>§ Repeat until a unvisited city exits:</p><p>· Choose next city with the conditional pheromone probability</p><p>· Store the path</p><p>§ Go back to the initial city</p><p>o Update pheromone level</p><p><strong>Observations:</strong></p><p>- Though the ants are legally blind, they tend to choose the shortest path after certain iterations with the help of pheromone</p><p>- The combined ensemble approach of ants helps in finding the shortest distance</p><p>- The parameters alpha, beta, no of ants and the number of cities play a huge role</p><p>- Alpha &gt;1 and beta &gt; 0. These conditions are so that the formulation of probability doesn’t get invalid.</p><p>- With basic alpha 1 and beta 1, the number of iterations are high</p><p>- With alpha 2, and beta 2, the number of iterations gets reduced</p><p>- With alpha &gt; beta the ants seem to choose paths that are even longer</p><p>- With beta &gt; alpha the ants seem to choose the shorter path helping to converge sooner.</p><p>- With increase in number of cities, more computation power is needed, taking more time to converge</p><p>- Increasing the number of ants will increase the computational capacity but can give a better result</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70dfb70f300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence: 4. GA, MA, CSP for Timetable Generation]]></title>
            <link>https://williamscott701.medium.com/artificial-intelligence-4-ga-ma-csp-for-timetable-generation-ab52dcaaff69?source=rss-992ed32cb583------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab52dcaaff69</guid>
            <category><![CDATA[constraints-programming]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[memetic-algorithm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[William Scott]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 19:51:23 GMT</pubDate>
            <atom:updated>2019-01-27T19:59:44.381Z</atom:updated>
            <content:encoded><![CDATA[<p>Code: <a href="https://github.com/williamscott701/Artificial-Intelligence/tree/master/4.%20GA%2C%20MA%2C%20CSP%20for%20Timetable%20Generation">GitRepo</a></p><h3><strong>Genetic Algorithm (GA)</strong></h3><p>- There is always a sub-optimal solution during the generations in GA and MA. We need not wait for thousands of years just to get to the optimal answer.</p><p>- All the timetable algorithms and constraints are developed considering the IIITD timetable and the staff and lecture halls available.</p><p>Basic Algorithm Steps:</p><p>1. Initialise Population — 100</p><p>2. Evaluate Function</p><p>3. Repeat while not converged</p><p>a. Crossover</p><p>b. Mutate</p><p>c. Evaluate (pick best 10)</p><p>Assumptions and Additional Features:</p><p>- The evaluation function takes the top 10 best performing chromosomes</p><p>- For better diversity, we can even include a randomly generated chromosome into the population randomly in a random generation with some probability</p><p>- <strong>Elitism is not used</strong></p><p>- [0, 0] is used to denote a free lecture hall where no lecture is happening</p><p>- In each generation, the 0,0 block is added into the possibilities to improve the probability of that getting randomly selected</p><p>- We can also include few random chromosomes into the population, this is not used as the performance with my current algorithm is satisfactory.</p><p>- <strong>Lots of Probability is used in many places to decide the mutation rate and crossover rate</strong></p><p>Chromosome:</p><p>- 3d structure of days, slots and lecture halls</p><p>- Days ✕ Slot ✕ Lecture Halls(N) → 5 ✕ 8 ✕ N</p><p>Fitness Function and Constraints Handled:</p><p>- A lecturer cannot teach when he is currently teaching (same subject or different subject)</p><p>- A lecturer should teach only the subject he is assigned to teach.</p><p>- A course cannot be held in any other hall if it is currently going on</p><p>- A course should satisfy the minimum number of classes required per week</p><p>- A course should not exceed maximum class limit per week</p><p>- A course once held on a day cannot be held on that day again</p><p>- Number of courses can be greater than or less than the number of lecturers</p><p>- [0, 0] is an empty block</p><p>- If any of the above conditions are not met, there is a penalty added. And fitness can be basically defined as the inverse of that penalty.</p><p>- Fitness = 1/(1+errorrate). Here the error rate is the error penalty for all the unsatisfied conditions mentioned above.</p><p>Crossover:</p><p>- Crossover is done on random-axis.</p><p>- Probability is used to select which kind of crossover should be used</p><p>Mutation:</p><p>- Mutation can be done on any dimension, but it will be of very less use if it is done only on one dimension.</p><p>- Probability is used to decide which dimension to be mutated and the number of times to repeat that process (1 or 2).</p><p>Observations:</p><p>- The performance is very good, but the convergence can take quite a number of generations.</p><p>- And after a set of generations, the best collision rate keeps a constant value for quite many generations (e.g., 1)</p><p>- The running time is less</p><p>- Bit difficult to converge with complex constraints, but will definitely converge after certain generations.</p><h3><strong>Memetic Algorithm (MA)</strong></h3><p>MA = GA + Local Hill Climbing</p><p>Basic Algorithm Steps:</p><p>1. Initialise Population</p><p><strong>2.</strong> <strong>Local Search</strong></p><p>3. Evaluate Function</p><p>4. Repeat while not converged</p><p>a. Crossover</p><p>b. Mutate</p><p><strong>c.</strong> <strong>Local Search</strong></p><p>d. Evaluate</p><p>The main difference between GA and MA is that we try to improve each individual chromosome before evaluation. This additional functionality is called local search (Local Hill Climbing). In this, for each chromosome, we move a bit around in its local search space and see if it is a better state than the previous. If that space is better, we then replace the parent with the generated chromosome.</p><h3>Local Search:</h3><p>- Local Search happens in local search space</p><p>- Recombine a pair of parents and replace them if the child is better than parents (mentioned in Lecture Slides).</p><p>- Take a step in either direction in the search space of each chromosome by changing a gene and replace parent if the child is better</p><p>- We can even take multiple steps depending upon our implementation, but the steps should not be too far to save the computational power</p><p>Observations and Points to Note:</p><p>1. Local search in MA is usually computationally heavy, but it is definitely worth the computation cost.</p><p>2. MA converges a lot faster than GA</p><p>3. There is a high probability that the best chromosome will be improved in each generation, and there is a huge improvement in the initial generations.</p><p>4. Can also solve complex constraints</p><p>5. Both GA and MA gives meaning full and evenly distributed results unlike CSP</p><p>6. The fitness function, evaluation function, crossover and mutation are same as GA</p><h3><strong>Performance Evaluation of GA and MA:</strong></h3><h3><strong>Stage 1:</strong></h3><p>- Random mutation on z-axis (lecture hall) once (on each chromosome)</p><p>- Random 1-point crossover on z-axis once</p><p>- MA is using positive replacing of parents upon recombination</p><p>- The constraints given are very lenient</p><p><em>GA — </em>2 courses/day</p><p><em>MA</em> — 2 courses/day</p><p>MA — 1 course/day</p><p><strong>Observations:</strong></p><p>- With 2 courses/day GA is able to converge fine.</p><p>- MA is able to converge much better</p><p>- MA is also able to handle 1 course/day</p><h3><strong>Stage 2:</strong></h3><p>- Random mutation on <strong>random</strong> axis once (on each chromosome)</p><p>- Random 1-point crossover on z-axis once</p><p><em>GA — </em>2 courses/day</p><p><strong>Observations:</strong></p><p>- The random axis mutation improved the GA for the same constraints in GA.</p><h3><strong>Stage 3:</strong></h3><p>- Random mutation on random axis <strong>random number of times (1(0.6) or 2(0.4))</strong> (on each chromosome)</p><p>- Random 1-point crossover on z-axis once</p><p>- MA is using positive replacing of parents upon recombination</p><p><em>GA — </em>2 courses/day</p><p><em>GA — </em>1 courses/day</p><p>MA — 1 courses/day</p><p><strong>Observations:</strong></p><p>- With the increase in randomness to the axis in mutation, the performance seems to increase.</p><p>- While GA is able to compute well even for stricter constraints (1 course/day). MA is preforming much better</p><h3><strong>Stage 4:</strong></h3><p>- Random mutation on random axis random number of times (1(0.6) or 2(0.4)) (on each chromosome)</p><p>- Random 1-point crossover on <strong>random</strong>-axis once</p><p>- MA is using positive replacing of parents upon recombination</p><p>- <strong>MA with different input values</strong></p><p><em>MA — </em>1 courses/day</p><p><strong>Observations:</strong></p><p>- Now I tried MA with stricter constraints and was checking how I can improve the performance on the worst conditions.</p><p>- I found that implementing randomness on crossover axis seems to help.</p><p>- MA converges in reasonable generations</p><h3><strong>Stage 5:</strong></h3><p>- Random mutation on random axis random number of times (1(0.6) or 2(0.4)) (on each chromosome)</p><p>- Random 1-point crossover on random-axis once</p><p>- MA is using positive replacing of parents upon recombination and <strong>surrounding check (another Hill Climb) — where we take a step in the local search space on either side a couple number of steps and replace the parent if the child is better.</strong></p><p><strong>Observations:</strong></p><p>- Now after stage 4, I tried to reduce the number of generations the MA is taking to converge.</p><p>- In this Local Search, first I try to wander each chromosome to its surroundings randomly to couple of steps and replace the parent if it is better.</p><p>- This reduces the generations by half, as we can observe.</p><h3><strong>Stage 6:</strong></h3><p>- Random mutation on random axis random number of times (1(0.6) or 2(0.4))</p><p>- Random “<strong>random</strong> (1 or 2)-point” crossover on random-axis once</p><p>- MA is using positive replacing of parents upon recombination and surrounding check</p><p>- <strong>Stricter Constraints</strong></p><p>MA — 2 courses/day</p><p>GA — 2 courses/day</p><p>GA — 1 course/day</p><p>MA — 1 course/day</p><p>Observations:</p><p>- Now I want to take my algorithm to its max, to generate an actual IIITD timetable. So I gave more constraints and I was trying different ways to improve the performance.</p><p>- I found that randomly deciding which crossover to perform is a very good technique.</p><p>- Here to make my algorithm simple, if my random variable decided to do a 2-point crossover, I just have to do the 1-point crossover twice.</p><p>- <strong>In this there is a problem, if the same point of crossover is chosen, then there is a problem that it returns the same parent. So I’m keeping a check if the same random point is chosen, and if it same I return the 1-point crossover chromosome.</strong></p><h3><strong>Inference:</strong></h3><p>- The generated timetable is very neatly diverse and follows all constraints. There are free classes at random times which will help students of IIITD to have some leisure time.</p><p>- Using this algorithm and implementing some more constraints we can actually use this as a timetable generator.</p><p>- I would personally use MA to find a solution faster with huge constraints.</p><h3><strong>Final Stage:</strong></h3><h3>GA:</h3><p>Converged in 125 generation</p><p>Timetable</p><p>Courses per day Error: 0</p><p>[[0 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0 0 0 1 1]</p><p>[0 1 0 1 0 1 1 0 1 0 1 1 0 1 0 0 1 1 0 0]</p><p>[0 1 1 0 1 0 0 0 0 1 1 1 1 1 1 1 0 1 1 0]</p><p>[1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 0 1 0 0 1]</p><p>[1 1 0 0 1 0 1 1 0 0 0 0 0 0 0 1 1 0 0 0]]</p><p>Course Frequency Error: 0</p><p>[2 3 2 2 2 2 2 3 3 2 3 2 2 3 2 2 3 2 2 2]</p><p>Lecture Z-Axis Collisions: 0</p><p>Total Collisions: 0 Fitness: 1.0</p><h3>MA</h3><p>Timetable</p><p>Courses per day Error: 0</p><p>[[1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 1 0]</p><p>[1 0 1 1 0 1 0 0 1 0 0 0 0 1 1 1 0 0 1 1]</p><p>[0 1 1 1 1 0 0 0 0 1 0 0 1 0 1 0 0 1 0 0]</p><p>[1 1 0 0 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1]</p><p>[0 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0]]</p><p>Course Frequency Error: 0</p><p>[3 4 4 3 2 2 3 2 3 4 3 2 4 4 4 3 2 2 4 2]</p><p>Lecture Z-Axis Collisions: 0</p><p>Total Collisions: 0 Fitness: 1.0</p><p><strong>Constraint Satisfaction Problem (CSP):</strong></p><p>- Basically a DFS on the set of possibilities on our 3D matrix</p><p>- The possibilities here are the all possible combinations of lecturer and course. Because a course taught by one professor should not be taught by another professor</p><p>- Gives uneven results</p><p>- [-1, -1] is an empty slot in the timetable. Starting the matrix with all zero’s</p><p>- As this tries to fill the matrix cell by cell, checking if the constraints are met, the data placed are sequential.</p><p>- The conditions here are taken the same as GA fitness function</p><p>- If it reaches a dead state where the conditions are not met, then we return back to the parent searching for a different combination</p><p>- This gives a solution but depends on our necessity if we have to use this.</p><p>- Also takes a little computational and space power depending on the type of CSP implemented.</p><p>- Becomes heavy depending on the constrains and the search space</p><p>- This is not a good approach both in terms of time complexity and space complexity</p><p><strong>Inference:</strong></p><p>- The timetable generated is very uneven</p><p>- The lecture halls are utilized to an extent in the first 3 slots and the rest of the day is totally free.</p><p>- If this timetable is used for IIITD, no student will be able to attend classes in the morning</p><p>- So I would not prefer this timetable for IIITD, lets go with GA/MA</p><p><strong>Timetable Generated:</strong></p><p><strong>Constraints:</strong></p><pre>courses = 10</pre><pre>lectureHalls = 3</pre><pre>professors = 6</pre><pre>minClassCount = 2</pre><pre>maxClassCount = 5</pre><pre>coursesPerDay = 1</pre><p><strong>Items in Stack: 271, Cost: 119</strong></p><p>Courses per day Error: 0</p><p>[[1 1 1 1 1 1 1 1 1 1]</p><p>[1 1 1 1 1 1 1 1 1 1]</p><p>[1 1 1 1 1 1 1 1 1 1]</p><p>[1 1 1 1 1 1 1 1 1 1]</p><p>[1 1 1 1 1 1 1 1 1 1]]</p><p>Course Frequency Error Max: 0</p><p>[5 5 5 5 5 5 5 5 5 5]</p><p>Course Frequency Error Min: 0</p><p>[5 5 5 5 5 5 5 5 5 5]</p><p>Total Collisions: 0</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab52dcaaff69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>