Recommendation System Fundamentals

This are summaries from Andrew N.G’s course on machine learning.

Problem formulation of recommendation system

  • For this post we will use movie recommendation as example
  • We want to recommend movies to user
  • We will have ratings for some (user, movie) pair and would want to predict ratings for other pair
    • Then for a given user we will recommend movies sorted by highest prediction ratings
  • Two kinds of recommendation system
    • Content based
    • Collaborative filtering
  • Content based recommendation
    • Each movie has some features
    • Train regression model for each user to predict ratings based on movie’s features

Collaborative Filtering

  • We need to know two things
    • Feature values for each movie
    • Weight parameter for each user
  • If we know one, we can calculate other
    • We will of-course consider (customer, movie) ratings
    • We have partially filled matrix as training set.
  • Can we do a joint optimisation for both ? That’s the idea behind collaborative filtering.
  • Why it is called collaborative filtering ?
    • Users are collaborating with each other to generate predictions for each other.

  • Notes of collaborative filtering equations
    • Both summations are equal.
    • x0 = 1 is not needed. x0 is constant term in linear regression
      • If model thinks it needs a feature which is constant it will create this on its own.

Collaborative filtering is essentially a matrix factorisation. We can construct matrix for movie and user based on vectors x and theta in above formulation.

  • Low rank matrix factorisation
    • Let number of user’s be nu
      • Number of movies nm
      • Number of movie feature k
    • User matrix dimension -> nu x k
      • For each user we have vector representing feature weights
    • Movie matrix dimension -> nm x k
      • For each movie we have feature value
    • Original matrix dimension -> nu x nm
    • We have factorised matrix into low rank k <= min(nu, nm)
    • It is very popular mathematical technique to discover latent structure with sparse data. [1]
  • Further application
    • Showing related item is different problem than recommendation
    • With collaborative filtering we are obtaining feature vectors for each movie/item
    • We can apply nearest neighbour on top of it

Cold start Problem

  • Mean normalisation helps combating that
  • In most ML algorithm we normalise feature (column)
  • Here you would like to normalise row from product perspective. Mathematically you can do both.
  • Example below
    • 5th user has not rated any movie (blue column in first matrix)
    • Regularised objective will make theta 0 for 5th user, which in turn produce 0 rating while making prediction
    • Mean normalisation transform Input matrix as shown below
    • During prediction time we add mean value for that movie
      • Theta will still be 0 for 5th user from matrix factorisation
      • After multiplying with 0 we are adding mean value to it

Reference

[1] https://arxiv.org/pdf/1507.00333.pdf

[Paper] Semantic Product Search

  • Paper is related to search systems for e-commerce.
  • Shortcoming of BM-25
    • lack of understanding of hypernyms, synonyms, antonyms
      • hypernym – general/broad word
      • Color is hypernym for red
      • Examples
        • Red dress and burgundy dress
        • sneakers and running shoes
    • Morphological variants (woman vs women)
      • Stemming and lemmatization is typical solution
      • Requires numerous hand-crafted rules
        • Converts reading glasses to reading glass
    • Sensitivity to spelling error
      • Typically solved by spell correction algorithms

Architecture

  • Sharing embedding layer in siamese network work well, capturing local word level matching even before training this network.
  • Average pooling
    • Comparing to LSTM performance of average pooling reduced by just 0.5 %
    • Evaluation metric were MAP and Recall@100
    • It helped computationally
    • Unlike web search query and items titles have smaller length
    • Query also does not have stop words
  • Batch Normalisation
    • Length of items are generally longer than query
    • They had observed difference in magnitude after avg pooling of query and item
    • I have seen people using FC layer instead to have separate parameters

