CS3245 Information Retrieval

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:

../../_images/20210414_082411.png ../../_images/20210414_082432.png

We rank by probability, using the binary random variable \(R\) to denote whether document is relevant to query. Probability ranking principle (PRP).

../../_images/20210414_082556.png

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).

  1. Find measurable statistics that affect judgement of document relevance
  2. Use them to estimate probability \(P(R=1|d,q)\)
  3. Order documents by decreasing probability.
../../_images/20210414_083344.png

The formulation relies on Bayes’ rule. Can express derivation by first converting to pure AND form. A couple of notes:

  1. \(P(x|R=1,q)\): Given a relevance document retrieved with q, probability that the representation is x.
  2. \(P(R=1|q)\): Probability of retrieving a relevant document for q.
  3. \(P(x|q)\): Given a query q, probability that there exists x.
../../_images/20210414_084313.png

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:

../../_images/20210414_084501.png ../../_images/20210414_084709.png

Simplify the notation,

../../_images/20210414_084808.png

We further assume terms not in query are not relevant (i.e. equally likely to occur in either relevant or irrelevant documents),

../../_images/20210414_084856.png

We then remove the second term, by converting it into an expression that is independent of the relevance:

../../_images/20210414_085108.png
\[{RSV}_d = \sum_{t:x_t=q_t=1} \log{\frac{p_t (1-u_t)}{u_t (1-p_t)}}\]
../../_images/20210414_085518.png

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,

../../_images/20210414_085757.png

In practice, we simplify to IDF,

../../_images/20210414_090043.png

A quick thought on probabilistic models:

../../_images/20210414_090144.png ../../_images/20210414_090311.png

Okapi25:

../../_images/20210414_090344.png ../../_images/20210414_090419.png ../../_images/20210414_090458.png

Language model of retrieval

Representation of the type of language. This approach can also be used for information retrieval as well.

../../_images/20210414_090811.png

“prior” -> “prior probability”, i.e. static quality score.

../../_images/20210414_090908.png

Language model, e.g. unigram, bigram, trigram, etc.

../../_images/20210414_091107.png

Key is, we generate a language model for every document, and see the probability of generating that particular query.

../../_images/20210414_091244.png

Same thing again, we need to smooth the probabilities:

../../_images/20210414_091337.png

We can use another method of smoothening, which gives us the mixture model:

../../_images/20210414_091438.png ../../_images/20210414_091537.png ../../_images/20210414_091721.png

Give these exercises a try:

../../_images/20210414_091748.png ../../_images/20210414_091822.png

Language model is more effective when recall levels are high:

../../_images/20210414_091859.png

Comparison with VSM:

../../_images/20210414_092143.png ../../_images/20210414_092201.png ../../_images/20210414_092212.png

Week 10: Relevance feedback

User giving feedback on relevance:

  1. User issues short query
  2. System returns set of retrieval results
  3. User marks documents as relevant / nonrelevant
  4. System computes better representation and retrieves revised set of results
../../_images/20210318_bikerelevance.png

Relevance feedback is classically done using Rocchio Algorithm with a VSM:

../../_images/20210318_rocchio.png

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.

../../_images/20210318_argmax.png ../../_images/20210318_argmax_cosine.png

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).

../../_images/20210318_rocchio2.png ../../_images/20210318_rocchiomod.png

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.

../../_images/20210318_003016.png

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?

  1. Start with query, get feedback and get updated results. These are biased to known relevant documents.
  2. Start with query, get feedback for collection without first results. Hard to compare performance, especially since most of relevant documents filtered out.
  3. Split collection into two distinct sets (use relevance improvement from first collection set on the second set).
  4. 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 (A is term-document matrix, AA^T is 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.

../../_images/20210322_XML.png

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#Gates vs section#Gates, different schemas, e.g. author/lastname#Gates vs author#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\).

../../_images/20210322_XMLdiagram.png

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|\),

