<?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 Bassim Eledath on Medium]]></title>
        <description><![CDATA[Stories by Bassim Eledath on Medium]]></description>
        <link>https://medium.com/@bassim_eledath?source=rss-3646d306eb30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1_sJAp8Bs0psoND7uudqng.jpeg</url>
            <title>Stories by Bassim Eledath on Medium</title>
            <link>https://medium.com/@bassim_eledath?source=rss-3646d306eb30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:46:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bassim_eledath/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[What We've Learned 3 Years into Harness Engineering]]></title>
            <link>https://medium.com/asurion-product-development/what-weve-learned-3-years-into-harness-engineering-1e8e01943661?source=rss-3646d306eb30------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e8e01943661</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[enterprise-ai]]></category>
            <dc:creator><![CDATA[Bassim Eledath]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 07:10:30 GMT</pubDate>
            <atom:updated>2026-10-20T13:03:07.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>What we’ve learned 3 years into Harness Engineering</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wA3iNhcy8Ek7KEX_ZzTPeA.png" /></figure><p>Putting a great model in a bad harness is like putting Usain Bolt in flip-flops. We saw this a little while ago with <a href="https://openai.com/index/how-two-settings-tripled-our-arc-agi-3-scores/">GPT-5.6 Sol performing poorly on ARC-AGI-3 because of two mismanaged settings: retained reasoning and compaction</a>. The default harness of the benchmark discarded the model’s reasoning after each move and dropped earlier actions as context filled up, so it kept starting over. Once both were enabled, the score nearly tripled from 13.3% to 38.3%.</p><p>At Asurion, a good harness is the difference between a customer getting the help they need and a conversation going in circles. We’ve been toiling with agentic frameworks since GPT-3.5, helping customers with problems as varied as a tablet that won’t charge, collecting the details a human expert needs to pick up a case, or activating a brand-new phone. This post traces how that thinking evolved over three years, culminating in AURA: a single harness we now use across many of our conversational AI use cases.</p><h3>The early days: decision trees</h3><p>One of our early production use cases was tech troubleshooting over chat. A customer opens a session with something like “my phone won’t stop ringing,” and we walk them through a sequence of steps to diagnose and fix it. That sounds simple, and on the happy path, where the customer answers exactly as we expect at every turn, it is. But real sessions are rarely that straightforward. Customers often describe their problem loosely, so we first have to work out what they actually mean via clarifying questions (like “do you have an iPhone or an Android?” since each has different steps), and even after we have those preliminary details, they might switch intents midway through. For example, they might abandon the ringing problem three steps in to ask why their texts suddenly won’t send.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5HC1zq_KZpo3QANf0EQWA.png" /><figcaption>Decision trees choose the next troubleshooting step</figcaption></figure><p>Back when we didn’t have reasoning models, we had to rely on the harness to handle all of that messiness. Our first system, like many at the time, was built on LangChain and Haystack, and its intelligence was really two large hand-written decision trees. The first was a gatekeeper that ran on every message and asked a few things: should we even be troubleshooting right now? Is the customer asking for a human? Is this really a billing or account issue we can’t touch? Then we had a second tree that decided the actual troubleshooting move (or next best action): which device we’re on, which step comes next, and whether the customer had switched problems or was ready to give up and talk to a person. We also had several binary classifier LLMs that we called checkers, which fed those trees the yes-or-no facts they branched on, each answering one narrow question like “is the issue resolved?” or “are they ready for the next step?”</p><p>It was a lot. It gave us predictable behavior and kept the model on a short leash, but it was also an incredibly large codebase that was becoming overbearing to manage. Worse, it was rigid and very difficult to adapt to new use cases, particularly the one that had just popped up: guiding a caller through a structured information-collection flow over the phone, gathering the details a specialist needs to pick up their case (now an important use case for us).</p><h3>The voice harness: state machines and latency</h3><p>So we built a second harness from scratch, this one specifically focused on voice. We did a few things differently this time:</p><ul><li><strong>Fewer dependencies:</strong> No more LangChain or Haystack. By that point, the third-party frameworks were costing us more than they saved. The non-domain-focused code of a harness is comparatively very light and was not worth outsourcing for us.</li><li><strong>An explicit state machine:</strong> We modeled the customer call as a finite state machine where each “phase” of the call (such as the intent detection phase, clarifying questions phase, etc.) is a state, and the LLM during any phase can emit a signal to tell the engine to stay, advance, or hand off to a human agent (signals here are just string flags like “ESCALATE”). For example, when a caller says, “I need to report a problem with my tablet,” the following happens in order:</li><li>The LLM in the intent detection phase figures out what the call is about, tags it report_issue, and returns COMPLETE because intent has been figured out, so the engine advances to the next phase, clarifying questions, to collect the details the specialist will need.</li><li>The LLM in the clarification phase asks for those details, like “when did you first notice it?”, returning STAY to keep asking until it has them, then COMPLETE.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9f0ZLD6yDocRoalw_FwOWA.png" /><figcaption>A state machine guides each phase of the call</figcaption></figure><p><strong>Latency optimizations:</strong> Waiting 5 seconds for a response on chat is okay (expected, even) but over a phone call it’s unbearable. So we split the work in two, a pattern we call the gateway-response architecture: one model decides, the other model tunes the wording. Say the bot just asked “when did you first notice this problem?” and the caller says “yesterday.” The first model, the gateway (smarter but slower), doesn’t write the reply at all. It just emits structured output, something like {&quot;answer&quot;: &quot;past&quot;, &quot;valid&quot;: true}, meaning the caller gave a valid answer and it’s a date in the past. Then the second model, the response model (faster), formats the already-chosen next question into natural wording. The gateway model stays fast because it emits a few tokens instead of sentences, and the response model is quick because formatting is lighter than reasoning about what to do. Meanwhile the safety checkers (is the caller frustrated? asking for a human?) are designed so they don&#39;t add latency to the turn. In our experiments, running two models sequentially like this not only improved response quality; it was also surprisingly faster than having a single model (with a larger prompt) do everything end-to-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAvpZU5BbQfFuKMitwwrBw.png" /><figcaption>One model decides, another words the response</figcaption></figure><p>This harness did its job well, but like the troubleshooter before it (and the many other harnesses we were maintaining), it was purpose-built and overfit for a single job. Before long, we were managing several harnesses at once, each specialized for its own purpose. As usage of our services scaled, so did the maintenance burdens. If our LLM gateway changed its request schema, all our client services across the harnesses would need to be updated. A lot of duplicated effort.</p><p>There was clearly a strong need for consolidation, and when reasoning models became fast enough for conversational AI, this finally became possible. When you can finally trust a model to reason, harness engineering becomes much simpler (by goal, not practice). In essence, your harness only has two responsibilities:</p><ol><li>Getting the right context to the LLM</li><li>Exposing the right set of tools/actions.</li></ol><p>And you leave the model to reason about the rest. It is worth pausing here to admire the simplicity of that as the rest of the blog post addresses the implications of it.</p><h3>AURA: one harness, many contributors</h3><p>This realization resulted in the framework we now use called AURA (Asurion Unified Real-time AI). It is one harness designed to power any conversational AI use case, across channels (chat and voice today).</p><p>At the heart of AURA is what we call a “contributor,” which is a plugin that exposes context and/or tools, and can be active or inactive. Some examples:</p><ul><li>In some deployments, we have an intent detection contributor that becomes active at the beginning of the conversation and exposes context about available intents and tools such as record_intent, which the LLM calls once it’s confident about why the customer reached out. Once the intent is recorded to state, the intent detection contributor becomes inactive.</li><li>The troubleshooting contributor injects the user’s device and the steps tried so far, with tools to log each step or flag that the customer is blocked.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6F0i6SPkr5GhT3xCoWanw.png" /></figure><ul><li>RAG? Also just a contributor! It exposes a search_kb tool, and when the LLM calls it, the contributor runs the search and injects the matching articles right back into context.</li><li>We have contributors for channels too. For example, when a session is live voice, a contributor switches on that adds system prompt instructions to keep responses short and conversational.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SN3h1PZ3oVYIb0cCpsVBUg.png" /><figcaption>Each contributor provides context and tools</figcaption></figure><p>Notably, many of our deployments have an escalation contributor that is always active because a user may ask for a human agent at any time, and that exposes the necessary context and tools for the LLM to route to a human.</p><p>Under the hood, a contributor is just an object that answers three questions about the current state:</p><ul><li>Am I active? Should this contributor participate in the current turn at all?</li><li>What context do I inject? The instructions or state the LLM needs while I’m active.</li><li>What tools do I expose? The actions the LLM is allowed to take while I’m active.</li></ul><p>Here is a grossly simplified version of what an intent detection contributor looks like:</p><pre>class IntentContributor(Contributor):<br>    def is_active(self, state, user_input) -&gt; bool:<br>        return state.intent is None              # active until an intent is on state<br><br>    def get_injections(self, state, user_input) -&gt; list[ContextInjection]:<br>        return [ContextInjection(&quot;intents&quot;, f&quot;Figure out why the customer is reaching out. Options:{INTENTS}.&quot;)]<br><br>    def get_tools(self, state) -&gt; list[ToolDef]:<br>        return [record_intent]                   # records the intent to state</pre><p>Why can’t the contributors be active all the time? The obvious answer here is noise. Every extra instruction and tool you hand the model is one more thing it can misread or misfire, and a longer prompt is slower and more expensive on every single turn for context the model was never going to use.</p><p>A natural follow-up question may be “why not have some semantic matching for contributors similar to how Claude Code has <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool">tool search</a>?” Well, besides keeping context lean, contributors are the way to have some form of steerability. For example, if an action isn’t part of a given use case, we simply don’t load the contributor that provides it, so the model never has that tool to call, however the customer phrases the request. (We still instruct the model not to promise outcomes it can’t deliver: removing a tool removes the action, not the temptation to talk about it.) So being able to disable contributors is as important as being able to enable them.</p><p>The big payoff with contributors being these modular units of context/actions is composability. Any new client, for any use case, for any channel, is now just a list of contributors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BD9QdQyV7X5LDKcoYQOacw.png" /><figcaption>Different use cases compose different contributors</figcaption></figure><h3>The rest of the harness</h3><p>Beyond contributors, there are other primitives of AURA worth briefly mentioning:</p><ul><li><strong>State:</strong> Typed, lives in an in-memory cache. If a newer turn starts on the same conversation while an older one is still running, the older turn is detected as stale and its write is discarded instead of overwriting newer state.</li><li><strong>Checkers:</strong> Small validators that review the model’s replies (if configured). They can flag a reply, attach an action like an escalation, or rewrite it. They’re an additional layer of review on top of the boundaries contributors already set.</li><li><strong>Background reasoning:</strong> A stronger model runs in the background after each turn and leaves a hint that the usually smaller, faster main model picks up on the next turn. The customer never waits on it, and if a hint arrives too late to be relevant, it’s simply dropped.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rdvUO_6hA6SUAJ70lIV-g.png" /><figcaption>Background reasoning leaves hints for the next turn</figcaption></figure><h3>Observability</h3><p>A harness engineering blog post wouldn’t be complete without us addressing observability in some way. We trace/record every turn of every conversation end to end through our observability platform, so any production session can be pulled back up, replayed, and inspected span by span, from the context each contributor injected down to every tool call the model made.</p><p>That tracing is also what powers what we call “expectations”, our umbrella term for the two forms of tests that guard the harness. Benchmarks are fixed expectations checked against a real turn or conversation. Some are blocking: verifiable, binary things that must always hold, and we treat a regression on any of them as a release blocker. For example, when a caller asks for a human, the bot <em>must</em> raise the escalate flag. If that does not hold true we cannot push to prod.</p><pre>async def test_agent_request_escalates():<br>    outcome = await run_turn(<br>        TurnInput(session_id=&quot;t-1&quot;, client_id=&quot;example_client&quot;, user_message=&quot;just get me a human&quot;),<br>        client=example_client, store=InMemoryStateStore(),<br>    )<br>    assert any(a.type == &quot;escalate&quot; for a in outcome.actions)</pre><p>Others are non-blocking: expectations we don’t pass every time given the current state of the model and architecture, but that we steadily push toward 100%. A customer says roughly when something happened and the LLM has to turn that into the right date, the kind of thing that’s correct most of the time but not always.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SERd4cPUqa8IEtO_b9kjuQ.png" /><figcaption>A Non-blocking benchmark</figcaption></figure><p>Simulations are our third type of test and they are like integration tests: an LLM plays the customer across a whole conversation (say, a customer who isn’t very technical setting up a new phone and getting stuck halfway through), and success is more subjective, but it’s an important qualitative gate before we ship. Simulations can still include verifiable expectations, like “somewhere in this conversation the bot must call record_intent.” Between the two, we cover the bases: the things that must not regress, and the messy end-to-end behavior we can only really judge by playing it out.</p><h3>A shift in roles</h3><p>Stepping back, AURA is logically (as well as in code) separated into three layers: config, contributors, and core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnPvTVvno3NhdkeCVQS9Uw.png" /></figure><ul><li>Config is the client layer, pure configuration that composes contributors into a specific product, owned by the teams closest to each client or use case.</li><li>Contributors are the reusable plugins we talked about.</li><li>Core is the engine underneath: the turn loop, state in an in-memory cache, tracing in our observability platform, the client for our internal multi-provider model gateway, etc.</li></ul><p>Core lives in its own repository on purpose, because it turns out not to be specific to conversational AI at all (one of our internal tools, a slide-deck creator, runs on the same core with an entirely different set of contributors).</p><p>A surprising byproduct of this is how our roles have been redefined by this architecture. We used to spend our time writing long prompts and standing up whole harnesses; now the job is mostly writing contributors. When a new client, use case, or channel shows up, the first question is no longer “what pipeline do we build?” but “what does the model need to see and be able to do here, and which contributors provide it?” The ML teams get better at building reusable contributors, and the client teams get faster at composing them into products.</p><h3>What’s next for AURA</h3><p>Two things we’re working on next:</p><ol><li><strong>AURA as an agent runtime:</strong> Everything so far is turn-based: a message arrives, a turn runs, a reply goes out. But some problems don’t wait for the customer to respond (they have to be proactive). For example, an internal assistant that supports human experts live during a call, where the model has to decide not just what to say but whether to say anything at all. So we’re designing the next version of AURA as an agent runtime that can act on events, not just messages.</li><li><strong>AURA as a platform:</strong> A great harness gets you a great agent, but keeping it great, or even improving it based on user feedback, is its own problem. So we’re building a platform where the teams closest to each use case can keep their agent healthy without touching framework code. They’ll be able to easily review and filter problematic conversations in production, group them by topic, and create benchmarks and simulations. We’re currently piloting this.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e8e01943661" width="1" height="1" alt=""><hr><p><a href="https://medium.com/asurion-product-development/what-weve-learned-3-years-into-harness-engineering-1e8e01943661">What We&#39;ve Learned 3 Years into Harness Engineering</a> was originally published in <a href="https://medium.com/asurion-product-development">asurion-product-development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Duplicate Questions using DataSketch]]></title>
            <link>https://medium.com/@bassim_eledath/finding-duplicate-questions-using-datasketch-2ae1f3d8bc5c?source=rss-3646d306eb30------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ae1f3d8bc5c</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bassim Eledath]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 22:07:11 GMT</pubDate>
            <atom:updated>2019-05-08T00:24:29.814Z</atom:updated>
            <content:encoded><![CDATA[<p>An implementation of MinHashing and LSH in Python.<br>Bassim Eledath and Rebecca C. Steorts, Duke University, Department of Statistical Science<br>Email: bassim.eledath@duke.edu; beka@stat.duke.edu</p><h3>Summary</h3><p>While previous articles addressing LSH (on Towards Data Science) have been largely theoretical, this article is aimed towards practitioners who wish to use LSH and MinHashing for tabular string data using Python.</p><h3>What is LSH?</h3><p>Put very simply, LSH is is an algorithmic technique that hashes similar input items into the same “buckets” with high probability. This technique is commonly paired with MinHashing to de-duplicate documents. More on this coming up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*2QrbFeTpFXbCz3Dsp_z9Xw.png" /><figcaption>A quick overview of the process</figcaption></figure><h3>Kaggle vs Real Life</h3><p>The data for this case study comes from Quora’s question pairs <a href="https://www.kaggle.com/c/quora-question-pairs">challenge</a>. We are given pairs of questions with labels indicating if they are duplicates or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*millcCzo2yxllycYcxtmKw.png" /><figcaption>Table 1: few rows from the dataset</figcaption></figure><p>The goal of the Kaggle challenge is to identify if the pair of questions are duplicates. But like many Kaggle challenges, this is an idealized scenario that does not reflect reality.</p><p>Put yourself in Quora’s shoes. You receive several questions (hundreds of thousands of them) in real time and you have to detect if there are similar questions that have already been answered. Notice, these questions don’t come in pairs. Suddenly, the sophisticated neural network classifier you created for the competition cannot be directly used!</p><h3>The Fundamental Problem</h3><p>For any classifier to work, we need to get the questions in pairs (see Table 1). Naively, we can pair every question with each other and proceed from there. But this is problematic. With thousands of questions from Quora’s question pairs<a href="https://www.kaggle.com/c/quora-question-pairs"> challenge</a>, it is simply not computationally feasible to compare all-to-all questions. This entails quadratic runtime complexity. We wish to only compare questions that are “similar” in order to save computational resources.</p><h3><strong>Don’t panic: MinHash and LSH to the rescue</strong></h3><p>In this article, we give a high-level overview of why these algorithms are used and gloss over the details. We encourage those interested in the technical details to see the literature we refer to at the end of our article for further reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*ZXbEgRvrpcLDMgGjyBqG2w.png" /><figcaption>Table 2: the process</figcaption></figure><ol><li><strong>Set Representation</strong>: As we see in Table 2, we first represent the questions as set representations of tokens known as k-shingles (k-grams, k-tokens) to ensure the probability of obtaining each shingle is low in the document space. For example, if we have a question like “Why are cats so cute?”, and we want to create shingles with k=1, we would end up with the following set representation: [“Why”,”are”,”cats”,”so”,”cute?”]. And with k=2:<br>[“Why_are”,”are_cats”,”cats_so”,”so_cute?”,”cute?_Why”]. Notice, the probability of finding each token in the union of shingles is lower in the second case with k=2 (finding “are_cats” is rarer than finding “cats” in other questions).</li><li><strong>MinHashing:</strong> Comparing compact vectors of integers is much easier than comparing strings or their sparse numeric representations. One way to create such a numeric representation of a question is to put it in a long vector that indicates the words from the entire corpus (the several thousand questions) used in the question (shown in the figure below).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*_ANAaUKMMdo1mI6B" /></figure><p>But as you may have guessed, the dictionary of words may be too long when you have several questions and our vector representations of questions would be too long and difficult to compare for similarity.</p><p>Hence, we compute the MinHash signatures for each question. What MinHash does is it creates a fixed length numeric “fingerprint” for each question, the size of which is a parameter that can be tuned by the user. Each number in the fingerprint is created by a random permutation of rows in the dictionary of words. To get a complete picture of this algorithm, we encourage you to check out this article <a href="https://medium.com/engineering-brainly/locality-sensitive-hashing-explained-304eb39291e4">here</a>. At a high level, the MinHash algorithm makes this vector representation far less sparse and easy to compare with other signatures for similarity.</p><p>To compare the similarity between two questions we compare their respective fingerprints and calculate their Jaccard Index, which is simply the number of integers that are in common between both signatures divided by the total number of integers in both signatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*lPCSJPMZQtoZCUyJ" /></figure><p><strong>3. LSH: </strong>Now that the questions how a compact numeric representation, and we’ve defined a similarity metric, we still have the problem of having to compare each signature with each other. That would still take a very long time. Ideally, you would want to compare questions that are more likely similar with each other, rather than comparing two completely different questions with each other.</p><p>To resolve this, we first change the way we calculate the MinHash signatures. Instead of using random permutations (refer to linked article for more details), we use hash functions to map the strings to their fingerprints. So if we get a new question, instead of looking at the entire dictionary of words to calculate its signature, we simply have to run a fixed number of hash functions on the questions. We then bucket those hash functions into bands.</p><p>When a new question arrives, and we want to determine whether there exists another similar question, we will go over every such band (see Table 2), and look for questions that share the exact same MinHash values on every row of that band. If such question exists, we’ll attempt the full MinHash comparison. For more details on this part of the process, refer to this article <a href="https://duvni.com/2017/10/minhash-lsh/">here</a>.</p><p>Links for further reading on theoretical concepts:<br><a href="https://medium.com/engineering-brainly/locality-sensitive-hashing-explained-304eb39291e4">https://medium.com/engineering-brainly/locality-sensitive-hashing-explained-304eb39291e4</a> (introductory)<br><a href="http://infolab.stanford.edu/~ullman/mmds/ch3.pdf">http://infolab.stanford.edu/~ullman/mmds/ch3.pdf</a> (intermediate)<br><a href="https://www.cs.princeton.edu/courses/archive/spring13/cos598C/Gionis.pdf">https://www.cs.princeton.edu/courses/archive/spring13/cos598C/Gionis.pdf</a> (advanced)</p><h3>Coding it Out</h3><p>For all the code, that was used to produce this article, see the <a href="https://nbviewer.jupyter.org/github/bassimeledath/quora_profile/blob/master/questions_analysis.ipynb">link</a> and please cite our article.</p><p><strong>Set Representation:</strong> Given that the questions are quite short in length and that I am processing the strings for stop words, I represented the questions as single word tokens. The practice of using k-shingles is more fruitful with longer documents and my intention with using MinHash and LSH isn’t to find precise duplicates but rather to find potential candidate pairs that can be further pruned with more complex algorithms.</p><pre># Set Representation</pre><pre>&#39;&#39;&#39;</pre><pre>set_dict maps question id (eg &#39;m23&#39;) to set representation of question</pre><pre>norm_dict maps question id (eg &#39;m23&#39;) to actual question.</pre><pre>May use this dictionary to #evaluate results of LSH output.</pre><pre>We loop through each question, convert them into shingles, and if the shingle isn’t a stop word,</pre><pre>we add them to a hashset which will be the value for the set_dict dictionary.</pre><pre>‘’’</pre><pre>set_dict={} <br>norm_dict={} <br>count=1<br>for question in tqdm_notebook([x for x in comb_ques[&#39;question&#39;] if type(x)==str]):<br>   temp_list = []<br>   for shingle in question.split(&#39; &#39;):<br>       if shingle not in stop_words:<br>           temp_list.append(shingle.lower())<br>   set_dict[&quot;m{0}&quot;.format(count)] = set(temp_list)<br>   norm_dict[&quot;m{0}&quot;.format(count)] = question<br>   count +=1</pre><p><strong>MinHashing</strong></p><pre><em># Create minHash signatures</em><br><br>‘’’</pre><pre>num_perm is the number of permutations we want for the MinHash algorithm (discussed before). The higher the permutations the longer the runtime.</pre><pre>Min_dict maps question id (eg &#39;m23&#39;) to min hash signatures.<br>We loop through all the set representations of questions and calculate the signatures and store them in the min_dict dictionary.</pre><pre>‘’’</pre><pre>num_perm = 256<br>min_dict = {}<br>count2 = 1<br>for val in tqdm_notebook(set_dict.values()):<br>   m = MinHash(num_perm=num_perm)<br>   for shingle in val:<br>       m.update(shingle.encode(&#39;utf8&#39;))<br>   min_dict[&quot;m{}&quot;.format(count2)] = m<br>   count2+=1</pre><p><strong>LSH</strong></p><pre><em># Create LSH index</em><br><br>‘’’</pre><pre>We set the Jaccard similarity threshold as a parameter in MinHashLSH. We loop through the signatures or keys in the min_dict dictionary and store them as bands (as described in the theory section of the article). Datasketch stores these in a dictionary format, where the key is a question and the values are all the questions deemed similar based on the threshold. But we need them in candidate pairs as they are much easier to evaluate, so we use a function called create_cand_pairs which simply changes the format of the dictionary to be a list of lists with each sub-list being a candidate pair.</pre><pre>‘’’</pre><pre>lsh = MinHashLSH(threshold=0.4, num_perm=num_perm)<br>for key in tqdm_notebook(min_dict.keys()):<br>   lsh.insert(key,min_dict[key])</pre><p><strong>Create candidate pairs</strong>: DataSketch does not have an inbuilt method to output candidate pairs, so I made one to work with the dictionary output of the LSH.</p><pre>def create_cand_pairs():<br>   big_list = []<br>   for query in min_dict.keys():<br>       bucket = lsh.query(min_dict[query])<br>       if len(bucket)==1:<br>           big_list.append([bucket[0],&quot;None&quot;])<br>       if len(bucket)&gt;1:<br>           first_val = bucket[0]<br>           for val in bucket[1:]:<br>               second_val = val<br>               big_list.append([first_val,second_val])<br>   return big_list</pre><h3>Evaluation of Results</h3><p>DataSketch does not have an inbuilt evaluation function for precision and recall, so I coded one out. The results are plotted below.</p><pre><strong>def</strong> evaluation(cand_pairs):<br>    tp = 0<br>    fp = 0<br>    fn = 0<br>    <strong>for</strong> pair <strong>in</strong> cand_pairs:<br>        <strong>if</strong> pair[1] == &quot;None&quot;:<br>            <strong>if</strong> str(norm_dict[pair[0]]) <strong>in</strong> correct_dict.keys():<br>                    fn +=1<br>        <strong>else</strong>:<br>            <strong>if</strong> isinstance(correct_dict.get(norm_dict[pair[0]]), (list,)):<br>                <strong>if</strong> norm_dict[pair[1]] <strong>in</strong> correct_dict.get(norm_dict[pair[0]]):<br>                    tp +=1<br>                <strong>else</strong>:<br>                    fp +=1<br>                    <br>    precision = tp/(fp+tp)<br>    recall = tp/(fn+tp)<br>    print (&#39;precision is <strong>{}</strong>&#39;.format(precision))<br>    print (&#39;recall is <strong>{}</strong>&#39;.format(recall))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*DeL5-Go2dQqGgjZA-qnddg.png" /></figure><h3>Interpretation of Results</h3><p>The quasi-inverse relationship between precision and recall is expected: with a lower threshold, we are more likely to see the duplicate question appear as a candidate pair. But we will also observe non-duplicate question pairs (which increases the number of false-positives). By increasing the threshold we see a decrease in false duplicate pairs but we also observe an increase in false negatives as the true duplicate pair comes up less often.</p><h3>Next Steps</h3><p>Now that we have our candidate pairs, we have significantly reduced our comparison space to pairings of questions that are similar to each other. In other words, we have the data in a format like the Kaggle competition where more sophisticated classification algorithms can be used to further weed out non-duplicate pairings. The similarity index used by our MinHash algorithm is the Jaccard Index which is purely reliant on the intersection of common words between questions; it does not incorporate other subtle syntactic similarities. <em>This</em> is the problem the classification problem will ideally solve.</p><h3>Further Reading</h3><p>[1] <a href="https://github.com/resteorts/record-linkage-tutorial/blob/master/03-lsh/03-lsh.pdf">https://github.com/resteorts/record-linkage-tutorial/blob/master/03-lsh/03-lsh.pdf</a><br>[2] <a href="https://arxiv.org/pdf/1710.02690.pdf">https://arxiv.org/pdf/1710.02690.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ae1f3d8bc5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Market Simulator Using Markov Chains and Python]]></title>
            <link>https://medium.com/data-science/how-to-build-a-market-simulator-using-markov-chains-and-python-7923256f8d29?source=rss-3646d306eb30------2</link>
            <guid isPermaLink="false">https://medium.com/p/7923256f8d29</guid>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Bassim Eledath]]></dc:creator>
            <pubDate>Wed, 05 Dec 2018 23:07:40 GMT</pubDate>
            <atom:updated>2018-12-05T23:12:43.661Z</atom:updated>
            <content:encoded><![CDATA[<h4>Model customer behavior, visualize A/B test results, predict user metrics…all using a simple Markovian framework!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC63NKUzUwxipVfDMG-Jow.png" /><figcaption>final product</figcaption></figure><p>In this article, I aim to introduce you (regardless of your technical ability) to Markov chains and use it to simulate customer behavior.</p><p>This isn’t going to be a traditional “how to” tutorial with code snippets every two lines. My primary aim in writing this is to provide you with a conceptual framework that you can flexibly use, so you do not necessarily have to code along to learn something new. Technical details will pop up here and there, but I will provide as much intuition for them as possible.</p><h3>Data Processing</h3><p>For this analysis I will be using Credit Sesame’s analytics data that I was provided with during a datathon. You can use any user data provided it spans your time-frame of interest (for example a week’s/month’s/year’s worth of data). It should follow a structure similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Rel153l3rtVlwaqhcl8dXg.png" /><figcaption>example data</figcaption></figure><p>Examples of action can be “clicked offer/ad”, “clicked subscribe” etc. Columns can also be other metrics such as page views or revenue. Include any column you think will be useful for what you plan on modeling — in my case, it is user engagement.</p><h3>Customer Segmentation</h3><p>Select a particular day in your dataset and get <strong>new-user</strong> data for <strong>that particular day</strong>. I am modeling how new users behave within 30 days of using Credit Sesame’s website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*tVajLvErawR_9tovhlBcYw.png" /><figcaption>new user data on a particular day</figcaption></figure><p>Next, we segment our customers into different categories or states. There are many ways you can do this.</p><ol><li>You can apply a <strong>scoring function</strong>: Give each user a score indicating their overall engagement. You could have higher weights for actions you think influence higher user engagement such as “session length”.<br>You can then divide the distribution into 3 segments (Inactive, Active and Very Active) based on your heuristics.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Lj2VtfXVVPbIs21m-gXm2Q.png" /><figcaption>Distribution of applied score function</figcaption></figure><p>2. Apply an unsupervised algorithm such as k-means: You may use clustering algorithms such as k-means to cluster similarly engaged customers. Each cluster would have their own distinct properties which are hopefully the ones you wish to model. You could even apply the algorithm on your previously calculated score function (univariate data) to make it even simpler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*FHVSNBqBal14VtqGUHyUjw.png" /><figcaption>K-means segments visualized on the score function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ZEJtY89x4KZFZs5T9BqCrg.png" /><figcaption>after segmentation on first-day data. 1 = inactive user, 2 = active user, 3 = very active user.</figcaption></figure><p>After segmenting first day data, you pick a time-frame. I chose to go with a month as I believe Credit Sesame has a lot of returning users and the magnitude of that can be captured with a month’s worth of data. After 30 days, users would have had the opportunity to shift to and from each segment: very active users may become inactive, moderately active users may become very active, and so on.</p><p>Apply segmentation to this post-30-day data. Make sure you account for the time frame (for example, average your engagement score for the 30 days).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*sHNQTdxQZLhzE9aCDitxKQ.png" /><figcaption>segmentation applied to 30-day data</figcaption></figure><p>Let’s visualize the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*h8Vgonx1Qi0K0YnbLlyirQ.png" /></figure><p>As expected, the number of users who became inactive rose over the 30 days and the number of users who stayed active and very active decreased.</p><p>Onto applying the Markov framework</p><h3>Markov Chains Groundwork</h3><p>Markov chains are simply mathematical systems that model state-to-state movement using certain probabilistic rules and fixed assumptions.</p><p>To put it more simply, when you have a system with fixed states (or segments), and agents/users who can move between those states with a certain fixed probability, you can model it using a Markov chain.</p><p>But let us first see if our system satisfies the assumptions of a Markov model:</p><ul><li><strong>ASSUMPTION 1:</strong> There are a finite set of states. In our system there only 3 segments customers can move in and out of.</li><li><strong>ASSUMPTION 2:</strong> The probabilities of moving between states are fixed. I admit, this is a strong assumption. While my system does take into account hundreds of thousands of user data points, it is easy to believe the variance of probabilities for different 30 day time frames shouldn’t be too large. But even with a lot of data, as we will see later on in the article, we have to be cautious.</li><li><strong>ASSUMPTION 3:</strong> State accessibility. Users in any segment can move to a different segment without any external restriction.</li><li><strong>ASSUMPTION 4: </strong>Non-cyclic. The segment-to-segment movement is in no way ‘automatic’ in our system, so this assumption is satisfied.</li></ul><p>Our system performs well against most assumptions of the Markov chain. This gives us some confidence in our model estimates, which we will get to once we build the model.</p><h3>Constructing the Markov Chain</h3><p>There are three parts to a Markov chain that are best represented as matrix-vector multiplication. If you are completely new to linear algebra, I would recommend going through this <a href="https://mathinsight.org/matrix_vector_multiplication">link</a> before proceeding with the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*vESU5MQQb5HhgYCc7V_VVQ.png" /><figcaption>N represents the number of segments</figcaption></figure><p>The initial state in our system is a 3x1 vector that represents the number of users in each segment. The end state is also a 3x1 vector that shows the number of users in each segment after the first month (after we multiply the initial state vector with the probabilities matrix). The transition probability matrix is a 3x3 matrix that represents the fixed probabilities of moving to and from different customer segments.</p><p>So how do we calculate these fixed probabilities?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*PXZBg9KAbMB35Icoz-A67w.png" /></figure><p>From our recorded segment movements. We look at how users from each segment on day 1 moved to various segments after 30 days and calculate the probabilities accordingly (equivalent to proportions).</p><p>0.89 (in the picture) refers to the probability that someone in segment 1 on day 1 stays in the same segment after 30 days i.e. it is the probability that an inactive user will stay inactive after 30 days. Note, the probabilities in each column must add up to 1. We repeat this process for all segments and build the final transition matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*LFraJizE-fVoD99_g98VDw.png" /><figcaption>Deconstructing the transition matrix for a clearer understanding</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Kuz8-e-PXYRfW4LoTFmo4g.png" /><figcaption>different way to visualize the transition matrix</figcaption></figure><p>Finally, we put it all together into this nice beautiful form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*uyMyT2mEpwatV0DhxDk0pw.png" /></figure><p>Now that we’ve modeled it, we can get to the fun stuff.</p><h3>Plotting results</h3><p>Let’s start by plotting the trend in our customer movement given our Markov chain.</p><pre>a_val,b_val,c_val = [],[],[]</pre><pre># initial state<br>init_state = np.array([188969, 81356, 14210])</pre><pre># transition matrix<br>a = np.array([[ 0.89, 0.75 ,0.49], [ 0.10, 0.22 ,0.44], [ 0.01, 0.03 ,0.07]])</pre><pre>for x in range(10):<br>    a_val.append(init_state[0])<br>    b_val.append(init_state[1])<br>    c_val.append(init_state[2])<br>    b = init_state<br>    init_state = a.dot(b)</pre><pre># plotting<br>plt.figure(figsize=(11,8))<br>plt.plot( [x for x in range(10)], a_val, marker=&#39;o&#39;, markerfacecolor=&#39;blue&#39;, markersize=12, color=&#39;skyblue&#39;, linewidth=4,label=&#39;Inactive users&#39;)<br>plt.plot( [x for x in range(10)], b_val, marker=&#39;o&#39;, markerfacecolor=&#39;red&#39;, markersize=12, color=&#39;pink&#39;, linewidth=4,label=&#39;Active users&#39;)<br>plt.plot( [x for x in range(10)], c_val, marker=&#39;o&#39;, markerfacecolor=&#39;orange&#39;, markersize=12, color=&#39;yellow&#39;, linewidth=4,label=&#39;Very active users&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.xlabel(&#39;Months&#39;)<br>plt.ylabel(&#39;Number of customers&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*d1jj1u6Sc810c-Agd9NQ5A.png" /><figcaption>output</figcaption></figure><p>What can we infer from this?</p><p>We see that after a period of around 2 months, all three segments hit an equilibrium i.e. while there are users moving from segment to segment, the overall number of customers in each segment stays constant.</p><p><strong>But there’s a catch</strong>. There is a very strong assumption we’re making here — we believe the probabilities are going to be fixed no matter how far into the future we predict user behavior. This is highly implausible. Let me give you an example: say you own a website that sells winter clothing. Active users who buy several coats over December are highly unlikely to follow the same shopping pattern in, say, July. Patterns can be seasonal and our Markov model does not capture that!</p><p>So what do we do?</p><p>We can either calculate different transition matrices for every month to capture these trends or we can restrict our domain of analysis to one month. Since the data I have only spans one month, I go for the latter option. If you do have data that spans further, I would encourage you to compare real data results to the Markov model output to see if the transition probabilities do stay fixed over the months, and adjust accordingly.</p><p>The results I get are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzStcXJeM0TfEwuToiOqYA.png" /><figcaption>Single month analysis of customer flow</figcaption></figure><h3>Applications:</h3><h4>A/B Testing</h4><p>Now that you have a model that describes customer behavior, how can we introduce “changes” or “interventions”, and model their impact? Well our Markov model recognizes two types of these changes:</p><h4><strong>1. Changes to initial state</strong>:</h4><p>Let’s say you own a pizza service and your website offers a buy-2-get-1-free deal on December 1st. You suspect this change will introduce many more active users who visit your website. Your assumptions are confirmed when you get a thousand unique new visitors, 300 of whom actually buy pizza (very active users) on that very day. You are pleasantly surprised and think “hmmm I’m used to getting a 100 orders a day: how will this fare in a month’s time.” You simply have to adjust the initial state in the Markov chain to account for this change.</p><pre># CHANGES TO INITIAL STATE - NUMBERS RECEIVED FROM MATRIX VECTOR PRODUCT</pre><pre>before = (855,130,15) # Without any change<br>after = (509,389,102) # After placing deal</pre><pre># create plot<br>plt.figure(figsize=(11,8))<br>index = np.arange(3)<br>bar_width = 0.35<br>opacity = 0.8<br> <br>rects1 = plt.bar(index, before, bar_width,<br>                 alpha=opacity,<br>                 color=&#39;b&#39;,<br>                 label=&#39;Without deal&#39;)<br> <br>rects2 = plt.bar(index + bar_width, after, bar_width,<br>                 alpha=opacity,<br>                 color=&#39;g&#39;,<br>                 label=&#39;With deal&#39;)<br> <br>plt.xlabel(&#39;Segments&#39;)<br>plt.ylabel(&#39;Number of Users&#39;)<br>plt.title(&#39;Customer behavior after a month&#39;)<br>plt.xticks(index + bar_width- 0.18, (&#39;Inactive&#39;,&#39;Active&#39;,&#39;Very Active&#39;))<br>plt.legend()<br> <br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*2oHMVdo9fVbYdvbHWkFOFg.png" /></figure><p>From changing the initial state from (inactive=500, active=400, very active=100) to (100, 600, 300), we get the results above. With more active and very active users early in the month, you increase your chance of having more repeat customers for the span of the month.</p><h4>2. Changes to transitional probabilities:</h4><p>You realize that these deals are good but they only impact initial states and the benefits of these deals do not last for several months i.e. they are short term solutions to expanding engaged users. In order to have more long lasting changes we’d have to introduce actions that change the probabilities. Let’s say you completely redesign your pizza delivery website to make checking out 10x faster. This is a type of action that will affect the number of users in each segment <strong>consistently. </strong>In order to account this type of change we change the probabilities in the transition matrix. <br>You can calculate the changed probabilities either by A/B testing the new website on a subsample of users, or, you can change them manually using your own heuristics and assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*6wFKzxEAmxsPdXwSL-KdzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*N1PeuslC_Ls2QPP8U8Q-WQ.png" /></figure><p>Assuming probabilities stay fixed, we can see how the customer flow changes with the new transition matrix.</p><h4>Predicting other metrics</h4><p>You can predict several other user metrics such as Customer Lifetime Value, revenue per user etc. using the techniques we described above. For example, to predict revenue changes, calculate the average revenue for each segment, calculate the output state, and multiply the revenue with the number of users in their respective segment.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*9KOp9TqhOCPMiiGWfnobLQ.png" /></figure><p>If you’ve gotten this far, I commend you. At a minimum, I hope I have been able to convey the beauty of Markov chains and their ability to provide key insights despite their simplicity (assuming the key assumptions are satisfied). I hope you find your own creative ways to apply this model!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7923256f8d29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-build-a-market-simulator-using-markov-chains-and-python-7923256f8d29">How to Build a Market Simulator Using Markov Chains and Python</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[Decoding BuzzFeed headlines using data science]]></title>
            <link>https://medium.com/data-science/decoding-buzzfeed-headlines-using-data-science-25198eb25082?source=rss-3646d306eb30------2</link>
            <guid isPermaLink="false">https://medium.com/p/25198eb25082</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[buzzfeed]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Bassim Eledath]]></dc:creator>
            <pubDate>Fri, 23 Nov 2018 20:44:16 GMT</pubDate>
            <atom:updated>2018-11-24T17:58:25.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding BuzzFeed Headlines Using Data Science</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*cETu8Ye4pqDYZczZ4gaBsg.png" /></figure><p>Love it or hate it (personally, fascinated by it), Buzzfeed has its characteristic way of capturing our fleeting attention, and a big part of their mojo lies in how they create their titles. I take an insight-driven approach to analyze BuzzFeed’s most common headlines using a variety of Machine Learning and NLP practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Zg_NRGDD2IohGEh9nqY9wA.png" /><figcaption>An overview of my analysis</figcaption></figure><h3>1. Data collection and cleaning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*25RDPSr9O8SbbCFiF8cnlg.png" /></figure><p>Using newsapi.org’s <a href="https://newsapi.org/s/buzzfeed-api">BuzzFeed API</a>, I was able to query up to 50 top headlines from the website at a time. I scraped 50 headlines twice a day for a week, which gave me approximately 700 headlines to work with.<br>Once that was done, I cleaned the text data by removing non-English sentences and unhelpful Unicode characters.</p><h3>2. What does the data tell us</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*udqkbKZ3zzudpx83FRHe1g.png" /><figcaption>preliminary plotting of some descriptive stats</figcaption></figure><p>The common consensus on the internet is that the ideal length of a headline is somewhere in <a href="https://coschedule.com/blog/best-headline-length/">between 50–70 characters</a>. The average BuzzFeed title length falls somewhere along this ballpark. As this is a quest to find BuzzFeed’s most recurring title structure, I narrow my search to titles with 11 words and proceed to do Part-of-speech tagging to uncover the most popular sequence of words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*AfIcFE-BAyjHSRjqBecmZQ.png" /><figcaption>the most popular sequence followed a CD, NNS, WDT, VBP pattern</figcaption></figure><p>We can see BuzzFeed loves starting its headlines with numbers. A headline starting with a number almost always leads to a list-based article such as “30 Things Under $10 That’ll Never Stop Being Useful”. Now I’m not an expert on the psychology of lists and why they appeal to us, but for anyone interested, there are several sources out there <a href="https://www.newyorker.com/tech/annals-of-technology/a-list-of-reasons-why-our-brains-love-lists">addressing this topic</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*eZFjzN7hSwGMde5e7mIAIg.png" /></figure><p>Onto, the next part of speech: the nouns. By quite the margin, these headlines follow their numbers with nouns (singular or plural).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*iPnDTbtzT6NwHyEMFFtXWw.png" /><figcaption>popular nouns used</figcaption></figure><p>Nothing too surprising here. These are nouns that all of us can relate to on some sensory level. Clearly for mass appeal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*LSRCBMhaLGGenrEoETiEkw.png" /></figure><p>What really captured my attention was the fourth word used in the sequence — “will”. <br>An example: “14 Things You’ll Understand If You Have A Gym Membership”.<br>Off the bat, we can see how the word “will” creates an anticipatory effect. There is an invisible but apparent cost for not clicking on the headline — the cost of not finding out.</p><p>Now that we have the structure in place, we can look at other characteristics of the headlines, such as sentiment: are these common headlines generally positive, negative or neither?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*S8yU5bUi78mvdbwWLx5z3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*acNsjV3VjAopS0hd-a0DIg.png" /></figure><p>The bimodal distribution does indicate there are a few positively skewed headlines, but overall, they are neutral. There are limitations to this assessment, however. One, BuzzFeed titles tend to use emojis and relevant punctuation marks (like ‘!!!’) which I naively cleaned out in the data collection process. I also did use a <a href="http://www.nltk.org/howto/sentiment.html">basic sentiment analysis model</a>, which may have missed out on slang, unusual comparisons and other signals of sentiment. Despite these concerns, when I looked at the sentences the model classified as ‘neutral’ (shown below), it didn’t seem like there was a lot of misclassification. I myself couldn’t manually classify these sentences as being either positive or negative: they are not opinionated by nature, which ran contrary to what I was initially expecting. And this goes back to my point earlier on how BuzzFeed uses anticipation as a tool to pique the interest of readers. These neutral headlines (which are in the majority) lead to articles that aim to convey some information you “need” to have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*DQB-_dpgk0FzVpqvMHqcuA.png" /><figcaption>neutral headlines</figcaption></figure><h3>3. Creating a simple BuzzFeed title generator</h3><p>Before I continue with this section, let’s summarize what we’ve learned so far about BuzzFeed’s titles:</p><ul><li>Headlines are succinct, at around 7–14 words each.</li><li>The most frequently used headline structure is [CD,NNS,WDT,VBP…] i.e. a number followed by a noun (mostly plural) followed by a Wh-word and a verb (mostly “will”).</li><li>The headline reveals a lot of information about the content of the article. They aren’t necessarily “clickbait”: quite the contrary in my opinion. They tell you exactly what you’ll be getting — list based articles that reveal some piece of information you want/need to know.</li><li>They are mostly neutral in sentiment. I don’t believe “anticipation” falls under the blanket of “positive” or “negative”. The goal of these headlines is to trigger your curiosity as efficiently as possible. In most cases they don’t need to invoke any polar sentiment to achieve this.</li><li>Note: I can’t stress this enough. The above analysis only pertains to the specific structure of headline this article has specified. BuzzFeed utilizes several other headline structures that are interesting and worth studying.</li></ul><p>Alright, let’s create a simple algorithm that tries to replicate this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*O7XjdSG31fptBRPRQzTNXQ.png" /><figcaption>structure I employ</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*DjIuGv1H-AHLR2_kVCDHAQ.png" /><figcaption>Output</figcaption></figure><p>Output looks good to me. Some of these titles look nonsensical (although, hilarious) but they work for our purposes. <br>To take it a step further, I wanted to see if a classification model would be able to pick up on this structure. For this I needed a dataset with headlines from a different source.</p><h3>4. Testing</h3><p>I decided to query around 500 headlines from <a href="https://www.kaggle.com/therohk/million-headlines">ABC news</a>. I combined the dataset with the BuzzFeed dataset to create a train and target set with the vectorized versions of the headlines with ‘1’ in the target variable indicating that it is a BuzzFeed title. I then fit a simple Support Vector Classifier model to the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*gZk-69raQUF09Lc0_uUAVA.png" /></figure><p>The model achieved an accuracy of 83.84 on the test set with many false positives (low precision, high recall) i.e. there were 13 cases where the model thought an ABC title was a BuzzFeed title. Using a thousand generated titles from our title generator, the model predicted all the titles to be that of BuzzFeed. So there is something about the structure of our generated titles that are indeed BuzzFeed-esque. Note, the random nouns and verbs I used to generate titles were not taken from the BuzzFeed corpus (I took them from the WordNet dictionary).</p><h3>Conclusion and Extras</h3><p>My intention in writing this was not to best replicate BuzzFeed headlines, but rather to analyze its structure and gain insights as to why they work. So I picked their most popular headline format and tried to make inferences given the data I was provided. You can access all the code and data I used <a href="https://github.com/bassimeledath/Buzzfeed_headline_analysis">here</a>.</p><p>I used a <a href="https://github.com/minimaxir/textgenrnn">pre-trained Recurrent Neural Network (RNN)</a> to generate text based on the BuzzFeed headlines given as input. Below is a sample of the output I got (after 4 epochs):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*JBEdFYx9tL6njdlDrm9O-A.png" /></figure><p>Now they don’t look exactly like the titles we’ve dealt with, but in some uncanny way they do exhibit the properties we’ve discussed in detail. They start with a number followed by a plural noun and they use the future tense to further pique your attention. Fascinating stuff.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25198eb25082" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/decoding-buzzfeed-headlines-using-data-science-25198eb25082">Decoding BuzzFeed headlines using data science</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>