Loss Function

  • They first tried with 2 part hinge loss
  • Analysing the overlap items they found that they were clicked but not purchased.
    • They note that from matching standpoint these products are okay to show to customer
  • So they introduced third term and decided it’s threshold to be 0
  • EmpIrical values used episolon (+) = 0.9, episilon (-) = 0.2
  • My view on this
    • For the products that has clicks but not orders, new loss tries to keep it below 0.55
    • 2 part hinge loss was for purchased vs random items
    • Some of those random items had got clicks
    • For positive items when we get similarity above 0.9 it should contribute 0 to loss
    • For negative items if we get similarity below 0.2 it should contribute 0 to loss
    • For neutral items if we get similarity below 0.55 it should contribute 0 to loss
  • y_hat is cosine similarity
    • Based on which loss is calculated
    • Instead of passing cosine similarity to sigmoid they are passing it through hinge function.

Tokenization Methods

  • Word unigram
  • word n-gram
    • To preserve information about word ordering
    • They preferred word n-gram over LSTM or CNN
  • Character trigram
    • Robust typos (iphone & iphonr)
    • Compound words (amazontv & firetvstick)
    • Item parts and sizes
      • Tires have different sizes
      • TVs have different model
  • Handling unseen words
    • Common NLP techniques
      • Mask the input
      • use same embedding for all unseen words
    • What they choose
      • Keep more embedding space for unseen words
      • Hash them to get the bucket
    • Enough space is allocated for frequent words and they are not hashed
      • 10k or 100k of n-grams are kept
  • Combining tokenization
    • One approach
      • Separate embedding for unigram, biagram and character trigrams
      • Compute. weighted sum of cosine similarity individually
    • Their approach
      • Consider them as bag or words

Data

  • Time range
    • Training data – 11 month
    • Eval data – 1 month
  • Trick of aggregating count as weight
    • Weight while computing the loss, simple multiplication ( I had done that in synonyms as well )
    • 54 billion query product training pairs
    • Reduced to 650 million
  • Ratio
    • 1 purchased
    • 6 impressed
    • 7 random
    • They plan for both matching and ranking
    • Matching -> Differentiate between (purchased + impressed) from random
    • Ranking -> Differentiate between purchased and impressed
  • Query Preprocessing
    • Changes queries to list of token IDs
    • array length = 99 % tile of query token length
    • Smaller tokens are padded to right
  • Item preprocessing
    • One approach
      • Embed every attribute independently and concat
    • Their approach
      • Ordered Bag of words for title and attributes
      • Issue was variability in attributes and lack of structured data across items

Model Evaluations

Evaluation Metrics

  • Matching
    • Recall@100 and MAP
      • Used for tuning model hyper parameter as well
    • 20k queries and sub-corpus for those queries
      • Around 1M items
      • Ordered + Impressed + Random
  • Ranking
    • NDCG and MRR
    • Purchased + Impressed

Evaluation Results

  • Table 1
    • L2 variant of hinge loss outperforms L1
      • They hypothesise that L2 is more robust to outliers
    • 3 part hinge loss outperforms 2 part in matching but not in ranking
      • Introduction of 3rd part forced purchased and random to be more separated
  • Table 2
    • LSTM, GRU vs avg Pooling for aggregation
      • Comparison is made for various losses
      • Average pooling is performing similar or slightly better
        • Definitely reduces computation time
      • Since query and product title are relatively short this works well
      • Recurrent methods are expressive but introduces specialisation between query and title
        • Some may argue it is a good thing
        • They argue that it might not capture local word level mapping
  • Table 3
    • Compares different tokenization methods
    • Vocab sizes in embedding space
      • 125k – unigram
      • 25k – bigram
      • 64k – character trigram
      • 500k – Out of vocabulary (OOV) bins
    • Advantage of adding bigrams
      • Example – Chocolate milk vs milk chocolate
    • Advantage of character trigrams
      • Robustness to spelling error
    • OOV adds additional parameters
      • case 1 : 500k unigrams
      • case 2 : 125k unigrams and 375k OOV
      • case 2 performs better
  • Table 4
    • Batch vs layer vs no normalisation
    • query sorted data vs shuffled data
    • Optimum combination was using batch normalisation with shuffled data
    • Query sorted data did not have much effect on layer normalisation but was on batch normalisation
      • Batch estimates for mean and variant would be biased for batch normalisation
  • Table 5