\[C_R \left( c_q,c_d \right) = \frac{1+|c_q|}{1+|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,

\[SimNoMerge \left( q, d \right) = \sum_{c_k, c_l \in B} \left( C_R \left( c_k, c_l \right) \sum_{t \in V} \left( W \left( q,t,c_k \right) \cdot \frac{W \left( d,t,c_l \right)} {\sqrt{\sum_{c \in B, t \in V} W^2 \left( d,t,c \right)}} \right) \right)\]

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,

\[SimNoMerge \left( Q, D \right) = \sum_{t \in Q \cap D} \left( \sum_{\langle c_q, t \rangle \in Q, \langle c_d, t \rangle \in D} \left( C_R \left( c_q, c_d \right) \sum_{q \in Q} \cdot W \left( Q,\langle c_q, t \rangle \right) \cdot \bar{\bar{W}} \left( D,\langle c_d, t \rangle \right) \right) \right)\]

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,

../../_images/20210323_SNM.png

The algorithm is termed SimNoMerge since different XML contexts are not merged. The context matching condition can be relaxes in SimMerge by:

  1. Extend the context to include all containing contexts, e.g. for title#"Macbeth's", include play//title#"Macbeth's".
  2. Merge all structural terms that have non-zero context resemblance, e.g. /play/act/scene/title and /play/title are merged when matching against query /play/title#"Macbeth's".
  3. 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:

  1. Document collection
  2. Test suite of information needs, expressed as queries (at least 50)
  3. 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).

\[\begin{split}Precision = P\left(relevant retrieved|retrieved\right) \\ Recall = P\left(relevant retrieved|relevant\right)\end{split}\]

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:

\[\frac{1}{F} = \alpha \frac{1}{P} + (1-\alpha) \frac{1}{R} = \frac{\beta^2 P + R}{\left(\beta^2+1\right) PR}\]

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.

../../_images/20210317_fmeasure.png

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).

../../_images/20210317_interp.png

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.

../../_images/20210317_score.png

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.

../../_images/20210317_232507.png ../../_images/20210317_MAP.png

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.

../../_images/20210317_ROC.png

I’m ignoring this one:

../../_images/20210317_233950.png

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:

../../_images/20210317_234410.png

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:

  1. Retrieve set of documents A which are likely to contain the K documents, i.e. K < |A| << N.
  2. Return K top-scoring documents in A.

Some ideas to consider:

  1. Index elimination: For a multi-term query, we can consider documents with a subset of query terms.

    1. Using terms with high idf, ignore low idf, i.e. treat as stopwords.
    2. 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).
  2. Champion lists: Precompute set of r documents with highest tf values for term t. Note that r should be much larger than K, 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.

  3. 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 of g(d), instead of increasing document ID. This captures how authoritative the document is.

  4. 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 of tf, before doing a union of documents. Even better, sort query terms by idf and terminate early when scores relatively unchanged.

  5. 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 b1 closest leaders for each document, and b2 closest leaders for the query.

  6. Query-term proximity: Users prefer documents in which most query terms appear close to each other, e.g. w be the width of smallest window for document containing all query terms. Can consider ignoring stopwords etc.

  7. 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.

../../_images/20210317_zone_indices.png

To incorporate proximity information, the query parser typically entail multiple retrieval attempts:

  1. Phrasal query for rising interest rates, and then rank by VSM.
  2. If less than K docs, run two term phrase query rising interest and interest rates and rank resulting documents by VSM.
  3. If still less than K docs, we only use VSM for individual terms.

In complete search system, we can consider this overview:

../../_images/20210317_search.png
  1. Documents stream in for parsing and processing
  2. Result snippets (representing the document) are generated and cached
  3. Index documents, e.g. zone and field index, tiered positional index, k-gram
  4. User query is parsed and results retrieved, optionally corrected if insufficient results.
  5. 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:

  1. 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)\)

  1. tf-idf weighting: \(Score(q,d) = \sum_{t \in q \cap d}{\text{tf-idf}_{t,d}}\).
../../_images/20210307_195745.png

Each document is represented by a point in the coordinate system, whose axes are each term itself. This is a |V|-dimensional space.

../../_images/20210307_201642.png

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:

../../_images/20210307_201707.png

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.

../../_images/20210307_202145.png

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.

\[cos\left(\vec{q},\vec{d}\right) = \frac{\vec{q} \cdot \vec{d}}{|\vec{q}||\vec{d}|} = \frac{\sum_{i=1}^{|V|} q_i d_i}{\sqrt{\sum_{i=1}^{|V|} q_i^2} \sqrt{\sum_{i=1}^{|V|} d_i^2}}\]

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, the occurs 7% of the time, and occurs 3.5% of the time, of occurs roughly 2.3% times.

