<?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 Miroslav Batchkarov on Medium]]></title>
        <description><![CDATA[Stories by Miroslav Batchkarov on Medium]]></description>
        <link>https://medium.com/@mbatchkarov?source=rss-d2856e1852fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ab-f5DQWKnukWN7NXWyxeA.png</url>
            <title>Stories by Miroslav Batchkarov on Medium</title>
            <link>https://medium.com/@mbatchkarov?source=rss-d2856e1852fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:48:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mbatchkarov/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[A Benchmark Comparison Of Content Extraction From HTML Pages]]></title>
            <link>https://medium.com/@mbatchkarov/a-benchmark-comparison-of-extraction-from-html-pages-98d7c1229f51?source=rss-d2856e1852fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/98d7c1229f51</guid>
            <category><![CDATA[data-extraction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Miroslav Batchkarov]]></dc:creator>
            <pubDate>Wed, 02 Aug 2017 18:04:01 GMT</pubDate>
            <atom:updated>2017-08-02T18:18:27.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Content extraction is the task of separating boilerplate such as comments, navigation bars, social media links, ads, etc, from the main body of text of an article formatted as HTML. The main content typically accounts for only a small portion of a page’s source code (highlighted in red in the image below). Extraction is usually the first step of any data analysis based on HTML data, as errors early on tend to propagate downstream and affect the rest of the study. High quality extraction is crucial to the success of data projects. However, extraction can be surprisingly tricky because HTML can be used in creative ways to achieve the same effect.</p><p>This post outlines how Skim Technologies’ content extractor works and compares our model to two established packages. Our model is more accurate than both competitors without making use of any external styling information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*OgmWHntBaL1l21rP." /><figcaption>Content on a page</figcaption></figure><h3>Background</h3><p>To date two main approaches to content extraction have been proposed. Rule-based methods typically take a DOM tree as input and use rules to decide which elements are boilerplate. Traditional ad blockers are the simplest instantiation of such a system. DOM elements that link to blacklisted domains are marked as boilerplate. Extending this idea, a larger set of simple rules can be used to assign scores to DOM elements based on how likely they are to be content. One once popular such algorithm is <a href="https://github.com/mozilla/readability/blob/master/Readability.js#L789">Readability</a>, which used rules like this:</p><ul><li>Add 1 point for each comma within this paragraph</li><li>For every 100 characters in this paragraph, add 1 point up to 3 points</li><li>Add 5 points if the element’s tag name is <em>div</em></li><li>Subtract 5 points if the element’s tag name is a <em>ol/ ul</em></li><li>Set score to zero if paragraph has length of less than 25 characters</li></ul><p>This system is effectively a linear classifier with ad-hoc feature weights. A human has to decide how many points to add or subtract for each rule. Unless explicitly programmed, it is tricky to include feature combinations such as “add 1 point if the element is a div and it contains more than 25 characters”. Further, keeping track of all interactions between rules becomes near impossible as the number of rules grows. From a practical perspective, it is hard for developers to extend a rule-based system as its complexity increases dramatically with the number of rules.</p><p>To mitigate the shortcomings of rule-based methods, recent work has made use of Machine Learning (ML). The main advantage over rules is that a decision function can be learned automatically by example. Rather than hand-crafting rules, developers provide a learning algorithm with input pages where each part of the page are marked as either content or boilerplate. Long term, such a system is easier to maintain and extend.</p><p>Two main approaches have emerged in ML-based content extraction. The first one is image-based, where a page is rendered and computer vision techniques are used to analyse the visual layout of the page. One such prominent system is <a href="https://www.diffbot.com/">Diffbot</a>. However, Diffbot is proprietary, so few details about how it works are publicly available.</p><p>The second family of ML content extractors operates on DOM trees, similar to rule-based models. However, supervised machine learning is used to learn how many points should be assigned to each element. This allows features to be combined in more complex ways than a human can ever write by hand. A prominent early system based on this approach is <a href="http://github.com/seomoz/dragnet">Dragnet</a>. Skim Technologies’ extractor is also based on the DOM tree. The advantage over visual methods is that the system is less reliant on external CSS/ JS files. This means faster loading times, as there is no need to fetch third-party resources over the network (other than the page’s HTML code). More importantly, external content delivery networks (CDNs) tend to go offline. The odds of a page being rendered the same way therefore decrease considerably over time.</p><h3>Our approach</h3><p>Four main steps are involved in training our content extractor. First, we acquire a sample of web pages to use as input to the ML model. Next, we break down HTML pages into “blocks”, which are the smallest unit our model operates on. For each block in the data set, we ask a human to provide a boilerplate/content tag. Finally, we use domain knowledge to extract informative features for each block, which are fed into a ML algorithm along with human tags. More details about each step are given below.</p><h3>DOM simplification</h3><p>DOM simplification is vital because the average DOM tree is very strung-out: ultimately it can have nodes containing just a single character. We need a way of mapping DOM elements, which are designed to make sense to a browser, to units that are useful to humans (sentences, paragraphs, etc). For example, consider the following naive way of implementing a drop cap with CSS:</p><pre>&lt;div&gt;<br>    &lt;span style=”font-size: 200%;”&gt;H&lt;/span&gt;</pre><pre>    &lt;span&gt;ello&lt;span&gt;</pre><pre>&lt;/div&gt;</pre><p>In this case, the DOM tree has three elements-a parent div and two child spans, but only a single logical block- the word “hello”. We therefore simplify the tree by, among other things, merging or removing insignificant children. The resultant data structure is a “block tree”. Like a DOM tree, it is hierarchical, but it is wider and shallower and has fewer leaves. The leaves are semantically more meaningful and usually map to paragraphs. The leaves are what we process downstream.</p><h3>Labelled data</h3><p>We gather training data by labelling each block in a given page as either content or not content. Four annotators labelled a total of ~400k blocks in ~2100 pages. Two thirds of those pages are the original <a href="http://github.com/seomoz/dragnet_data">Dragnet data</a>, re-labelled to correct some occasional errors. The remaining pages are a random sample of real-world pages that were processed by our system in December 2016. We built a simple web-based tool to help us gather tags for each block. We bootstrap the data set by first labelling a small data set and training a prototype model, which we then use to pre-tag blocks to save annotator time.</p><h3>Model training</h3><p>To achieve a good trade-off between speed and accuracy in production, we extract a relatively small set of shallow features and classify blocks independently of one another. Our feature extraction pipeline generates over 40 features per block. These are inspired by Dragnet and include:</p><ul><li>Shallow textual features, such as number of words, text/link/keyword density, average word/sentence length, readability score</li><li>Structural features, such as distance to the title</li><li>Our patent-pending styling and group features</li></ul><p>We take context into account by also including additional features from adjacent blocks. All features we currently extract are language-independent, so our extractor works equally well with pages written in any human language.</p><p>Our final step is binary classification (content vs boilerplate) with gradient-boosted decision trees.</p><h3>Evaluation</h3><p>To assess our model’s performance, we compare it to Dragnet and Diffbot. We made every effort to ensure a fair comparison. We first split our data set 80–20. Both our model and dragnet are trained on the 80%, and all three models evaluated on the remaining 20%. The final test set includes 427 pages, 275 of which are from dragnet and 153 are from our data. Details about Diffbot’s training data are not publicly available.</p><p>We use Dragnet’s <a href="https://github.com/seomoz/dragnet/blob/master/dragnet/model_training.py#L238">evaluation process</a>, where content extraction is evaluated similarly to an information extraction system. Given an HTML page as input, the task is to output the main body of the article as plain text. This evaluation considers how good a model is at retrieving the main body and is independent of how pages are broken down into blocks. Note this post focuses exclusively on boilerplate removal and disregards other features of both Diffbot and our extractor, such as title or author extraction. These will be considered in a separate post.</p><p>Token-level precision, recall and F1 for all three models are:</p><blockquote>Dragnet: .847/ .921/<strong>.876</strong></blockquote><blockquote>Diffbot: .917/ .943/ <strong>.921</strong></blockquote><blockquote>Skim Tech: .956/ .925/<strong>.</strong>926</blockquote><p>Skim Technologies’ content extractor emerges as the winner, massively outperforming Dragnet and beating Diffbot by half a percentage point. These results suggest that careful data preprocessing and feature engineering result in considerable improvements in extraction accuracy, even without access to external styling information. These in turn improve the performance of downstream models such as <a href="https://medium.com/skim-technologies/a-benchmark-comparison-of-extractive-summarisation-systems-d77d46ca2489">text summarisers</a>.</p><p>Qualitatively, both Skim Tech and Diffbot appear to perform well on pages with a traditional layout, where the main body is in the page center and boilerplate is at the edges. Such pages are typically extracted very well, with only occasional false positives or false negatives. Skim Tech performs better in dynamically modified pages, for example ones where a paywall is generated with JS <a href="http://www.msn.com/g00/en-us/tv/news/trump-putin-shake-hands-at-g20/vp-BBDWzY9">[1]</a> <a href="http://www.marica.bg/%D1%81-%D0%BF%D0%B8%D1%80%D0%B0%D1%82%D1%81%D0%BA%D0%B8-%D0%BA%D0%BE%D1%80%D0%B0%D0%B1-%D0%BE%D0%BA%D0%BE%D0%BB%D0%BE-%D0%B7%D0%B0%D0%BA%D0%B8%D0%BD%D1%82%D0%BE%D1%81-news763277.html">[2]</a> <a href="https://gizmodo.com/personal-info-of-650-000-voters-discovered-on-poll-mach-1797438462">[3]</a>. This is likely because we do not currently execute JS code in pages.</p><p>Dragnet performs better than <a href="https://moz.com/devblog/benchmarking-python-content-extraction-algorithms-dragnet-readability-goose-and-eatiht/">reported by its authors</a>, possibly because the original paper used a logistic regression classifier, whereas the latest release uses a more powerful model (extremely randomised trees).</p><p>Our Diffbot comparison is not under identical conditions because the test data does not include JS/CSS files. Pages may render differently to how they used to when the data was first gathered. Manual inspection of 20 Dragnet pages (from 2012) and 20 of our pages (from 2016) shows that half render as they would have originally. Diffbot’s model uses computer vision, so it is possible that differences in page rendering may lower its accuracy. However, we view over-reliance on styling and visual information as a limitation. It should be possible to extract content from pages in the absence of external CSS, because such information goes missing over time.</p><p>In terms of speed, Dragnet is the fastest, processing tens of documents a second (when documents are on disk). Our extractor averages about one document per second. However, that includes a number of other models beside content. Also, our code is currently optimised for accuracy first, developer productivity second and speed last. Most of our feature extraction pipeline is written in pure Python and therefore much slower than it could be (compared to Dragnet, which is almost exclusively in C/C++/Cython).</p><p>We cannot present definitive speed figures for Diffbot because we can only access their code through an HTTP API. Factors such as network latency, API outages, request caching and rate limiting significantly affected our perceived throughput. Our subjective experience is that when we were not being rate-limited, Diffbot’s speed was in the same ballpark as our system’s.</p><h3>Roadmap</h3><p>While we are happy with our model’s current accuracy, we are also excited about what the future could look like as we turn our attention to improving its speed. We plan to reimplement critical parts of our extractor in Cython to make it blazing fast. Along the way, we will also be adding new features and more training data to increase accuracy.</p><p>We intend to extend this comparison to more extractors, such as Embedly, Boilerpipe or Goose, and more web pages. We would also like to do a speed comparison under identical conditions. Lastly, both Skim Techonologies and Diffbot’s APIs offer more ways of structuring a page that go beyond content extraction. We recently <a href="https://medium.com/skim-technologies/a-benchmark-comparison-of-extractive-summarisation-systems-d77d46ca2489">evaluated</a> a number of text summarisation APIs. We would also like to compare other models such as author, date and title extraction.</p><p>If you have any questions about this evaluation, or would like to test out our API’s then contact us via <a href="/service/mailto:api@skimtechnologies.com">api@skimtechnologies.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98d7c1229f51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gold standard data: lessons from the trenches]]></title>
            <link>https://medium.com/@mbatchkarov/gold-standard-data-lessons-from-the-trenches-2b26b2cc8d27?source=rss-d2856e1852fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b26b2cc8d27</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Miroslav Batchkarov]]></dc:creator>
            <pubDate>Mon, 19 Jun 2017 00:00:00 GMT</pubDate>
            <atom:updated>2018-04-06T10:45:22.138Z</atom:updated>
            <content:encoded><![CDATA[<p>I am moving my blog over to Medium, so I am re-posting all content here. Thir article was originally written in June 2017 as a summary of a talk I gave at PyData Berlin. It is intended for a non-technical audience.</p><h3>Introduction</h3><p>It is often said that rather than spending a month figuring out how to apply unsupervised learning to a problem domain, a data scientist should spend a week labeling data. However, the difficulty of annotating data is often underestimated. Gathering a sufficiently large collection of good-quality labeled data requires careful problem definition, quality control and multiple iterations. As a result, gathering enough data to build a high-accuracy supervised model can take much longer than one might expect. This post describes my experiences in labeling gold-standard data for natural language processing and the lessons learned along the way.</p><h3>Case study 1: word embeddings</h3><p>Words vectors have become popular in recent years as they can be built without supervision and can capture complex semantic relations well. For example, adding the vectors of king and woman and subtracting the vector of man yields a vector that is very close to that of queen.</p><p>Algorithms for training word vectors have been evaluated by correlating the “similarity” of word pairs, as predicted by a model, to those provided by a human judge. A typical data set consists of word pairs and a similarity score, e.g. cat, dog, 80% and cat, purple, 21%. A model is considered good if it assigns high scores to word pairs that are scored highly by a human. Let us consider what it takes to label such a data set and what can go wrong in the process.</p><h3>Is the task clearly defined?</h3><p>What exactly is word similarity? We all have an intuitive understanding, but a lot of corner cases are hard to pin down. What makes the words cat and dog similar? Is it because they are both animals? What about topically related words, such as rice and cooking? What about antonyms, e.g. big and small? Human annotators need clear and unambiguous description of what is required of them, otherwise data quality will be poor. For instance, the similarity scores provided by 13 annotators for the pair tiger–cat range from 50% to 90% in WordSim353, a data set often used to rank word similarity. Click <a href="http://sro.sussex.ac.uk/62044/1/acl2016.pdf">here</a> for a more detailed analysis of this issue.</p><h3>Is the task easy for humans to do?</h3><p>Even with clear instructions, some tasks are inherently subjective. It is unlikely that every person you ask will provide the same similarity score for cat and dog, or will interpret a written sarcastic comment the same way out of context. If humans cannot agree what the right answer is for a given input, how can a model ever do well? Of course, data scientists can take steps to address those issues. First, make sure that you have clear written annotator guidelines, even if you plan to do the annotation yourself. Ask others to read the guidelines and explain how they interpret your instructions.</p><p>Second, do not be afraid to change the task to make it easier. If your use case allows it, make the task as simple as possible for the annotators. Ask yourself if it is business-critical to get fine-grained labels or if a coarser-grained (and therefore easier) annotation schema would suffice.</p><h3>Do you have quality control in place?</h3><p>Not having a mechanism for identifying annotator errors or consistently under-performing annotators is perhaps the most common error in data labeling. There are many viable ways to do quality control — the key is to ensure at least one of them is in use. A common approach is to measure if different annotators agree with one another or with a known gold-standard — see next case study. Conflicts may be resolved by an independent adjudicator.</p><p>Ideally, quality control should be an automated process that runs continuously. Remember that systematic errors may be a sign of unclear guidelines. Talk to your annotators to understand the source of the problem. Be prepared to discard your first data set.</p><h3>How much data can you hope to get?</h3><p>A supervised learning model may require a significant amount of labeled data to perform well. However, obtaining this much data may be problematic for a number of reasons:</p><ul><li>Human annotators are expensive, even on crowd sourcing platforms that systematically underpay.</li><li>Good, trustworthy annotators are hard to find, especially if they need special training.</li><li>An aside on ethics: pay fairly and treat annotators with respect at all times. The less you pay, the higher the odds you will have to repeat the job.</li><li>Errors in labeling may be hard to correct, so be prepared to discard data.</li></ul><p>Keep an eye on the learning curve of your model. Do not rush into gathering more data unless there is evidence to suggest it would help. It is often better to focus on quality rather than quantity.</p><h3>Case study 2: symptom recognition in medical data</h3><p>The second case study involves identifying mentions of symptoms or diseases in notes taken by a doctor during routine exams. An ideal note may read: Abdominal pain due to acute bacterial tonsilitis. No allergies. However, these notes are often taken in a hurry and typically look more like this:</p><p>Abd pian//acute b tons//n/a alergies.</p><p>This presents a different set of challenges for a data scientist.</p><h3>Do you need an expert annotator?</h3><p>Most doctors’ notes are impossible to decode for a layperson. Annotation therefore has to be done by a trained doctor, but most doctors prefer to practice medicine rather than label data. The typical doctor is also not an expert in machine learning or linguistics (and vice versa), so they may not have the same vocabulary. This makes it harder to provide a clear task definition.</p><h3>Can you measure inter-annotator agreement?</h3><p>Can you quantify the degree to which annotators agree? In the case of word similarity, this is as simple as comparing numerical scores. This gets trickier when the annotation unit has complex structure (e.g. it is a phrase). For example, in the sentence burning neck pain one annotator may pick up the first two words as a symptom, while another may pick up the last two words, and a third may not mark any symptoms.</p><h3>Tooling</h3><p>Do you need specialist software to capture and store data? Depending on the complexity, can you write something yourself or do you have to assemble a team? Will the tool be intuitive and easy to use, or is it confusing your annotators? In our medical example, the tooling is getting much better and allows annotators to be very productive. Several years ago tools such as <a href="http://brat.nlplab.org/">BRAT</a> were less mature and took a long time to set up, whereas now they run out of the box.</p><p>Further issues arise where hardware is involved, e.g. in internet-of-things or industrial applications. These include writing bespoke software for the device to capture data, transmitting it to a server reliably (and securely!) and storing potentially massive amount of data that machines generate.</p><h3>People issues</h3><p>Many data science talks focus on the technical aspects of data gathering, with people issues often taking a back seat. However, a single well-trained and reliable annotator producing large amounts of labeled data can often contribute more to the success of a project than a team of programmers. It is therefore important to build and maintain a good working relationship with the annotators. This is much easier if they are located near you. Be prepared to deal with small issues such as annotators not showing up for sessions, or taking two-week breaks between sessions. The more time passes between sessions, the more the annotators will need re-training. This is the main reason why quality control should be run continuously.</p><p>If you are using a crowd sourcing platform, beware of click farms. The academic literature has some fantastic resources on the subject- see references.</p><h3>General lessons</h3><ul><li>Get to know the problem domain</li><li>Do not be afraid to start from scratch if your assumptions are wrong</li><li>Monitor quality continuously</li><li>Beware of crowd-sourcing</li></ul><h3>References and notes</h3><p>The first case study is based on <a href="http://sro.sussex.ac.uk/62044/1/acl2016.pdf">this paper</a>, which is in turn based on my PhD work. The second case study is inspired by the PhD work of my lab mate <a href="https://www.linkedin.com/in/savkov/">Aleksandar Savkov</a>.</p><ul><li>Herbert Rubenstein and John Goodenough. 1965. Contextual correlates of synonymy. Communications of the ACM 8(10):627–633.</li><li>Felix Hill, Roi Reichart, and Anna Korhonen. 2015. Simlex-999: Evaluating semantic models with (genuine) similarity estimation. Computational Linguistics</li><li>Lev Finkelstein, Evgeniy Gabrilovich, Yossi Matias, Ehud Rivlin, Zach Solan, Gadi Wolfman, and Eytan Ruppin. 2001. Placing search in context: The concept revisited. Proceedings of the 10th international conference on World Wide Web pages 406–414.</li><li>George Miller and Walter Charles. 1991. Contextual correlates of semantic similarity. Language and Cognitive Processes 6(1):1–28.</li><li><a href="http://esslli2016.unibz.it/?page_id=346">Chris Bieman. Crowdsourcing Linguistic Datasets</a></li><li><a href="http://crowdsourcing-class.org/">Chris Carlison-Burch et al. Crowdsourcing and Human Computation Class</a></li><li>Rion Snow, Brendan O’Connor, Daniel Jurafsky, and Andrew Y. Ng. 2008. Cheap and fast- but is it good?: evaluating non-expert annotations for natural language tasks.</li><li>Gadiraju, U., Kawase, R., Dietze, S., Demartini, G. 2015. Understanding Malicious Behaviour in Crowdsourcing Platforms: The Case of Online Surveys.</li><li>Ron Artstein and Massimo Poesio. 2008. Inter-Coder Agreement for Computational Linguistics. Proceedings of the Association for Computational Linguistics.</li></ul><p><em>Originally published at </em><a href="http://mbatchkarov.github.io/2017/06/19/gold-standard-data/"><em>mbatchkarov.github.io</em></a><em> on June 19, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b26b2cc8d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An exploration of scipy sparse matrices]]></title>
            <link>https://medium.com/@mbatchkarov/an-exploration-of-scipy-sparse-matrices-7f5f8d291e16?source=rss-d2856e1852fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f5f8d291e16</guid>
            <category><![CDATA[scipy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Miroslav Batchkarov]]></dc:creator>
            <pubDate>Fri, 10 Oct 2014 00:00:00 GMT</pubDate>
            <atom:updated>2018-04-06T10:50:50.249Z</atom:updated>
            <content:encoded><![CDATA[<p>I am moving my blog to Medium and posting all old articles here. The post below was originally written in October 2014 but it should still be relevant today.</p><p>—</p><p>My colleague <a href="https://github.com/mattilyra">Matti Lyra</a> recently faced an interesting computational problem. He wanted to see how quickly a stream of temporally-ordered documents evolves, and he chose to do it by looking at how often new words appear in the steam. This post is about how to do this efficiently in Python.</p><p>More formally, the problem is: given a <a href="http://en.wikipedia.org/wiki/Document-term_matrix">term-document matrix</a> (stored as a scipy.sparse.csc_matrix), find how many new terms each document introduces as efficiently as possible. Here is what we came up with.</p><p>First let’s generate some plausibly-looking (sparse) matrix to play with.</p><pre>import numpy as np <br>from scipy.sparse import csc_matrix </pre><pre>np.random.seed = 0 <br>mat = csc_matrix(np.random.rand(10, 12)&gt;0.7, dtype=int) mat[1, 0] = 2 # add some variety to the matrix <br>mat[0, 1] = 3 <br>print(mat.A) <br>[[0 3 1 1 1 0 0 0 1 0 1 0] <br>[2 0 1 1 0 0 0 0 0 1 1 1] <br>[1 0 0 0 0 1 1 1 0 0 0 0] <br>[0 1 0 0 1 0 0 0 0 1 1 0] <br>[1 1 0 0 1 0 1 0 0 0 0 1] <br>[0 0 1 0 0 0 1 0 0 0 0 0] <br>[0 0 1 0 0 0 1 0 1 1 0 1] <br>[0 1 0 1 0 1 0 0 0 0 1 0] <br>[0 0 0 1 0 0 1 0 1 0 1 1] <br>[0 0 0 0 0 0 1 0 1 1 0 1]]</pre><p>The (sparse) matrix is stored as three dense arrays, data, indices and indptr. data contains the non-zero values of the matrix, in the order in which they would be encountered if we walked along the columns top to bottom and left to right. If this were a csr matrix, the walk would have been along the rows.</p><pre>mat.data[:10] <br>array([2, 1, 1, 3, 1, 1, 1, 1, 1, 1])</pre><p>These numbers correspond to the non-zero values we would encounter if we walked along the columns of the matrix. Note column boundaries are not marked- this is what indptr is for. indptr[i] tell us where the i-th columns begins. For the matrix above, we have</p><pre>mat.indptr[:10] # start and end index of each column in the data array <br>array([ 0, 3, 7, 11, 15, 18, 20, 26, 27, 31], dtype=int32)</pre><p>So the first column starts at position 0 and runs until position 3 (exclusive), the second columns starts at position 3 and runs until position 7, etc. Here are the non-zero values stored in the first and second column.</p><pre>print(mat.data[mat.indptr[0]:mat.indptr[1]]) print(mat.data[mat.indptr[1]:mat.indptr[2]]) <br>[2 1 1]<br>[3 1 1 1]</pre><p>What is still missing is what row these values should go in. This is stored in mat.indices. We can index it similarty to how we index mat.indptr. To get the rows in the first column where the non-zero values go, we would do this:</p><pre>print(mat.indices[:10]) # position of the data in a given row <br>print(mat.indices[mat.indptr[0]:mat.indptr[1]]) <br>[1 2 4 0 3 4 7 0 1 5]<br>[1 2 4]</pre><p>i.e. the non-zero rows in the first column are at positions 1, 2 and 4.</p><p>Let’s get back to our original problem of finding how many new terms appear in each document. First, we want to find when (in what document) a term first appears, i.e. the position of the first non-zero row in each column. Fortunately, the scipy.sparse.csc format makes that very easy:</p><pre>first_nonzero_row = mat.indices[mat.indptr[:-1]] first_nonzero_row <br>array([1, 0, 0, 0, 0, 2, 2, 2, 0, 1, 0, 1], dtype=int32)</pre><p>Now that we know when words first appear, we want to find how many words appear for the first time in each document:</p><pre>new_cols_per_row = np.bincount(first_nonzero_row, minlength=mat.shape[0]) <br>print(new_cols_per_row) <br>[6 3 3 0 0 0 0 0 0 0]</pre><p>And there you have it- new_cols_per_row[i] corresponds to how many new terms appeared in the i-th document.</p><p>One trick we missed in our original implementation is the minlength parameter to bincount. Without it numpy will get rid of bins (i.e. rows) with zero new features, and the result will be smaller than what we would expect:</p><pre>np.bincount(first_nonzero_row) <br>array([6, 3, 3])</pre><p>In the real text streams Matti works with, we didn’t find this to be a problem, i.e. every document had at least one new term.</p><p><em>Originally published at </em><a href="http://mbatchkarov.github.io/2014/10/10/rate_of_vocab_growth/"><em>mbatchkarov.github.io</em></a><em> on October 10, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f5f8d291e16" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>