Online evaluations

  • Three categories
    • toys and games, kitchen and pets
  • Conversion rate, revenue and other KPI increased with statistical significance
  • Challenges
    • Precision was decreased
    • To mitigate they added guardrails using some heuristic and ranking models to filter non relevant items
    • Not that recall@100 was metric for matching task and not precision.

Training Acceleration

  • Increasing query product pairs from 200 million to 1.2 billion had improved matching metric by 10 %
  • Data parallel training
    • Idea
      • Split data
      • Same model on multiple GPUs
      • Take the average of gradient in the end
    • Cons for this architecture
      • Limits embedding metric
        • It has to fit on single GPU
      • Data parallel approach has high communication overhead
        • We need to weight till forward pass from each GPU is available
  • Model parallel training
    • Pros in this architecture
      • Simplicity of average pooling
      • Siamese has some parallelism by default
    • How they implemented
      • Embedding metric is split across GPUs, across embedding dimension
        • Hence we need to concat to get final embedding vector for each token
          • Concatenation requires O(2k) communication of floating point numbers
        • Partial token embeddings are averaged at each GPUs
      • Full dataset is sent to all GPUs
  • In the result section they have told that embedding dimension was 256
  • Explaining above image
    • For low embedding dimension time-to-train increases with number of GPUs but for high embedding dimension time-to-train decreases with number of GPUs
    • Dotted line
      • Following two should have same training time
        • 2048 embedding with 1 GPU
        • 1024 embedding with 2 GPU
      • Doted line is for the ration of embedding_size/GPU
      • With ideal scaling it would be horizontal

Exampels

Nearest Neighbour Search

 

This post is a lecture summary of a course by the University of Washington available on Coursera: Machine Learning: Clustering and Retrieval.

Problem: Document Retrieval

Given a document, we want to search for similar documents in a corpus.

Representation: How to Represent Documents as Vectors?

  • Bag of Words: Count the frequency of each word in the vocabulary.
  • TF-IDF: Calculate the IDF (inverse document frequency) of each word in the vocabulary. Weight word frequency (TF) by its IDF in a given document.
    • TF: Same as bag of words.
    • IDF: Higher for rare words, calculated as log(D_total / (1 + D_word)).

Distance Metrics

There are different distance metrics used to measure similarity or dissimilarity between vectors. Let’s explore some commonly used distance metrics:

Euclidean Distance:

  • Euclidean distance between two vectors x and y can be calculated using the vectorized form: sqrt((x-y).T.(x-y)).
  • It is beneficial to normalize features because features can have different units and varying ranges.
  • Normalization can be achieved by dividing either by the range or by the variance of the features.

Scaled Euclidean Distance:

  • Scaled Euclidean distance allows for weighting different dimensions differently based on their importance.
  • For example, in text analysis, we may want to give more weight to the title/abstract than the body of an article.
  • This can be achieved by summing up the word vectors of the article and title and using a diagonal matrix A that contains weights for each feature.
  • The vectorized form for scaled Euclidean distance is: sqrt((x-y).T.A.(x-y)).

Cosine Similarity:

  • Cosine similarity measures the cosine of the angle between two vectors.
  • Similarity = x.dot(y).
  • Distance = 1 – similarity.
  • Cosine similarity is not a proper “distance” metric because it does not satisfy the triangular property (|ab| + |bc| > |ac|).
  • Cosine similarity is commonly used in Natural Language Processing (NLP) tasks due to its computational efficiency for sparse features.
  • Feature vectors in NLP tend to be sparse.
  • The range of similarity values is generally between -1 and 1. However, when features are non-negative, the range becomes 0 to 1, which is the case with TF-IDF.
  • Normalization can be performed instead of using the inner product: Similarity = x.dot(y) / (|x||y|).
  • Normalization avoids doubling the length of documents by copying.
  • One side effect of normalization is that long documents and tweets may appear similar, which is undesired when suggesting tweets to someone reading a document.
  • To address this, an alternative approach is to cap the maximum word count that can appear in a vector.