Dictionary compression

  1. 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.
../../_images/20210219_130723.png
  1. 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.
../../_images/20210219_131815.png
  1. Front coding: Use first number of characters as common prefix.
../../_images/20210219_132034.png

Postings compression

  1. 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.
../../_images/20210219_132349.png
  1. Variable byte gap encoding: Reserve 1 bit as a continuation term,
../../_images/20210219_132702.png

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:

../../_images/20210219_133812.png

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)

  1. Use termID instead of terms itself (map), each record is 8-bytes (termID, docID).
  2. Define block as, e.g., 10M records (~80 MB)
  3. Accumulate records for each block + sort + create posting lists + write
  4. Merge blocks into one sorted order
../../_images/20210213_234109.png ../../_images/20210213_234146.png

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.

../../_images/20210214_000914.png

Instead of maintaining a term mapping, we construct the index by hashing, sort the terms within the dictionary, then write to disk.

../../_images/20210214_001016.png

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:

  1. Constructs (termID, docID) pairs and sorts all T pairs, O(T log T)
  2. Group into B blocks and construct inverted index for each block, ~O(M/B)
  3. n-way merge of B blocks with total of M termIDs, O(M)

SPIMI:

  1. In same block, collect (term, docID) pairs and construct inverted index
  2. Sort terms then write block to disk and repeat
  3. n-way merge of B blocks with total of M terms, 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.

../../_images/20210214_004302.png ../../_images/20210214_004310.png ../../_images/20210214_004401.png

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:

  1. Append special $ symbol to word to be indexed, e.g. tie$

  2. Index all rotations of the term, i.e. tie$, ie$t, e$ti, $tie

  3. Perform wildcard search by rotating wildcard to the right:

    • X lookup X$
    • X* lookup $X*
    • *X lookup X$*
    • *X* lookup X*
    • X*Y lookup Y$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:

  1. Correcting document(s) being indexed
  2. 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:

  1. 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)

../../_images/20210213_levdist.png
  1. Weighted edit distance

    Using probability model to give more weight to certain character replacements, e.g. m -> n more likely than m -> 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).

  2. 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 membership and december are both candidates for november.

    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 Heathrow
  • fled form Heathrow
  • flea form Heathrow

Alternatively, the phrase can be broken down into biword conjunctions, and look for biwords that correct only one term.

  • flew from
  • from Heathrow
  • flea form

We can then enumerate phrases from lexicon containing common biwords. Heuristics for phrase suggestions can be:

  1. Hit-based spelling correction: Corrections with the most hits
  2. 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:

  1. Retain first letter
  2. Change all occurrences of following letters to 0: A, E, I, O, U, H, W, Y
  3. 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
  4. Reduce consecutive digits into one
  5. Remove all zeros from string
  6. 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.

../../_images/20210207_211952.png

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:

  1. Search for postings with to and be
  2. For each document, check positions to verify to be exists
  3. Search for posting with to be and or
  4. For each document, check positions to verify to be or exists
  5. 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:

  1. Positional index roughly 2-4x larger than non-positional index
  2. 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
      1. 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

  1. Collection: Fixed, static set of documents
  2. 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.

../../_images/20210122_125839_searchmodel.png

Metrics for a good retrieval system:

  1. Precision: Fraction of retrieved documents relevant to user’s unordered
  2. Recall: Fraction of relevant documents in collection that are retrieved
  3. 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:

../../_images/20210122_131133.png

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.

../../_images/20210207_211952.png

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:

../../_images/20210122_135717.png

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,

\[\begin{split}P(\text{Lady Gaga}|\text{`I don't want'}) &= \prod_n P(w_n) \\ &= P(\text{`I'}) \times P(\text{`don't'}) \times P(\text{`want'}) \\ &= .15 \times .05 \times .15\end{split}\]

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.

e.g. paint my love

Unigram:
P(paint) * P(my) * P(love)

Bigram:
P(paint my) * P(my love) # not true bigram
P(paint) * P(my | paint) * P(love | my)

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.