<?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 Martin Davtyan on Medium]]></title>
        <description><![CDATA[Stories by Martin Davtyan on Medium]]></description>
        <link>https://medium.com/@martinthenext?source=rss-bf9e863a77c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aLsw0WGsMoVpiGst3QVapw.gif</url>
            <title>Stories by Martin Davtyan on Medium</title>
            <link>https://medium.com/@martinthenext?source=rss-bf9e863a77c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:56:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@martinthenext/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[Inventing programming with Python]]></title>
            <link>https://medium.com/@martinthenext/inventing-programming-with-python-d45a5d2b60c8?source=rss-bf9e863a77c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d45a5d2b60c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[teaching-computer-science]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Martin Davtyan]]></dc:creator>
            <pubDate>Mon, 12 Nov 2018 02:57:28 GMT</pubDate>
            <atom:updated>2019-07-29T21:12:23.395Z</atom:updated>
            <content:encoded><![CDATA[<h4>A draft of a <a href="http://www.rigb.org/">Royal Institution</a> masterclass to “invent” core programming concepts through looking at code.</h4><p>Often, when people are taught programming for the first time, what they really get is basic syntax of a particular language. For example, there is a wealth of great hands-on intro tutorials on Python. The problem is that just showing people how to make a “for” loop to print numbers from 1 to 10 doesn’t explain <strong>why </strong>Python loops are written this way or <strong>how </strong>this is relevant or useful for real-world problems. I tried to address this issue by showing the <strong>reasoning </strong>behind some of the core concepts, rather than the rules of manipulating them. If you are thinking of ways to introduce a group of people to programming, maybe flicking through this could be useful.</p><p>Following are the notes outlining a very interactive masterclass/workshop session for a small audience with no programming experience.</p><p>We all know programming is very useful in making cool stuff. But what is programming really?</p><p>Q: What is programming?</p><p>A: Making computers compute things.</p><p>But is it really just that? You are going to be faced with two different types of programming problems in your life:</p><ol><li>School problems: small riddles you solve once “on the spot”</li><li>Real problems: problems you solve for at least several days, maybe in a team</li></ol><p>All the cool stuff, like programming robots or making websites belongs in the second category — you always want to improve whatever you are building, so you are coming back to it. All powerful programming languages, including Python, are built for solving real problems.</p><p>Q: Who worked on one programming task for more than a day?</p><p>Q: What can be a difference in code you write for type 1 and 2 problems?</p><p>A: When solving real problems, you need code to be understandable and extensible. These are the basic principles that drive all real-world code, once you understand them, programming languages are going to make much more sense! Also, you are going to better at solving real-world problems.</p><p><strong>Note</strong> The class is meant to be very interactive. Students would submit code for review, and then we would discuss it all together. The goal is make sure students understand what every piece of demonstrated code does.</p><p>Problem 1. Make a program that computes squares of first three prime numbers</p><p><em>Solution 1.1:</em></p><pre><strong>print(2*2)</strong><br><strong>print(3*3)</strong><br><strong>print(5*5)</strong></pre><pre>4<br>9<br>25</pre><p>That works. Here we have a sequence of commands we call <strong>code</strong>, telling the computer to print things.</p><p>Q: Our job is done — this program makes the computer compute what we wanted. Right?</p><p>A: This code is not the best code we could write. <strong>There are multiple ways to make a computer do something, and some ways are better than others.</strong></p><h3>Simple code and data</h3><p>Computers would rather read binary code they can execute in their processors.</p><p><em>Solution 1.2:</em></p><p>0000 0010 0000 0011 0000 0101 1111 1111 1010 1000 1110 1001 0101 0000 1010 1010 0010 1001 0010 0010 1010 0100</p><pre>4<br>9<br>25</pre><p>This program gives the right output too. The first three bytes are representations of 2, 3 and 5 — this is <strong>data</strong>. The rest could be binary <strong>code</strong> telling a computer to:</p><ol><li>Scan memory for numbers until it sees 1111 1111</li><li>Square every number it sees and store them in place of the old number</li><li>Scan memory for numbers and print them until it sees 1111 1111</li></ol><p>Q: What if we want to modify this code to print squares of first <strong>four</strong> prime numbers?</p><p>A: 0000 0010 0000 0011 0000 0101 0000 0111 1111 1111 1010 1000 1110 1001 0101 0000 1010 1010 0010 1001 0010 0010 1010 0100</p><p>Q: What if we need first ten? Binary is hard to read and it is easy to make a mistake.</p><p>People invented programming languages to make computer programs easy to work with, so they could be changed and re-used. <strong>Computer programs are written for people</strong>. Hence, the goal of a programmer in any language (except for binary) is not only to make a computer do something, but to do it in a most understandable way. If you want to just make a computer do something, googling the solution works in most cases :)</p><p>Python has an amazing ecosystem and libraries that allow you to do so many things! Once you understand the logic of their code and how to work with it, you can start using it and easily start building things you consider complicated now. This is why real-life programming is important to understand.</p><h3>Lists</h3><p>There are a few ideas about how to make things easier to understand, in programming and in general, all of them very intuitive. Consider this list:</p><ol><li>Buy a can of tomatoes</li><li>Buy a lemon</li><li>Buy a loaf of bread</li></ol><p>It is clear that it is a shopping list and it would be better to write it as:</p><p>Buy: &lt;- action</p><ol><li>Can of tomatoes &lt;- a list of objects</li><li>Lemon</li><li>Loaf of bread</li></ol><p>In programming a similar idea is called <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself"><em>Don’t repeat yourself</em></a><em> (DRY)</em>.</p><p><em>Solution 1.3:</em></p><pre><strong>for</strong> x <strong>in</strong> [2, 3, 5]: <em># &lt;- a list of objects</em><br>    <strong>print</strong>(x * x) <em># &lt;- action</em></pre><pre>4<br>9<br>25</pre><p>To avoid repetition we separated <strong>data</strong> from <strong>code</strong>. <strong>data</strong>: In Python [2, 3, 5] is called a <em>list</em>. <strong>code</strong>: this is <em>for loop</em>, it is doing exactly the same thing as</p><p><em>Solution 1.4:</em></p><pre>x = 2<br><strong>print(x * x)</strong><br>x = 3<br><strong>print(x * x)<br></strong>x = 5<br><strong>print(x * x)</strong></pre><pre>4<br>9<br>25</pre><h3>Data</h3><p>You can give lists names, just like you do with numerical variables. To know their length you can use a function len. By giving them a name you can show what the list <strong>means</strong>.</p><p><em>Solution 1.5:</em></p><pre>primes = [2, 3, 5]</pre><pre><strong>for</strong> x <strong>in</strong> primes:<br>    <strong>print</strong>(x * x)</pre><pre><strong>print()<br>print</strong>(<strong>len</strong>(primes))</pre><pre>4<br>9<br>25</pre><pre>3</pre><p>So in Solution 1.3 we just invented a <strong>data</strong> structure (list) and a <strong>code</strong> expression (for loop) to make it DRY.</p><p>Q: How would you now print out the first five prime numbers squared? Which code is easier to adapt?</p><p><em>Conclusion</em>. Programming languages are similar to normal languages in a way they are there to express ideas for others to understand. We can <em>invent </em>constructions in a language that help us express ourselves better.</p><p><em>Problem 2.</em> The school math Olympiad had 20 problems, out of which John solved 12, Jack solved 16 and Jane solved 17. Pupils get into the next round if they solved at least 13 problems. Pupils can enter their name into the computer and it is stored in variable name. Print &#39;YES&#39; if they are getting into the next round, and &#39;NO&#39; otherwise.</p><p><em>Solution 2.1:</em></p><pre>name = &#39;Jack&#39;</pre><pre><strong>if</strong> name == &#39;John&#39;:<br>    <strong>print</strong>(&#39;NO&#39;)<br><strong>if</strong> name == &#39;Jack&#39;:<br>    <strong>print</strong>(&#39;YES&#39;)<br><strong>if</strong> name == &#39;Jane&#39;:<br>    <strong>print</strong>(&#39;YES&#39;)</pre><pre>YES</pre><p>To take actions based on a condition, we invented a <strong>code</strong> expression called <em>if clause</em>.</p><p>Q: What’s the problem with this code?</p><p>Q: What if there is a new student Joe who scored 20? How would you adapt this code?</p><p>A: This code is not easy to adapt, because it doesn’t show the logic behind who to print ‘YES’ to. We should include inferring ‘YES’ or ‘NO’ from a pupil’s score.</p><p><em>Solution 2.2:</em></p><pre><strong>if</strong> name == &#39;John&#39;:<br>    score = 12<br><strong>if</strong> name == &#39;Jack&#39;:<br>    score = 16<br><strong>if</strong> name == &#39;Jane&#39;:<br>    score = 17<br>    <br><strong>if</strong> score &gt;= 13:<br>    <strong>print</strong>(&#39;YES&#39;)<br><strong>else</strong>:<br>    <strong>print</strong>(&#39;NO&#39;)</pre><pre>YES</pre><h3>Dictionary</h3><p>Q: How do you now adapt the code to account for Joe?</p><p>A: You have to repeat two lines again, changing name to Joe and score to 20. The top block mostly contains data, let’s invent a <strong>data</strong> structure to store mappings between things — a dictionary.</p><p>key → value</p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}<br><br><strong>print</strong>(scores)<br><strong>print</strong>()<br><strong>print</strong>(scores[&#39;John&#39;])</pre><pre>{&#39;Jane&#39;: 17, &#39;John&#39;: 12, &#39;Jack&#39;: 16}<br><br>12</pre><p>Q: How do you now adjust the code for Joe?</p><p>A:</p><pre>scores[&#39;Joe&#39;] = 20<br><br><strong>print</strong>(scores)<br></pre><pre>{&#39;Jane&#39;: 17, &#39;John&#39;: 12, &#39;Jack&#39;: 16, &#39;Joe&#39;: 20}</pre><p>You can get keys and values separately as <em>lists</em>:</p><pre>scores.keys()<br></pre><pre>[&#39;Jane&#39;, &#39;John&#39;, &#39;Jack&#39;]<br></pre><pre>scores.values()<br></pre><pre>[17, 12, 16]</pre><p>Q: How do you now solve the problem with the dictionary?</p><p><em>Solution 2.3:</em></p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}<br><br><strong>if</strong> scores[name] &gt;= 13:<br>    <strong>print</strong>(&#39;YES&#39;)<br><strong>else</strong>:<br>    <strong>print</strong>(&#39;NO&#39;)</pre><pre>YES</pre><p>To be very short you can also use a so-called <em>ternary operator</em> (composed of three parts) to compress the <em>if-else</em> statement:</p><p><em>Solution 2.4:</em></p><pre><strong>print</strong>(&#39;YES&#39; <strong>if</strong> scores[name] &gt;= 13 <strong>else</strong> &#39;NO&#39;)</pre><pre>YES</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TloQJjW2XS8FPnPJGA5qMw.png" /><figcaption>Recap of everything we invented this far</figcaption></figure><h3>Code</h3><p>We invented lists and dictionaries to organize <strong>data</strong>. Let’s now invent functions — to organize <strong>code</strong> expressions:</p><pre>arguments (variable 1, …, variable N) → [function] → value</pre><p>Most functionality in programming languages comes in functions. They take some arguments as input and produce output. You can <em>call </em>(i.e. start)<em> </em>them by passing them a list of arguments in parenthesis.</p><p>For example, function sum takes a list of numbers as in input and <em>returns</em> their sum.</p><p>A:</p><pre>sum([1, 2, 3, 4, 5])</pre><pre>15</pre><p>Q: What is an argument here? What is a return value?</p><p><em>Problem 3.</em> Same as Problem 2, but new rules: instead of solving 13 problems to get into the next rounds, each pupil needs to solve at least one problem more than an average result.</p><p>How would you change the code?</p><p><em>Solution 3.1:</em></p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}</pre><pre>name = &#39;Jack&#39;</pre><pre><strong>if</strong> scores[name] - sum(scores.values()) / len(scores.values()) &gt;= 1:<br>    <strong>print</strong>(&#39;YES&#39;)<br><strong>else</strong>:<br>    <strong>print</strong>(&#39;NO&#39;)</pre><pre>YES</pre><p>Q: What is the problem with this code?</p><p>A: Our previous code read pretty easily: scores[name] &gt;= 13 - if the score of pupil with this name is bigger or equal to thirteen. The new one is confusing, we want it to read naturally. Just like we have a name to a piece of <strong>data</strong>, we can give names to pieces of <strong>code</strong> by defining <em>functions</em>.</p><p><em>Solution 3.2:</em></p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}</pre><pre>name = &#39;Jack&#39;</pre><pre><strong>def</strong> average(numbers):<br>    sum_of_numbers = sum(numbers)<br>    count = len(numbers)<br>    <strong>return</strong> sum_of_numbers / count<br>                <br><strong>if</strong> scores[name] - average(scores.values()) &gt;= 1:<br>    <strong>print</strong>(&#39;YES&#39;)<br><strong>else</strong>:<br>    <strong>print</strong>(&#39;NO&#39;)</pre><pre>YES</pre><p>Notice how we can use whatever the names we want when defining functions. When writing a function you can think only about how to use input arguments to get output. This way code expresses what you are doing better.</p><p>With such a flexible tool as functions we can get code to human language as we want, for example:</p><p><em>Solution 3.3:</em></p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}</pre><pre>name = &#39;Jack&#39;</pre><pre><strong>def</strong> average(numbers):<br>    sum_of_numbers = sum(numbers)<br>    count = len(numbers)<br>    <strong>return</strong> sum_of_numbers / count</pre><pre><strong>def</strong> problems_solved_more_than_average(name, all_scores):<br>    score_for_name = all_scores[name]<br>    score_average = average(all_scores.values())<br>    <strong>return</strong> score_for_name - score_average<br>                <br><strong>if</strong> problems_solved_more_than_average(name, scores)  &gt;= 1:<br>    <strong>print</strong> (&#39;YES&#39;)<br><strong>else</strong>:<br>    <strong>print</strong> (&#39;NO&#39;)</pre><pre>YES</pre><p>Q: How do we decide which parts of code to define as functions?</p><p>Q: Which part of code / logic changed compared to Problem 2?</p><p>A: How we decide on who gets into the next round based on their score.</p><p>Solution 3.4:</p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}<br><br>name = &#39;Jack&#39;<br><br><strong>def</strong> average(numbers):<br>    sum_of_numbers = sum(numbers)<br>    count = len(numbers)<br>    <strong>return</strong> sum_of_numbers / count<br><br><strong>def</strong> passed_to_next_round(name, all_scores):<br>    score_for_name = all_scores[name]<br>    score_average = average(all_scores.values())<br>    <strong>return</strong> score_for_name - score_average &gt;= 1<br>                <br><strong>if</strong> passed_to_next_round(name, scores):<br>    <strong>print</strong>(&#39;YES&#39;)<br><strong>else</strong>:<br>    <strong>print</strong>(&#39;NO&#39;)</pre><pre>YES</pre><p>Notice how our code is now longer than the initial solution, but more understandable.</p><p>Bonus points. Remember ternary operator? :)</p><pre>scores = {<br>    &#39;John&#39;: 12,<br>    &#39;Jack&#39;: 16,<br>    &#39;Jane&#39;: 17<br>}<br><br>name = &#39;Jack&#39;<br><br><strong>def</strong> average(numbers):<br>    sum_of_numbers = sum(numbers)<br>    count = len(numbers)<br>    <strong>return</strong> sum_of_numbers / count<br><br><strong>def</strong> passed_to_next_round(name, all_scores):<br>    score_for_name = all_scores[name]<br>    score_average = average(all_scores.values())<br>    <strong>return</strong> score_for_name - score_average &gt;= 1<br>                <br><strong>print</strong>(&#39;YES&#39; <strong>if</strong> passed_to_next_round(name, scores) <strong>else</strong> &#39;NO&#39;)</pre><pre>YES</pre><p>Before, we used structures like lists and dictionaries to easily store and edit <strong>data</strong>.</p><p>Functions allow us to <em>isolate</em> pieces of <strong>code</strong>, so complicated computations read easier. Now you can look over this code quickly without knowing exactly what the criterion for passing is. This is called <strong>abstraction</strong>, when you abstract from details to be able to only look at what you need to know.</p><h3>Summary</h3><p>Code is written for people to read and change. To make it easy to read and change, we use data structures (like lists or dictionaries) and code expressions (like for loops, if-else statements or functions like “len”). We also define our own functions to try and make code so easy to understand it almost reads like human language.</p><p>A natural next step after this workshop would be to introduce classes:</p><pre>built-in function (len, sum)          ⟷ functions (def …)</pre><pre>built-in data structures (list, dict) ⟷ <strong>classes </strong>(class …)</pre><p>Nevertheless, I imagine classes may not be <em>necessary </em>for a lot of applications people have in mind when starting to code.</p><p>Please feel free to contact me if you have any corrections or suggestions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAbBynliPp9o5yTckIgV6w.jpeg" /><figcaption>P. S. Medium requires a title picture for every article, so here is a blurry pavement from Sintra, Portugal</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d45a5d2b60c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making text search learn from feedback]]></title>
            <link>https://medium.com/filament-ai/making-text-search-learn-from-feedback-4fe210fd87b0?source=rss-bf9e863a77c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fe210fd87b0</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Martin Davtyan]]></dc:creator>
            <pubDate>Tue, 29 May 2018 08:59:33 GMT</pubDate>
            <atom:updated>2018-05-29T12:07:11.156Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking together a search engine and getting it to improve as people use it</h4><p>Full text search has lots of applications, from customized website search engines to enterprise knowledge management systems. There are very elaborate tools (e.g. <a href="https://www.elastic.co/products/elasticsearch">Elasticsearch</a>) that will allow you to set up a full text search index for pretty much anything. As soon as people start using your search, you start getting feedback: information about which search results get clicked on and which get skipped. Unfortunately, a lot of times this information isn’t used.</p><p>In this post we are going to <strong>build a toy search engine in Python</strong>, using <a href="http://www.nltk.org/">nltk</a> and <a href="http://scikit-learn.org/stable/">scikit-learn</a> to:</p><ol><li>Give you a basic understanding of how classic full text search works</li><li>Propose a simple way to utilise user feedback to improve search results</li></ol><p><strong>You don’t need any knowledge of machine learning</strong> to understand this post, only Python and basic math notation.</p><h3>Classic search</h3><p>Suppose we have a collection of documents, for example, different web pages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6526af9751cae3f3d8ee544b03896a3a/href">https://medium.com/media/6526af9751cae3f3d8ee544b03896a3a/href</a></iframe><p>Consider a user who wants to find contact information and types in a query into a search box: query = &#39;contacts&#39;</p><p>Just like with Google, our job is to come back with a set of documents, sorted by their relevance to the user’s query. We aim to have the most relevant results on top of the page. For that, we would like to come up with a number, a <strong>score</strong>, to quantify how relevant a particular document is to a given query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjlEHTjlE9yAYaBlYmPgJA.png" /></figure><p>Once we figure out how to compute these scores, our search can work like that:</p><ol><li>For a given query, compute scores for all documents in the collection</li><li>Sort all documents according to their scores</li><li>Return <em>N</em> documents with a highest score</li></ol><h3>Tokenization and stemming</h3><p>If we want to quantify how a particular document is relevant to a given query, a simple idea would be to count a number of overlapping terms. Splitting a text into words (while removing punctuation, etc.) is called <a href="https://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html"><strong>tokenization</strong></a> and it’s very easily done with NLTK:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e7b10e9d6efa0716fb213bb7a6b1e1f/href">https://medium.com/media/0e7b10e9d6efa0716fb213bb7a6b1e1f/href</a></iframe><p>We are still not going to find any overlapping words between the document and the query, because “contacts” is not capitalized and is in plural form. To solve this issue, we use <a href="https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html"><strong>stemming</strong></a> to strip words of their plural forms, formatting, etc.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/002b4858ef872884b28d2483fd1baff8/href">https://medium.com/media/002b4858ef872884b28d2483fd1baff8/href</a></iframe><p>We also transform a user query into a list of terms:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1dc87be7db40c151afb4b5f1858b531/href">https://medium.com/media/c1dc87be7db40c151afb4b5f1858b531/href</a></iframe><p>Great, if our score is now a number of overlapping terms between a query and a document, docs[1] scores 1 while the other two score 0. We can now sort documents based on that score and show to our user. Our first search system is ready.</p><h3>Vector Space Model</h3><p>One problem with our first approach is that all terms count the same towards a relevance score. For example, a query-document pair (“a cat”, “this is a page about dogs”) will have the same score as a pair (“a cat”, “my favourite cats”), as both of them have exactly one overlapping term (“a” for the first pair, “cat” for the second). Intuitively, if “cat” is a rare term in our document collection, any document which does mention it should score high for this query. On the other hand, “a” is so frequently seen that it shouldn’t matter much if it is metioned in a query or not: queries “cat” and “a cat” should return the same results.</p><p>Of course, to address this issue we could just have a list of so-called <a href="https://nlp.stanford.edu/IR-book/html/htmledition/dropping-common-terms-stop-words-1.html"><strong>stop words</strong></a> — words we want to exclude from consideration as they are too popular. A more elaborate approach would be to <strong>weight</strong> counts of terms by their popularity.</p><p>To do this, it is useful to think of texts not as lists of terms, but rather as numerical vectors in a common vector space. In a field of Information Retrieval, this view is called a <strong>vector space model</strong>.</p><p>A simple way to map each text (document or query) to a vector in the same space is:</p><ol><li>Extract a set <em>T</em>​ of all unique terms mentioned in the collection of documents — this is called a <strong>vocabulary</strong></li><li>Sort the vocabulary alphabetically, so that each unique term <em>t </em>∈<em> T</em> has an index</li><li>Map each document to a vector <em>v</em>​, where <em>v[i]</em>​ is how many times term<em> t[i]​ </em>has been used in the document — so called <strong>term frequency (tf)</strong></li></ol><p>This representation is called <strong>bag of words</strong>.</p><p>To make “cat” count more because it’s less popular, we can multiply the <strong>tf</strong> components of the vector corresponding to different terms with the measure of rarity, called <strong>inverse document frequency</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bN3GmAiNecqmFd9d_9LANg.png" /></figure><p>This way to represent documents as vectos is called <strong>tf-idf</strong> and can be easily computed with scikit-learn Vectorizer class. Let us use it to score documents.</p><h3>Scoring</h3><p>We first gather the vocabulary across the entire collection of documents by calling the fit method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d32972e9c316a03baffeb90932f58420/href">https://medium.com/media/d32972e9c316a03baffeb90932f58420/href</a></iframe><p>Every term now is mapped to a index in a vector we are going to be outputting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92725d7548ba1e7c638d010b6d72d211/href">https://medium.com/media/92725d7548ba1e7c638d010b6d72d211/href</a></iframe><p>Now we can transform texts into vectors, e. g. queries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497178d9b80a112b2706352bf0d01738/href">https://medium.com/media/497178d9b80a112b2706352bf0d01738/href</a></iframe><p>As each document and query is now respresented as a vector, we can now say the score is a similarity of these two representations, for example, <strong>cosine similarity</strong> — cosine of an angle between two vectors. If two vectors in this (|<em>T</em>|-dimensional) space have similar directions, that means they have similar terms mentioned in them.</p><p>Let’s calculate cosine distance between the query vector and all vectors for all documents we have in our collection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ff47e37d6d9fb05bbdc3e2f8b044cba/href">https://medium.com/media/2ff47e37d6d9fb05bbdc3e2f8b044cba/href</a></iframe><p>These are our <strong>scores</strong>! Intuitively, similarity between the query and docs[0] is zero as there is no term overlap at all.</p><p>We can now order (rank) documents by their scores (from high to low):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9162ebb77c3aaa618d202f1090467f0/href">https://medium.com/media/b9162ebb77c3aaa618d202f1090467f0/href</a></iframe><p><strong>Success</strong>, we hacked together a search engine based on a tf-idf vectorizer: we extract a vocabulary from a collection of documents and, when a user comes with a query, return a document with the closest (in terms of cosine similarity) vector to the query. We could, of course, easily return top 10 documents as well.</p><h3>Features</h3><p>Our simple system only uses one bit of information to score documents for a query: similarity of tf-idf vectors. If we want to improve the search, we may take other things into consideration, i.e. sizes of documents, how close seach terms are in the text, how new the document is, etc. As long as all these things can be expressed as floating point numbers, we can just calculate the score as a weighted sum of these different features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVicY_KqNEYLFrcBB997zA.png" /></figure><p>Weights <em>w[i]</em>​ allow us to control how relatively important features<em> f[i]</em>​ are. For example, if we think that bigger documents are going to be of more interest to users, we can add document size as a feature to our system with a small weight (compared to that of tf-idf similarity) and look at feedback to see if it improves results.</p><h3>Improving search with feedback</h3><p>Let’s imagine people started using our machine learning system and we have received some feedback on which results turned out relevant and which not:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/042413c85aee947c3f0892f4190432ee/href">https://medium.com/media/042413c85aee947c3f0892f4190432ee/href</a></iframe><p>In this dict keys are queries and values are (document index, feedback value) pairs, where 0. means irrelevant and 1. means relevant. Let’s see what our current search system would return for the given query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68030dfc2cfc4ff7fbecce73e85d5fa9/href">https://medium.com/media/68030dfc2cfc4ff7fbecce73e85d5fa9/href</a></iframe><p>So, our system returns a chatbot-related page as it mentions the right term, but people mostly want to see About us page, judging by the feedback. How do we incorporate this information in our results?</p><h3>Machine-learned scoring</h3><p>A widespread approach to improve search performance with feedback is using machine learning to optimise feature weights <em>w[i]</em>​ from the score formula. For example, imagine we only have two features and a bunch of examples of relevant (R) and non-relevant (N) documents from feedback. Feature weights will then define a direction of a separating line, where the score above a given threshold would capture most relevant items:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DX1TjIigGSTWnlilXYAWA.png" /><figcaption>Given examples of relevant (R) and non-relevant (N) responses, you could train a classifier to separate the two classes</figcaption></figure><p>When stated this way, it is a classification problem: we are looking to classify documents into relevant and irrelevant based on their features. In a more complicated formulation, we want to not only estimate if documents are relevant, but rank them by relevance like in the above example. This could be viewed as a problemn of <a href="https://en.wikipedia.org/wiki/Ordinal_regression">ordinal regression</a>. For web search, a popular learning to rank algorithm is a so-called <a href="https://en.wikipedia.org/wiki/Ranking_SVM">Ranking SVM</a>.</p><p>One problem with using ML in this case is that even the most basic methods (e.g. Naive Bayes to classify documents into relevant and irrelevant) require quite a lot of data. If you just started gathering feedback or you don’t have a lot of users to learn from, they might not work. In the last bit of post we show a very simplistic approach to use feedback without using much data.</p><h3>Nearest neighbour feedback as a feature</h3><p>If you are given a particular query (e.g. &#39;who makes chatbots&#39;), an intuitive thing to do when you have feedback data is to look if this query was asked before. If it did, we would have some data on which documents appeared relevant or irrelevant to other users before. We would then score relevant documents higher and irrelevant documents lower.</p><p>To combine this logic with our previous approach of scoring based on tf-idf similarity, let us define <strong>feedback features: positive and negative</strong>. Positive feedback feature would equal the number of times a given document appeared relevant for a given query. Negative feedback feature would be the number of times a document appeared irrelevant. Both features would be 0 if we don’t have feedback for a given query-document pair, so it doesn’t impact our score.</p><p>But what if the exact given query has not been asked before? For example, we need to score documents for a query &#39;who is making chatbots information&#39;. We could find the <strong>nearest neighbor</strong> query - one closest (in terms of tf-idf, as always) query we do have feedback for. Then, we could <strong>weight</strong> our two feedback features by the similarity. This way, if we find a query which is very similar to the given one, feedback features impact the overall score a lot, but otherwise the features are close to zero.</p><p>For example, consider the <strong>positive feedback feature</strong>. For query <em>q</em> let us find a closest feedback query <em>q’</em>​, i.e. the query with the highest cosine similarity <em>​ρ(q, q’).</em> For query <em>q’</em>, we have seen a set of documents <em>{d[j]} </em>with positive judgments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EL40KYtu2ji0ox7MknP2Zw.png" /><figcaption>We give positive feature values to documents d[1] and d[2]— they appeared relevant (R) for a query similar to q</figcaption></figure><p><strong>Let us score each document with a proportion of postive feedback they received</strong> for <em>q’</em>. Then, let’s weigh all the scores by the similarity between the original query <em>q</em> and the nearest neighbour query <em>q’</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rss8VX7Fq3C8q0ijldEalQ.png" /></figure><p>Let’s quickly implement the positive feedback feature it and see it works. For a given query, find a nearest neighbor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0a965592fe18c18fc91754736ced2b/href">https://medium.com/media/fa0a965592fe18c18fc91754736ced2b/href</a></iframe><p>Look at all documents that received positive feedback</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a7cab000da3592e1d2236409365f61/href">https://medium.com/media/b1a7cab000da3592e1d2236409365f61/href</a></iframe><p>What is the proportion of positive feedback for different documents?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb114deed2a931d68acf6daa5539bf67/href">https://medium.com/media/cb114deed2a931d68acf6daa5539bf67/href</a></iframe><p>Finally, let’s scale with a similarity between the original query and nearest neighbor query, and output a feature vector:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6f2d3e6c0f045b4405eab3948dba7e6/href">https://medium.com/media/a6f2d3e6c0f045b4405eab3948dba7e6/href</a></iframe><p>That is our feature vector! Positive feedback feature has the biggest value for the document most people thought was relevant for the nearest neighbour query. Makes sense.</p><h3>Scorer</h3><p>To combine the positive feedback feature with the tf-idf feature we developed before, let’s summarize our code in a Scorer class that can take a collection of documents and improve scoring based on positive feedback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2735b12d5e787a8a52d1751d6a5a8aad/href">https://medium.com/media/2735b12d5e787a8a52d1751d6a5a8aad/href</a></iframe><p>Let’s see if it produces scores we expect before we show it any feedback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e40a8492f0f8670e77e33fef40a923a6/href">https://medium.com/media/e40a8492f0f8670e77e33fef40a923a6/href</a></iframe><p>Indeed, ‘chatbots’ and ‘information’ match the two last documents in the collection. Based on these scores we would return the last document:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b23993c6059b00e59f628cd9881e8da0/href">https://medium.com/media/b23993c6059b00e59f628cd9881e8da0/href</a></iframe><p>Now let’s give feedback to the scorer and see if changes the scores:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d47d468a2367d65ca538db7d06a7e73/href">https://medium.com/media/1d47d468a2367d65ca538db7d06a7e73/href</a></iframe><p>As expected, we now score the first document the highest, as it received some positive feedback. Note that our feature weights attribute larger importance to feedback, this is why the resulting scores changed so much. If valued the tf-idf feature more, scoring would change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9712960fd9edfc59bb4c4127f6e0d035/href">https://medium.com/media/9712960fd9edfc59bb4c4127f6e0d035/href</a></iframe><h3>Summary</h3><p>In this post we showed how to hack together a simple text search engine that:</p><ol><li>Works based on document contents</li><li>Learns from feedback</li></ol><p>Obviously, for the sake of simplicity we excluded a lot of details that could improve the quality but, as you can see, to quickly come up with something that works is easy if you have a basic idea :)</p><p>If you have any questions about the material or you want to chat about your NLP/ML project, feel free to email me — martin.davtyan at filament dot ai.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fe210fd87b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/filament-ai/making-text-search-learn-from-feedback-4fe210fd87b0">Making text search learn from feedback</a> was originally published in <a href="https://medium.com/filament-ai">Filament-Syfter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>