Cosine vs Euclidean:

  • The choice between cosine and Euclidean distance depends on the use case.
  • Cosine distance is more suitable for text features where the magnitude of the vector is not as important as the orientation.
  • Euclidean distance is a better choice for count features, such as measuring how many times a document was read.
  • For mixed feature types, both cosine and Euclidean distances can be computed (possibly with a subset of relevant features) and combined using appropriate weights, considering the trade-offs and requirements of the specific problem.

 

Brute Force

  • Calculate distance to each document in corpus
  • Suppose there are N documents in corpus
  • Complexity  would be O(N) for 1-NN
  • It will be O(N log k) for k-NN
    • Using priority queue
  • It is computationally inefficient when we N is large and we need to query often

KD-Trees

KD-Trees are used to divide the space into hierarchical regions via a tree structure. Here’s how it works:

  • At each node, we store the smallest bounding box that contains all the data points in that region.
  • While querying (for 1 nearest neighbor, which can be extended for k nearest neighbors):
    • First, we find the leaf node where the query point belongs.
    • Then, we find the nearest neighbor within that node.
    • We keep moving up in the tree.
    • If the distance between the query point and the bounding box is greater than the distance found so far, we skip that region and move up the tree.
    • If it is less, we traverse down the tree.
  • To calculate the distance between a point and a rectangle, you can use appropriate distance metrics like Euclidean distance or other suitable measures. It is computationally easy rectangles are axis aligned[1]

Construction of KD-Trees:

Here are the steps involved in constructing KD-Trees:

  • Choose a splitting strategy:
    • Widest dimension: Split based on the dimension with the widest range.
    • Alternating dimension: Split alternately between dimensions.
  • Determine the value to split on (split value):
    • Median: Choose the median value of the points along the splitting dimension.
    • Center point: Compute the center point as the average of the left and right extremes.
  • Stop conditions for splitting:
    • If there are fewer points left than a specified threshold.
    • If the minimum width of the region is achieved.

How to Prune More Aggressively:

To prune more aggressively in KD-Trees, consider the following approach:

  • Suppose the nearest distance found is r.
  • Instead of pruning points that are farther than distance r, prune all points that are farther than (r/a), where a > 1.
  • This allows for more aggressive pruning and can speed up the search process.

Limitations of KD-Trees:

KD-Trees face challenges in high-dimensional spaces. Here are some limitations:

  • In high dimensions, the radius of the search space is generally large.
  • For d dimensions, the radius intersects 2^d hypercubes, resulting in an extensive search space.
  • One possible solution is to prune all points that are farther away than (r/a), where a > 1, to mitigate these issues.

 

LSH – Locality Sensitive Hashing

Locality Sensitive Hashing (LSH) is a technique used to classify data points into various bins and search within a given bin. Here’s how it works:

  • The idea is to group data points into bins based on their proximity and search within the relevant bin(s).
  • If necessary, nearby bins can also be explored to expand the search.
  • To determine nearby bins, multiple random lines (or planes in higher dimensions) are used.
  • Let’s consider a motivating example with points in a 2D plane:
    • A single random line passing through the origin is chosen.
    • Points that are closer to each other will mostly fall into the same bin.
  • However, using just one line can lead to more data points in a single bin, increasing query time.
  • The solution is to use multiple random lines (or planes) to achieve more efficient classification of neighboring bins.
  • For example, let’s consider three lines, f1, f2, and f3, defined as f(x,y) = 3x + 4y = 0:
    • If f1(p,q) < 0, f2(p,q) > 0, and f3(p,q) > 0 for a given point (p,q), we assign it to the bucket [0,1,1].
  • To facilitate searching within bins, a dictionary can be used, where the key represents the bin (e.g., [0,1,1], [0,1,0]), and the value is a list of all points in that bin.
  • To find nearby bins:
    • Flip one bit to find bins with a single bit difference.
    • For more exploration, flip two bits to find bins with two bits difference.
  • It is possible for the nearest point to be in a different bin.
  • The number of neighboring bins to explore depends on factors such as computational budget or a predefined quality threshold.
  • In some cases, an exact nearest neighbor may not be necessary, and a point with a predefined quality (epsilon) is sufficient.
  • LSH is useful in scenarios like document suggestion, where similar documents need to be retrieved efficiently.
  • LSH can also be extended to high-dimensional spaces by using planes or hyperplanes instead of lines.
  • For assigning bins to data points, dot product calculations are performed, which work well even in large dimensions, especially when the feature vectors are sparse.

