CS3245 Information Retrieval¶
Week 13: Web search¶
First generation search engine (Goto, 1996) based on revenue maximization.
Second generation search engine (Google, 2000) presentation of separate pane for ads.
Ads may affect editorial content: Search engine optimization (organic) and search engine marketing (paid). Advertisers bid for keywords (sale by auction) and charged only when someone clicks the link (CPC).
- Cannot rank solely by price, since relevance matters as well
- Key measure of relevance: Click-through rate (CTR)
- Trades in short-term revenue for overall acceptance of system and maximize overall revenue.
Interesting auctioning concepts:
- Essentially, the actual price is the amount needed to outbid the next lowest bidder, in order to maintain the current ad rank.
- In other words, the amount paid multiplied by own CTR must exceed the lower bidder’s bid multiplied by their CTR.
Problems?
- Keyword arbitrage: Keyword is bought on Google, and then redirects traffic to a third party page full of ads. This is essentially ad spamming. Adverserial information retrieval.
- Violation of trademarks: Misleading to users to trigger an add off a trademark if user cannot buy that product, e.g. Geico, Louis Vuitton.
Week 12: Web crawling and link analysis¶
Web crawling¶
Web crawling is a non-trivial problem. Involves,
- Indexing files (download into hard drive)
- Recursive descent in filesystem
- Being a good citizen on the web
Basic crawler operation. Assumes web is well-linked.
- Start with seed pages in queue, e.g.
https://en.wikipedia.org/ - Repeat:
- Pull URL from queue
- Fetch and parse page + push new URLs to queue
Some comments:
- Be polite:
Bandwidth limited for each server, so using
robots.txtprotocol. Cache this file for each site crawled. Gives sitemap(?), where you’re allowed to crawl, what behaviors are banned, etc. - URL Frontier: URL Frontier is the data structure that holds and manages URLs seen but not crawled. Need to decide when to crawl the same host based on the policy, come up with a crawling schedule.
- Duplicates:
Ignore duplicate content (e.g. use document fingerprints or shingles),
filter URLs based on exclusion policy in
robots.txt, remove duplicate URLs (after normalization) although need to consider which pages are going to be fresh. - Distributed: Distributed crawler to run multiple crawl threads at different geographical nodes, can consider mapping target hosts to nodes to reduce latency.
- Spider traps: A set of webpages that cause the crawler to enter infinite loop or crash, either intentionally or unintentionally. Can be made sophisticated by using dynamic pages.
Link analysis¶
Do these links help with the relevance query?
Two assumptions:
- A hyperlink is a quality signal: d1 author deems d2 is high-quality and relevant.
- Anchor text describes the content of d2, i.e. searching on text of d2 + anchor text to d2 will be better.
If only text is queried, can pull up a lot of potentially irrelevant content, e.g. copyright page, Wikipedia page, spam pages, no match with graphical pages. The anchor text would be a good indicator instead. Anchor text can be weighted more highly than document text.
Not all actors are good, however, e.g. Google bombs: Manipulate Google search by malicious anchor text, e.g. “dangerous cult”, “who is a failure?”, “evil empire”.
PageRank¶
Comes from citation analysis (of references in scientific literature). Citation frequency can be used to measure impact of an article. However, due to link spam, in-link frequencies may not be reflective of link quality. Can use weighted citation frequency (Pinsker, Narin, 1960s), where the vote by the article is weighted according to its citation impact.
The importance of a page is given by the sum of importance of pages linking to the page, weighted by the number of outlinks. More outlinks means roughly less importance.
Algorithm¶
Assume the position of a random web surfer.
- Start at random page
- Follow one of n links with 1/n probability
- Do this repeatedly, then use the long-term visit rate as the page’s score
- This is the global score for the page, based on the network topology
Essentially a first order Markov chain:
We can build the transition probability matrix using the number of outlinks. Problem is there might be dead ends or spider traps. We want to make the Markov chain ergodic, i.e. can be in any state at every step with non-zero probability, which according to a theorem, converges to a long term stable rate:
This is circumvented using teleporting technique:
- No outlinks: Teleport to a random webpage
- With outlinks: Small probability to teleport \(\alpha\), say, 10%
The 1/3 in C is the teleport probability to every possible node, since dead end. The 1/30 in A is the 10% chance teleportation, distributed across each node, i.e. 1/10/3. The rest are 90% * 1/2 + 10% * 1/3 = 29/60.
To evaluate the long term stability, we use the probability vector, e.g. an initial one hot vector representing a certain state, and repeatedly multiply with the transition matrix. The long term visit rate will converge regardless of which starting vector used.
This means at the long term visit state, we get a vector \(a\), such that \(a\mathbf{A} = a\). This means \(a\) is actually the eigenvector of the transition matrix \(\mathbf{A}\).
Essentially a global quality score for use in querying. Note that a simple PageRank may not be ideal if purely using the static quality score. Need other criteria, e.g. term proximity, tiered indices, anchor text, …
Week 11: Probabilistic information retrieval¶
11 Probabilistic information retrieval
12 Language models for information retrieval
Probabilistic approach to retrieval¶
Foundation: Reasoning under uncertainty.
- IR system has uncertain understanding of user information need and document collections
- IR system must make an underlying guess of whether a document satisfies the query (information need)
Recap of probability theory:
We rank by probability, using the binary random variable \(R\) to denote whether document is relevant to query. Probability ranking principle (PRP).
Limitation: Limited to the available data used to build the probabilistic model.
Binary Independence Model¶
Assumptions:
- Binary: Documents and queries represented as binary term incidence vectors, i.e. bag of words.
- Independence: No association between individual terms.
Need to estimate how terms in document contribute to relevance. To simplify, we assume relevance of individual documents are independent (although not true, e.g. duplicate results).
- Find measurable statistics that affect judgement of document relevance
- Use them to estimate probability \(P(R=1|d,q)\)
- Order documents by decreasing probability.
The formulation relies on Bayes’ rule. Can express derivation by first converting to pure AND form. A couple of notes:
- \(P(x|R=1,q)\): Given a relevance document retrieved with q, probability that the representation is x.
- \(P(R=1|q)\): Probability of retrieving a relevant document for q.
- \(P(x|q)\): Given a query q, probability that there exists x.
Above, we use the odds to simplify the calculation, i.e. ignore (2) and (3). We use the independence assumption to split into individual components:
Simplify the notation,
We further assume terms not in query are not relevant (i.e. equally likely to occur in either relevant or irrelevant documents),
We then remove the second term, by converting it into an expression that is independent of the relevance:
Essentially just need to calculate the odds ratio, i.e. odds of term appearing if relevant vs odds of term appearing if not relevant. Now assuming we fully know which documents are already relevant,
In practice, we simplify to IDF,
A quick thought on probabilistic models:
Okapi25:
Language model of retrieval¶
Representation of the type of language. This approach can also be used for information retrieval as well.
“prior” -> “prior probability”, i.e. static quality score.
Language model, e.g. unigram, bigram, trigram, etc.
Key is, we generate a language model for every document, and see the probability of generating that particular query.
Same thing again, we need to smooth the probabilities:
We can use another method of smoothening, which gives us the mixture model:
Give these exercises a try:
Language model is more effective when recall levels are high:
Comparison with VSM:
Week 10: Relevance feedback¶
User giving feedback on relevance:
- User issues short query
- System returns set of retrieval results
- User marks documents as relevant / nonrelevant
- System computes better representation and retrieves revised set of results
Relevance feedback is classically done using Rocchio Algorithm with a VSM:
We want to find the query vector q that maximizes the difference between
similarity with relevant document set, and similarity with nonrelevant
document set. Problem is we do not know the set of relevant documents in
the first place.
In IR query, the query is shifted by the set of relevant and nonrelevant documents, such that the new query vector falls nearer to the centroid of relevant documents. This typically increases recall a lot more, and reasonable values are \(\alpha = 1\), \(\beta = 0.75\), \(\gamma = 0.15\), with \(\gamma \lt \beta\) typically since positive feedback is more valuable. Another alternative sets gamma to zero, or use only the nonrelevant document with highest ranking which is shown to be most consistent (Ide dec-hi).
Query weights can be adjusted by considering Naive Bayes probabilistic model, by estimating probability of term appearing in document depending on the document’s relevance. Not sure how.
Effectiveness¶
Works only if user can phrase query close enough to information need:
- Misspellings (use spelling correction)
- Cross-language information retrieval (documents in same language cluster)
- Mismatch in searcher vocab and collection vocab
Rocchio model assumes single cluster, but for disjunctive queries, the relevant documents may be multimodal class (several clusters). Users may be reluctant to provide feedback, and feedback may generate long queries that are costly to compute.
For web, users typically do not want the interaction to be more than once, is difficult to explain to average user, and relevance feedback typically enhances recall which is not what users want.
Evaluation of feedback strategies¶
How to determine if relevance strategies actually do work?
- Start with query, get feedback and get updated results. These are biased to known relevant documents.
- Start with query, get feedback for collection without first results. Hard to compare performance, especially since most of relevant documents filtered out.
- Split collection into two distinct sets (use relevance improvement from first collection set on the second set).
- Use more user-facing metrics, e.g. time taken between different strategies
Other feedback strategies include,
- Pseudo-relevance (blind) feedback: Assume top k ranked documents are relevant and do immediate relevance feedback. Typically works, but can cause a bias in type of documents searched. Query drift.
- Indirect relevance feedback: Monitor clicks in high volume system, i.e. clickstream mining, and use metrics such as number of clicks.
Query reformulation¶
In contrast to relevance feedback, users give additional input on query words or phrases (e.g. more query terms). Some search engines suggest related queries.
Queries can be automatically expanded with a thesaurus. This thesaurus can be:
- Controlled set of vocabulary maintained by human editors
- Manual thesaurus with no canonical terms
- Automatically derived from word co-occurrence over collection, or documents
or paragraphs (
Ais term-document matrix,AA^Tis the similarity score between terms), e.g. “apple”, “pear” contexts typically appear with “harvest”, “peel”, “eat”, etc. - Query log mining from huge volume of queries
Relevance feedback typically performs better than query expansion, but query expansion has the benefit of being more easily understood.
XML retrieval¶
No consensus on how structured retrieval is best performed. Users are also bad at stating specific structural constraints, e.g. COUNTRY vs STATE, LANDMARK vs BUILDING. XML is used in this discussion, but can be extended to HTML.
Self-reading of XML introduction here.
Note that XML may have an overall schema that dictates what contexts are allowed. Notation for XPath (i.e. paths, contexts):
- Root element:
/ - Sequential traversal:
/book/title - From anywhere, with value “Macbeth”:
book/title#Macbeth - Arbitrary elements in path:
/book//title
Structured retrieval principle: A system should always retrieve the most specific part of a document answering the query (smallest unit). Problems:
- Hard to determine which are relevant, e.g. Macbeth: play, scene, act?
- Grouping by non-overlapping units (e.g. book chapters) hides context
- Use largest unit as indexing unit, but relevance of whole document not a good predictor of relevance of subelements.
- Use all leaves and extend upwards, but same problem (but in reverse).
- Index all elements, but introduces redundancy due to recurring nested elements.
- Difficult to distinguish between similar nodes, e.g. author vs writer,
and different contexts, e.g.
author#Gatesvssection#Gates, different schemas, e.g.author/lastname#Gatesvsauthor#Gates
Vector space model¶
The vocabulary terms in XML are the leaves of the XML tree. To account for the context under which the term is defined in, we consider lexicalized subtrees, where each dimension is a subtree of the XML tree that contains at least one vocabulary term (leaf). This contrasts with VSM in unstructured model where each dimension is a single vocabulary term.
To reduce the dimensionality further, we consider only contexts, i.e. all paths that end in only one vocabulary term. This gives us a set of structural terms (of context and vocabulary term), denoted \(\langle c_t, t \rangle\).
A simple measure of context similarity is the context resemblance function, which is zero if two contexts \(c_q\) and \(c_d\) do not match, and non-zero if they match (i.e. \(c_q \rightarrow c_d\) by inserting additional intermediate nodes), given by their path lengths \(|c_q|\) and \(|c_d|\),
If the contexts match, the resemblance has a value of 1.0.
This cumulates in a variant of the cosine measure called SimNoMerge,
where V is the entire vocabulary (i.e. non-structural terms), B is the set of all XML contexts, and \(W(q,t,c)\) and \(W(d,t,c)\) are the weights of term \(t\) in XML context \(c\), in query \(q\) and \(d\) respectively. The weights can be calculated using the standard tfidf.
Note that in practice, not all XML contexts belong to each query / document, and not all terms exist in the query / document. A better expression is,
In other words, for all vocabulary terms \(t\) existing in both query Q and document D, for all contexts in which they exist in the respective text, sum their respective weights within that text, weighted by the resemblance of the two contexts. Rephrasing in a more computational style,
The algorithm is termed SimNoMerge since different XML contexts are not
merged. The context matching condition can be relaxes in SimMerge by:
- Extend the context to include all containing contexts, e.g.
for
title#"Macbeth's", includeplay//title#"Macbeth's". - Merge all structural terms that have non-zero context resemblance, e.g.
/play/act/scene/titleand/play/titleare merged when matching against query/play/title#"Macbeth's". - Relax \(C_R\).
Review this for INEX relevance assessment,
i.e. {3E}, {2E,3L,3S}, {1E,2L,2S}, {1S,1L}, {0N}.
Week 9: Evaluating effectiveness of IR¶
- Measuring effectiveness of IR systems
- Test collections used
- Relevant and non-relevant documents
- Evaluating ranked retrievals to develop test sets
- User utility and document relevance
- Generation of result snippets
To measure IR effectiveness, need a test collection consisting of three things:
- Document collection
- Test suite of information needs, expressed as queries (at least 50)
- Set of relevance judgements (binary relevant or nonrelevant)
In particular, relevance is relative to the information need, not the query,
e.g. Information on whether drinking red wine is more effective at
reducing risk of heart attacks than white wine vs wine AND red AND white
AND heart AND attack AND effective. Tuning of system parameters to increase
relevance for one collection is not good enough.
Standard test collections¶
- Cranfield collection: Pioneering test collection
- Text Retrieval Conference (TREC): 1.89 million documents with 450 information needs
- GOV2: 25 million webpages, easily available
- NII Test Collections for IR Systems (NTCIR): Cross-language IR for East Asian languages
- Cross Language Evaluation Forum (CLEF): Cross-language IR for European languages
- Reuters-RCV1: 806,791 newswire documents
- 20 Newsgroups: 1000 articles from each of 20 Usenet newsgroups
Evaluation of unranked retrieval sets¶
Precision P and recall R, where precision is number of relevant items
retrieved over all retrieved items (including false positives), and recall is
the number of relevant items retrieved over all relevant items (including
false negatives).
Accuracy is a common measure, i.e. true positives and negatives over the whole collection, but is extremely skewed. Number of nonrelevant documents is much higher, so labelling some documents as relevant can lead to high rate of false positives.
Precision and recall are good in certain scenarios, e.g. precision is important to a user doing web query (highest relevance among retrieved documents), recall is important for professional searchers (completeness desired). With increasing number of retrieved documents, recall increases and precision typically decreases. F measure is used as a weighted harmonic mean:
where \(\beta^2 = \frac{1}{\alpha} - 1\). The default balanced F measure \(F_1\) uses \(\alpha = 1/2\), or in other words \(\beta=1\). Harmonic mean better as opposed to arithmetic mean, since performance will be rate worse if recall and precision very imbalanced.
Evaluation of ranked retrieval results¶
In a ranked retrieval context, the top-k retrieved documents has an associated
precision and recall. For increasing number of retrieved documents, recall
generally increases, while precision increases only if (k+1)th document
is relevant, otherwise there is a sharp drop. The curve can be simplified using
the interpolated precision \(p_{interp}(r) = {max}_{r' \ge r} p(r')\),
assuming people would like to see incrementally more documents (higher recall)
if they increase the total relevance of the viewed set (higher precision).
For each information need, the 11-point interpolated average precision (marked by the interpolated precision at recall = {0, 0.1, 0.2, …, 1.0}) is obtained, and averaged across all information needs.
Another common measure is the Mean Average Precision (MAP) which provides a single-figure measure of quality across recall levels. For each information need, the incremental precision values for each subsequent document in the top k retrieved are averaged, and this value is averaged over all information needs.
MAP scores vary strongly with information need, so test set of information needs must be large and diverse enough to be representative.
Since not all documents are considered by a user in a web query, another solution is to use “Precision at k” documents, but is strongly affected by total number of relevant documents for a query.
R-precision alleviates this problem by adjusting for the size of relevant
documents (which can be pooled from top returned results, so not necessarily
representative), such that at the break-even point, both precision and recall
are equal to r/|Relevant|. This is empirically shown to be highly
correlated to MAP.
Another is the Receiver Operating Characteristics (ROC) curve that plots true positive rate against increasing false positive rate, where the single-valued measure is the area under the ROC curve.
I’m ignoring this one:
Assessing relevance¶
Test information needs need to be germane to the test document collection. Such information needs have to be pulled by domain experts, otherwise they do not resemble the actual information need. The results are skewed by choice of collection, queries and relevance judgement sets.
For large collections, relevance judgements are pooled over subset of collection formed from top k documents returned by number of different IR systems. While human judges form idiosyncratic and variable relevance judgements, the main point still lies in how the IR system satisfies these idiosyncratic needs. The kappa statistic is used to determine the level of agreement between judges, designed for categorical judgements:
Here, P(A) is the proportion of times the judges agreed, and P(E) the
proportion of times they are expected to agree by chance.
- 1: Two judges always agree
- > 0.8: Good agreement
- 0.67 - 0.8: Fair agreement
- < 0.67: Dubious agreement
- 0: Two judges agree by chance
- < 0: Worse than random
Note the error in the image above: P(relevant) = 0.7875. The probability
they agree by chance is given by the probability of both judges agreeing,
simply based on the aggregated relevance / non-relevance chance for all
(document, judge) pairs.
Typically use pairwise kappa for more than two judges. Taking a judge’s opinion as gold standard typically doesn’t change the relative effectiveness of IR systems being evaluated.
Corrections to relevance judgements include using ordinal notion of relevance (grouping into major relevance classes). It is however still important to consider marginal relevance (of one document relative to other documents), such that the total set of documents examined yield much higher diversity and utility to the user. Can approach using distinct facts as evaluation units, but makes it harder to create a test collection.
Other benchmarks¶
- Speed of indexing (as function of document length distribution)
- Speed of search (as function of index size)
- Expressiveness of query
- Speed of retrieval on complex queries
- Size of document collection (number and variety)
- NFR: Information security
Measure of user utility for a search engine can be obtained by determining return rate of user to the same search engine, but these are also affected by advertisers on the search engine. For enterprise intranet search engine, the relevant metric is user productivity (i.e. time taken by users to find information they need).
But these measures are only proxies - user studies need to be performed for better characterization. For search engines with large userbase, typically can perform A/B testing and use clickstream mining to determine rate of top result click, simply by changing a single parameter from the control.
A useful term: Overall Evaluation Criterion (OEC). But beware, some
changes may be uncorrelated, result in wrong OEC. Need to be clear what the
end goal is (e.g. add price to page, decreases clicks, but sales remain the
same).
Result snippets¶
Summaries of document can be static or dynamic, the latter customized according to user need. Metadata can be used for static snippets, such as description metadata or title or author, to avoid accessing the actual document in real-time. NLP can be used to effectively summarize the document.
For dynamic content, typically show “keyword-in-context” that are (1) maximally informative wrt terms, (2) self-contained, (3) short enough, but are expensive to compute. Snippet generation must be fast since many documents are yielded. Can consider snipping a fixed number of characters. Caching regularly is also key.
Week 8: Complete search system¶
In the computation of cosine similarity, by doing a term-by-term processing, we only consider a limited subset of documents in the posting list, hence we do not need to consider the whole collection search space.
One faster way is to ignore query term frequency weight, i.e. tf = 1. This
reduces the requirement to do a costly multiplication during the dot product.
Since we are only concerned with the number of search results K in the end,
another way is to only consider documents likely to be among the K highest
scores.
This inexact retrieval is not necessarily a bad thing since the cosine measure
is only a proxy for user-perceived relevance. The main idea is more akin to
“building evidence of document relevance”.
This requires a two main steps:
- Retrieve set of documents
Awhich are likely to contain theKdocuments, i.e.K < |A| << N. - Return
Ktop-scoring documents inA.
Some ideas to consider:
Index elimination: For a multi-term query, we can consider documents with a subset of query terms.
- Using terms with high idf, ignore low idf, i.e. treat as stopwords.
- Consider only documents that contain many of the query terms, i.e. using postings traversal. This can be done using concurrent document traversal across multiple postings lists (advance pointer to smallest document).
Champion lists: Precompute set of
rdocuments with highest tf values for termt. Note thatrshould be much larger thanK, and can be adjusted with the rarity of the term.Can be segregated into high and low champion lists - if not enough documents obtained from merging high lists, can further account with low.
We can extend this further into n-tiered lists.
Static quality score: Assign query-independent score
g(d)(e.g. from number of referral links) that can be summed with the query-dependent score. This means we can order the postings list in decreasing order ofg(d), instead of increasing document ID. This captures how authoritative the document is.Impact ordering: Ordering documents in decreasing order of tf. Similarly, the query terms can be processed in order of decreasing idf. Stop conditions: (1) Fixed number of documents
r, (2) threshold value oftf, before doing a union of documents. Even better, sort query terms byidfand terminate early when scores relatively unchanged.Cluster pruning: Pick \(\sqrt{N}\) leaders. For each follower (not leaders), assign them a leader. Search involves finding leaders, then search among followers. Can also tune by setting
b1closest leaders for each document, andb2closest leaders for the query.Query-term proximity: Users prefer documents in which most query terms appear close to each other, e.g.
wbe the width of smallest window for document containing all query terms. Can consider ignoring stopwords etc.Metadata: Searching by parametric indices (i.e. publication year, pages) or by free-text zone indexes (i.e. title, abstract, references). Alternative ways of storing the postings lists, either by each zone, or for each document state where the term appears.
To incorporate proximity information, the query parser typically entail multiple retrieval attempts:
- Phrasal query for
rising interest rates, and then rank by VSM. - If less than
Kdocs, run two term phrase queryrising interestandinterest ratesand rank resulting documents by VSM. - If still less than
Kdocs, we only use VSM for individual terms.
In complete search system, we can consider this overview:
- Documents stream in for parsing and processing
- Result snippets (representing the document) are generated and cached
- Index documents, e.g. zone and field index, tiered positional index, k-gram
- User query is parsed and results retrieved, optionally corrected if insufficient results.
- Retrieved documents are ranked by a scoring model, which can be built using machine learning.
Contrast all these types of indexing:
- Boolean queries require exact match
- Wildcard queries as part of VSM can spawn multiple terms
- Phrasal queries cannot use VSM to score since latter loses positional information
Week 7: Ranked retrieval¶
Relevant results are ranked higher in a ranked retrieval model. This is better for users that (1) may have difficulty crafting precise Boolean queries, (2) will be unable to sieve thousands of document matches. RR models are typically associated with free text queries, which are more intuitive for users.
Possible solutions for relevance scoring functions:
- Jaccard coefficient: Documents do not need to be the same size + score [0,1]. However, does not account for term frequency (search Caesar in doc1 Caesar Caesar and doc2 Caesar) and document frequency (search the Caesar in doc1 Caesar and doc2 the).
To account for term frequency, we use the alternative term collection frequency to weigh the score. But raw frequency has high variance, which can cause the factor to dominate. Better to scale with the log instead.
\(w_{t,d} = 1 + {log}_{10} \text{tf}_{t,d}\)
As for document frequency, since rare terms give more information that common terms, can scale with inverse of document frequency. Here, N is used to scale so that the value will always be non-negative (log(x), x >= 1). This is used to differentiate between importance of words within the same query.
\(\text{idf}_t = {log}_{10}\left(\frac{N}{\text{df}_t}\right)\)
This gives us the tf-idf weighting scheme:
\(w = (1 + {log}_{10} {tf}{t,d}) \times {log}_{10}\left(\frac{N}{df_t}\right)\)
- tf-idf weighting: \(Score(q,d) = \sum_{t \in q \cap d}{\text{tf-idf}_{t,d}}\).
Each document is represented by a point in the coordinate system, whose axes
are each term itself. This is a |V|-dimensional space.
Note that:
- This is effectively a sparse matrix.
- The bag-of-words model also does not consider word ordering in document.
There are many variations of weights:
Can mix and match, specified in SMART notation: ddd.qqq, i.e.
lnc.atn means log-term frequency + no idf + cosine normalization
for document, and augmented term frequency + idf + no normalization.
Typically lnc.ltc for web search engines (avoids expensive calculation).
How to calculate IDF for queries? Perhaps can use pseudo-queries. Also an example to practice with.
Queries as vectors¶
To use this idea, can represent queries as a vector in the same space as well. The rank of the documents will be equal to the proximity to the query in this space, i.e. Euclidean distance.
To match documents with similar distribution of terms, we rank in order of increasing angular separation, i.e. cosine of angle.
Of course, we can normalize each vector during the pre-processing step instead.
The selection of top K documents can be done with O(J) build heap and
K * O(lg J) extract max, as opposed to complete sorting O(J*lg(J) + K).
Week 6: Index compression¶
To compress the index, we need to know the frequency behaviour of terms:
- Heaps’ law \(M=kT^b\) gives an empirical growth to the vocabulary size given the number of tokens \(T\) seen in the collection. Typically, \(30 \leq k \leq 100\) and \(0.4 \leq b \leq 0.6\).
- Zipf’s law states that \(k^{th}\) most frequent term has frequency
proportional to \(1/k\), e.g. in the Brown corpus,
theoccurs 7% of the time,andoccurs 3.5% of the time,ofoccurs roughly 2.3% times.
Dictionary compression¶
- Dictionary-as-a-string: Instead of allocating fixed character array sizes for each term, we store as a whole concatenated string, and store pointers to each term. This requires per term: 4 bytes frequency, 4 bytes positings pointer, 3 bytes pointer, requires roughly 60% of original space.
- Blocking: Same as dictionary-as-a-string, but group as block of size \(k\) instead. Only issue is need to perform linear search through each block.
- Front coding: Use first number of characters as common prefix.
Postings compression¶
- Gap encoding: As opposed to storing the entire document ID, we encode only the gaps to reduce the storage size. Issue with less frequent terms with much larger gaps.
- Variable byte gap encoding: Reserve 1 bit as a continuation term,
A little similar to unicode encoding, which follows a slightly different encoding style. Reasons for difference is to (1) support validation, (2) fast forwarding, (3) easier backtracking.
Effects of compression:
Week 5: Index construction¶
Many design decisions in IR are based on characteristics of hardware, in particular seek time and transfer time in hard drive storage.
- Disk seeking does not transfer data, so transfer of one large chunk of data to memory is faster than many small chunks.
- Memory space is several orders smaller than hard drive space.
We use RCV1 for this lecture, i.e. one year of Reuters newswire (1995-1996).
Some statistics:
- Documents (N): 800,000
- Average tokens per document (L): 200
- Terms (M): 400,000
- Average bytes per token: 6 (w space/punctuation), 4.5 (wo)
- Average bytes per term: 7.5
- Tokens: 100,000,000
Note that we are dealing with (term, docID) pairs, i.e.
(7.5 + 4) x 100,000,000 bytes = 1.1 GB.
Inefficient to process all data on disk as well. Instead a hybrid method is
favored, i.e. both memory and hard disk operations.
Blocked sort-based indexing (BSBI)¶
- Use termID instead of terms itself (map), each record is 8-bytes (termID, docID).
- Define block as, e.g., 10M records (~80 MB)
- Accumulate records for each block + sort + create posting lists + write
- Merge blocks into one sorted order
Merging can be done using binary merges (i.e. log2(10) = 4 layers). In each layer, read into memory runs of 10M blocks, merge, then write back (?).
Merging can be done efficiently using n-way merge (in this case, for all 10 blocks simultaneously). We can read reasonably sized chunks to minimize disk seeking losses.
Single-pass in-memory indexing (SPIMI)¶
Problem: Assumption that we can keep the whole dictionary in-memory for term-termID mapping.
Instead of maintaining a term mapping, we construct the index by hashing, sort the terms within the dictionary, then write to disk.
This is essentially what the initial idea could have been at the start, i.e. build a hashtable and append terms, then sort terms instead of tokens.
Key differences¶
BSBI:
- Constructs (termID, docID) pairs and sorts all
Tpairs,O(T log T) - Group into
Bblocks and construct inverted index for each block,~O(M/B) - n-way merge of
Bblocks with total ofMtermIDs,O(M)
SPIMI:
- In same block, collect (term, docID) pairs and construct inverted index
- Sort terms then write block to disk and repeat
- n-way merge of
Bblocks with total ofMterms,O(M).
Distributed indexing¶
Distributed manner of indexing, with assumption that individual machines are fault-prone.
MapReduce¶
Frame work into map phase and reduce phase.
- Map: Parsers process input -> list(k, v)
- Reduce: Inverters process (k, list(k, v)) -> output (for range of index)
Dynamic indexing¶
Collections are typically dynamic. One way is to have a main big index, and new additions go into a smaller auxiliary index (and merge results); deletions are maintained in an invalidation bit-vector (filter results).
We periodically re-index into the main index, requiring up to floor(T/n)
accesses of the auxiliary index, where T is the total number of postings and
n the size of the auxiliary index. Not sure what this is, refer to
textbook.
Week 4: Tolerant retrieval¶
Dictionary to be implemented either as a tree or hashtable. Hashtable is faster, but no easy way to find minor variations, e.g. judgement vs judgment, does not support prefix search, and occasionally requires rehashing.
Binary trees can be used, either using binary trees or B-trees (balanced). B-trees of order M has nodes of at most M children and contains M-1 keys. Main benefit over AVL tree is that it’s better for disk-based trees, since the keys in the same node are stored in the same block.
Tolerant retrieval¶
Query may not be exact, better if search engine allows for ambiguity, e.g. prefix search (kilo*) or wildcards (colo*r). Postfix search done by maintaining a reversed B-tree. This supports X*Y styled searches, but calculation of intersection between X* and *Y terms is expensive.
General wildcard queries X*Y can be better handled using Permuterm index. Essentially:
Append special
$symbol to word to be indexed, e.g.tie$Index all rotations of the term, i.e.
tie$,ie$t,e$ti,$tiePerform wildcard search by rotating wildcard to the right:
XlookupX$X*lookup$X**XlookupX$**X*lookupX*X*YlookupY$X*
Bigram (k-gram) index¶
Permuterm increases proportionally to average word length. To solve this,
we can approach this using a letter bigram index instead, e.g.
searching mon* results in intersection query $m AND mo AND on.
False positives, e.g. moon are filtered out post-query.
Note
Procedure: Add word boundaries, then index as bigram index, i.e. from
Sad acorn -> $s, sa, ad, d$, $a, ac, co, or, rn, n$.
A search for a*rn will query merge on $a, rn and n$.
Fast and space efficient.
Problem is, wildcards can result in very expensive query execution, especially
for short prefix searches, e.g. prog*.
Spelling correction¶
Two principal uses:
- Correcting document(s) being indexed
- Correcting user queries to retrieve right answers
Either done with isolated words, or sensitive to context, e.g. I flew form New York. For isolated word correction, it uses a lexicon from which correct spellings come, such as a dictionary.
Alternatively, can use metrics to determine closest word for word correction:
Edit distance using Levenshtein distance (minimum number of insert, delete, replace, transpose operations on character level to obtain the second word), typically dynamic programming:
d(HEY, BOT) = min( d(HEY,BO)+1, d(HE,BOT)+1, d(HE,BO)+1 )d(HEY, BOY) = min( d(HEY,BO)+1, d(HE,BOY)+1, d(HE,BO)+0 )intuitively, Insertion (left/middle), Match/Replace (right)
Weighted edit distance
Using probability model to give more weight to certain character replacements, e.g.
m -> nmore likely thanm -> q`. The dynamic programming is then modified to handle weighted input matrix.Problem now lies in which term to compute the edit distance to (in order to correct the word).
ngram overlap
Enumerate all ngrams in lexicon. Retrieve all lexicon ngram matches, and threshold by number of matching ngrams (or with other variants, e.g. weighted by keyboard layout, assume initial letter correct). Problem is
membershipanddecemberare both candidates fornovember.Possible to use Jaccard measure: \(\frac{|X\cap Y|}{|X\cup Y|}\), i.e. the number of overlaps with total number of ngrams.
Context-sensitive spelling correction¶
If we want to correct flew form Heathrow to flew from Heathrow, we
need the surrounding context. To obtain possible corrections, we can enumerate
all possible phrases with one word corrected at a time:
flew from Heathrowfled form Heathrowflea form Heathrow
Alternatively, the phrase can be broken down into biword conjunctions, and look for biwords that correct only one term.
flew fromfrom Heathrowflea form
We can then enumerate phrases from lexicon containing common biwords. Heuristics for phrase suggestions can be:
- Hit-based spelling correction: Corrections with the most hits
- Query log analysis + tweaking (not covered…?)
Spelling correction can be computationally expensive. Number of queries can be reduced by running only for queries with few matches, or avoid routine runs.
Soundex¶
Class of heuristics to expand a query into phonetic equivalents, note that this is language-specific - mainly for names, and was invented for US census.
Idea is to turn every token into 4-character reduced form, and then build and search index on the reduced forms. Typical algorithm:
- Retain first letter
- Change all occurrences of following letters to 0: A, E, I, O, U, H, W, Y
- Change letters to digits:
- B, F, P, V -> 1
- C, G, J, K, Q, S, X, Z -> 2
- D, T -> 3
- L -> 4
- M, N -> 5
- R -> 6
- Reduce consecutive digits into one
- Remove all zeros from string
- Pad string with zeros and return first four positions
Not very effective for non-English names, e.g. Xin vs Hsin.
Example spelling correction algorithm in Python.
Week 3¶
Skip pointer¶
At indexing time, skip pointers can be added to allow traversal to skip groups. In the example below, suppose pointers A and B are at 41 and 11 respectively, the next traversal involves the smaller pointer jumping to 31. Costs come from comparisons and space, as well as adjusting pointers for dynamic collections.
Simple heuristic uses \(\sqrt{L}\) evenly-spaced skip pointers, which ignores the distribution of query terms. With modern hardware (Bahle et al. 2002), the IO cost of loading bigger postings list can outweigh gains from in-memory merging.
Phrase queries¶
Searching phrases, e.g. “Stanford university” instead of simply individual words by themselves in separate contexts.
Implementation using biword indexes¶
Possible implementation using biword indexes, e.g. “I visited Stanford University” -> “I visited”, “visited Stanford”, “Stanford University”, and using Boolean query on biwords. Can yield false positives, e.g. “I visited my house. My friend visited Stanford University”.
Implementation using extended biwords¶
Parsing the indexed text and perform part-of-speech-tagging (POST), i.e.
assigning grammar to words such as Noun (N) or articles/prepositions (X).
Any sequence of the form /NX*N/ is an extended biword and also stored
in the dictionary, e.g. “catcher in the rye” -> “catcher rye”.
Same issue, false positives, and index blowup due to much larger dictionary compared to unigrams. Biword indexes not standard solution, but can be part of a compound strategy.
Implementation using positional indexes¶
The general technique is by augmenting the inverted index to include positions for every occurrence as well, e.g.
<be: 993427;
1: 7, 18, 33, 72, 86;
2: 3, 149;
4: 17, 291, 430, 434;
5: 363, 367; ...>
For example, to search for to be or not to be, we recursively merge at
the document level:
- Search for postings with
toandbe - For each document, check positions to verify
to beexists - Search for posting with
to beandor - For each document, check positions to verify
to be orexists - And so on…
This allows for proximity queries as well, i.e. search only nearby words. Positional indices expand postings storage substantially, which we can apply index compression over.
Index size depends on average document size, as well as frequency of term appearance. Some rules of thumb:
- Positional index roughly 2-4x larger than non-positional index
- Positional index size roughly 35-50% of original document size
Williams et al. (2004) added a next work index that stores words following a given word, executed in 1/4 of time but 26% more space over a positional index.
Hybrid¶
The positional index and biword index can be both combined, storing biwords that are generally more popular.
Choosing terms¶
Text extraction¶
- Format: PDF / Word / Excel / HTML?
- Language? Many have different languages in same document.
- Character sets?
Granularity of indexing¶
- What is a unit document? File / email / set of HTML pages e.g. song lyrics (page), birthday of Lincoln (sentence)
- How coarse (everything matches)? How fine (nothing matches)?
These choices usually depend on the context / projected use of the IR engine.
Tokenization¶
A token is a sequence of characters grouped together as a useful semantic unit. Each token is a candidate for an index entry (terms), but how to determine if it should be emitted? e.g.
Apostrophes, hyphens, spaces
- Finland’s -> Finland / Finlands / Finland’s
- Aren’t -> Aren t / Are n’t / Are not
- Hewlett-Packard -> Hewlett Packard
- state-of-the-art -> state of the art
- lowercase / lower-case / lower case
- San Francisco
- Los Angeles-San Francisco
Numbers, dates
- 3/20/13 / Mar. 12, 2013 / 20/3/13
- 55 B.C.
- B-52
- My PGP key is 324a3df234cb23e
- 234-2333
- Product code: BB01-E02
Language
- Chinese / Japanese no spaces between words, and no guarantee of unique tokenization
- Japanese intermingle multiple writing systems: Katakana, Hiragana, Kanji, Romaji, Arabic numerals. End-users typically express queries in Hiragana
- Arabic / Hebrew written right to left, but things like numbers are left to right
- Ligatures
- Unicode surface presentation is complex, but stored in linear order
Stop word removal¶
Stop list contains common words from dictionary to be excluded, e.g. words that have little semantic content such as ‘the’ and ‘to’. Current trend away from this due to (1) good compression techniques, (2) good query techniques, (3) required in certain phrase queries, e.g. “King of Denmark”, “Let it be”, “flights to London”.
Normalizing tokens to terms¶
Normalization of words into the same form, e.g. U.S.A. and USA, called a term (an entry in our IR system dictionary). This defines equivalence classes, e.g. deleting periods, deleting hyphens, removing accents, umlauts, diacritics…, case-folding, spelling / format variations, synonyms, transliteration by soundex?
Most important criterion: How do users write their queries? e.g. Tübingen -> Tubingen, typically written in lowercase
Another related technique is asymmetric expansion, which may be potentially more powerful but often less efficient:
- window -> window, windows
- windows -> Windows, windows, window
- Windows -> Windows
Lemmatization¶
Reduce inflection / variant forms to base form, e.g. am, are, is -> be.
Stemming¶
Reduce terms to their roots before indexing, e.g. stemming, which chops away the suffixes, e.g. automate, automatic, automation -> automat
Porter’s algorithm is a list of conventions with 5 phases of reduction applied sequentially, that is commonly used for stemming English, e.g.
- sses -> ss
- ies -> i
- ational -> ate
- tional -> tion
- (m>1) ement -> “” (word length dependent)
Other stemmers exist, e.g. Lovins stemmer which is a single-pass, longest suffix removal (about 250 rules). Lemmatizer must perform full morphological analysis with modest benefits for retrieval. Also dependent on language.
Week 2¶
Information retrieval¶
Information retrieval (IR) is finding materials of an unstructured nature that satisfies an information need from within large collections.
Initial strategies for search in large corpus is a simple string search, but this method does not scale (e.g. slow, cannot support complex operations, ranked retrieval not possible).
Term-document incidence¶
| Term | Anthony and Cleopatra | Macbeth | Hamlet |
|---|---|---|---|
| Antony | 1 | 1 | 0 |
| Brutus | 1 | 0 | 1 |
| Caesar | 1 | 1 | 1 |
| Calpurnia | 1 | 0 | 0 |
Incidence vectors can be used to generate search query, e.g.
Brutus and Caesar but not Calpurnia -> 101 AND 111 AND 011.
Not trivial to implement NOT operation to detect non-presence.
Assumptions of IR¶
- Collection: Fixed, static set of documents
- Goal: Retrieve documents with information relevant to user’s information need and helps user complete a task
Search engines need to identify what the task / information need is behind the search query. The classic search model below represents the flow from task to completion.
Metrics for a good retrieval system:
- Precision: Fraction of retrieved documents relevant to user’s unordered
- Recall: Fraction of relevant documents in collection that are retrieved
- Others
Data structures¶
2D fixed array is a naïve solution, but consider many documents with few words
and many search terms. Sparse matrix representation is much better.
This is an inverted index: For each search term t, we store a sorted list
of all document IDs containing t.
This is a dictionary-of-sets.
Construction involves tokenization and linguistic-aware modifications:
One optimal algorithm is to do bulk sorting: (1) Sort by document ID, (2) Sort by search terms, (3) Construct dictionary directly. This has an added benefit of ignoring duplicate terms, and generate sorted list. End result is dictionary with frequency + sorted linked list (in memory). Also forms the word list in sorted order.
Note that document frequency also stored to optimize query, later on it.
Alternative is to go without the sorting, and maintain a pointer to the end of the linked list. Possible?
Querying inverted index¶
Processing AND query involves stepwise walking through each list in sorted
order: when pointer to each list reach the same docID, the docID
is added to the merged list. Merge query is O(x+y) time, where x and y
is the size of each list. We can extend this to composite queries like
A AND NOT B.
Query optimization: Start with smallest set, then cut further. Same applied
to (A OR B) AND (C OR D) queries, by estimating the size of each OR block
(sum of frequencies) then selecting in increasing order.
This is the epitome of a Boolean retrieval model, being able to answer
queries that are Boolean expressions, by viewing documents as a set of words
and providing exact matches, e.g.
“What is the statute of limitations in cases involving the federal tort claims
act?” -> LIMIT! /3 STATUTE ACTION /S FEDERAL /2 TORT /3 CLAIM.
Extra exercises:
Week 1¶
Language model¶
Language model (LM) can be created based on a text collection, with probabilities assigned to sequence of words after training. This probabilistic model does not require knowledge of the grammar. One such model is the unigram model - the language as an unordered collection of tokens (e.g. bag of words), which outputs a count / probability of an input.
Note
Suppose an example from Lady Gaga:
I want your love and I want your revenge.
Using a probability model, we treat each individual words as an individual event. To mitigate issues with zero probabilities in limited samples, smoothening can be employed to bias all counts in the LM. In an LM with five more words,
Context matters. An ngram LM considers a seqeuence of n tokens, e.g. bigrams (n=2) and trigrams (n=3). Special START and END markers can be used to encode beyond word boundaries. Such a model can be used to predict a current word from the previous n-1 words, based on the Markov assumption. Ngrams models more accurate but exponentially costly to construct.
Note
Markov Assumption: Future behaviour of dynamical system only depends on its recent history, i.e. Ngram model is (N-1)-order Markov model.
Language model should be built in the way it’s designed to be understood, e.g. model for English should be from left-to-right.