References

[1] https://stackoverflow.com/questions/5254838/calculating-distance-between-a-point-and-a-rectangular-box-nearest-point

[2] https://gamedev.stackexchange.com/questions/44483/how-do-i-calculate-distance-between-a-point-and-an-axis-aligned-rectangle

Negative sampling in word2vec

In the precious post we talked about skipgram model.

https://datastoriesweb.wordpress.com/2018/01/31/word2vec-and-skip-gram-model/

 

Now let’s say we have 1000 words and 300 hidden units, we shall have 300,000 wights in both hidden and output unit, which are two many parameters.

Output label during training is one hot vector with 999 zeros and single 1. We randomly select 5 zeros and update weight for six words only. (5 zeros and single 1). The more frequent word is the highr the probability of it getting selected. Google paper has mentioned some emperical formula for this. This is know as negative sampling.

Above was for output layer. In hidden layer weights are updated only for input words. (Irrespective if it is negative sampling or not)

 

Reference:

http://mccormickml.com/2017/01/11/word2vec-tutorial-part-2-negative-sampling/

 

 

Word2Vec and skip gram model

Skip gram model

  • Weights of hidden layer serves as word vectors
  • There is just one hidden layer and one output layer(softmax)
  • Hidden layer does not have any activation
  • As input is one-hot vector, output is also one-hot vector
    • output of hidden layer would be corresponding word vector
  • In the below diagram:
    • Size of input (1 x 10000)
    • Size of output (1 x 10000)
    • Weight of hidden layer (10000 x 300)
    • Weight of output layer (300 x 10000)
    • So too many weight to learn – solution : negative sampling
  • Training pair would be nearby words in predefined window
    • We can imagine how huge can that be
    • It is pair of words both one-hot encoded
    • Sure, we need to know previously size of our vocabulary (which will be dimension of one-hot vector)
  • The paper google release was trained on google news data and used 300 dimension vector, which means 300 neuron in hidden unit. The paper lists this no and size of training words and efficiency.
    • Not there is one more parameter called named window size which was set to 5.
    • It means that 5 words before and after center words are considered as pair for training data.
  • There is no activation function on the hidden layer neurons, but the output neurons use softmax.
word2vec.PNG

Why word2vec

  • Earlier NLP methods used to rely on synonyms/hypernyms which is not totally contextual
    • Earlier case was mainly one hot encoding of vector
  • “proficient” is synonym of good only in some context
  • New words are getting added everyday
  • All words are one-hot encoded
    • Somewhat similar word might be orthagonal
    • Size of vector become too large

Role of TF-IDF

  • It is a scoring mechanism
  • Instead of average vectors of all the words in document we can have weighted average by TF-IDF score

There are two more things:

  • Continuous Bag Of Words
  • Negative sampling

CBOW

  • It also takes average of context words
    • One argument in the favour that averaging is valid
  • Both CBOW and skip gram does not add non-linearity in hidden layer
    • Output layer uses softmax
    • Idea is that word-embedding is used to predict target word.

From Matmul to Embedding tables

When you train a Word2Vec model, you are fundamentally initializing and training embedding tables using the Word2Vec objective function.

How Word2Vec Uses Embedding Tables

In standard Word2Vec (specifically the Skip-gram architecture), the model maintains two separate embedding tablesfor the entire vocabulary:

                  [ Vocabulary Size (V) ]
                    /                 \
                   /                   \
  1. Target Embedding Table         2. Context Embedding Table
  (Shape: V x Dimension)            (Shape: V x Dimension)
  1. Target Table ($\mathbf{W}$): Used when a word acts as the “center” or target word.
  2. Context Table ($\mathbf{W}’$): Used when a word appears in the surrounding window of a target word.

Step-by-Step Mechanics of Training

When the model processes a sentence chunk like “the dog barks”, where dog is the target word and barks is the context word:

  1. The Lookup: The unique integer ID for “dog” is used to look up a vector from the Target Table. The ID for “barks” looks up a vector from the Context Table.
  2. The Comparison: The model takes the dot product of these two vectors to measure how “close” they are in vector space.
  3. The Loss & Update:
    • If using Negative Sampling, the model also pulls random “noise” words from the Context Table (like “banana”).
    • It calculates the loss (maximizing the dot product for “barks”, minimizing it for “banana”).
    • Backpropagation updates the specific rows in both embedding tables for those words.

The Final Output

Once training is complete, the Context Table is discarded, and the Target Embedding Table becomes your final dictionary of word vectors.

Original paper

We are revving activation and using matul to calculate dot products

On the hidden layer. The paper’s architecture is:

one-hot (V) → W_in (V×d) → h (d) → W_out (d×V) → scores (V) → loss

That middle h is drawn as a layer, so it looks like an MLP with one hidden layer. But there’s no activation on it. h is literally the row of W_in you just looked up — no ReLU, no tanh, nothing. Mikolov’s phrase for it in the paper is that the nonlinear hidden layer is removed; that’s the stated reason the model trains fast enough to run on billions of words.

PyTorch Implementation

class SkipGramNS(nn.Module):
def __init__(self, V, d):
super().__init__()
self.emb_in = nn.Embedding(V, d) # center vectors (the ones you keep)
self.emb_out = nn.Embedding(V, d) # context vectors
def forward(self, center, context, neg):
# center: (B,) context: (B,) neg: (B, K)
v = self.emb_in(center) # (B, d)
u_pos = self.emb_out(context) # (B, d)
u_neg = self.emb_out(neg) # (B, K, d)
pos_score = (v * u_pos).sum(-1) # (B,)
neg_score = torch.bmm(u_neg, v.unsqueeze(-1)).squeeze(-1) # (B, K)
return pos_score, neg_score
# loss form 1 - how the paper writes it
loss = -(F.logsigmoid(pos_score) + F.logsigmoid(-neg_score).sum(1)).mean()
# form 2 - what it actually is
loss = F.binary_cross_entropy_with_logits(pos_score, torch.ones_like(pos_score)) \
+ F.binary_cross_entropy_with_logits(neg_score, torch.zeros_like(neg_score))

Softmax vs BCE

1. Softmax makes words compete; contexts shouldn’t compete.

A center word like cat has many valid contexts: sat, the, chased, animal. Softmax normalizes across all of them, so probability is a fixed budget — pushing sat up necessarily pushes chased down, even though both are correct. Binary cross-entropy scores each pair on its own: “is this pair real, yes or no.” Every genuine context can score high at the same time. The problem is really multi-label, and BCE treats it that way.

2. Sampled softmax needs a correction term; negative sampling doesn’t.

To make sampled softmax approximate the true softmax, you have to subtract log(k · q(w)) from each logit, where q(w) is the probability you sampled that word. Without it you’re biased — frequent words get sampled more often and get systematically over-penalized. That means you must track your sampling distribution and plumb it into the loss. Negative sampling just drops that term and accepts that it’s a different objective.

3. Word2vec never needs the probability.

Sampled softmax exists to give you a usable estimate of p(context | center). Word2vec throws the scores away and keeps the embedding table. If you don’t need a calibrated distribution, you don’t need the machinery that produces one.

The honest caveat: this ordering flips in modern retrieval. Two-tower recommender systems mostly use sampled softmax with the logQ correction rather than BCE, because ranking quality against a large corpus is exactly the case where the normalization helps and the popularity bias hurts. So “negative sampling is better” is a word2vec-specific claim, not a general one.

References :

http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/

http://cs224d.stanford.edu/

http://web.stanford.edu/class/cs224n/syllabus.html

http://nadbordrozd.github.io/blog/2016/05/20/text-classification-with-word2vec/