Does not have second order derivative in denominator
Using 1 to solve for minima problem
Minima problem is same as finding root of derivative
Has second order derivative in denominator
There is a nice derivation starting from taylor series [3]
Newton’s Method
Based on Taylor series expansion
Advantages
Convergence is rapid in general, quadratic near optimal point
Insensitive to no of variables
Performance does not depend on choice of parameter
Gradient method depends on learning rate
Disadvantages
Cost of computing and storing Hessian
Cost of computing single newton step
You need double derivative (Example in note is a simple root finding problem)
Gradient Descent
Very popular method and does not need any write up
Exhibits approximately linear convergence
Advantage
Very simple to implement
Disadvantage
Convergence rate depends on number of the Hessian
Very slow when for large no of variables (say 1000 or more)
Performance depends on choice of parameters like learning rate
Gradient Descent vs Netwon’s Method
Edit 1 : I believe term step is more suitable here. Gradient step and Newton step. Method is more suitable for interior point methods, active set methods, cutting plane methods and proximal methods.
Newton’s method for finding roots:
In optimization we are essentially finding roots of derivative.
We are approximating function using Taylor series. We are finding minimum of this approximated function. This root will be our new guess. This perspective is used in derivation.
Andrew N.G Lecture [2]
Gradient Descent
Newton
Simpler
Slightly more complex (Requires computing and inverting hessian)
Needs choice of learning rate alpha
No parameters (third point in image is optional )
Needs more iteration
Needs fewer iteration
Each iteration is cheaper O(n) where n is no of features
Each iteration is costly. Hessian is (n+1) * (n+1). Inverting matrix is roughly O(n^3)
Use when no of features are less (n<1000)
Use when (n > 10,000)
Gradient can only give you direction. If you want to know next point (or step size), second order derivative (hessian) is must.
Golden Section Search
Typically applicable for one dimension only
We used it to calculate mobile/tablet adjustments
As a good practice we had avoided recursion and took at max 20 iteration breaking loop with some criterion
Applicable for strictly unimodal function
Three points that maintain golden ratio (phi)
Following two problems are different :
Searching in rotated sorted array
Finding a max on uni-modal function
Formal has a property that left one end will be smaller than other, which later does not have
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
K-mean is probably most popular algorithm and most taught algorithms in academia. However it has got many limitation and listing some of them here:
You need to specify value of k
Can cluster non-clustered data
Sensitive to scale
Even on perfect data sets, it can get stuck in a local minimum
Means are continuous
Hidden assumption: SSE is worth minimizing
K-means serves more as quantification
In Hierarchical clustering you don’t need to specify values of k, you can sample any level from the tree it build either by top down or bottom up approach. Such a tree is called Dendrogram.
When averaged across all possible situations, every algorithm performs equally well 🙂
Imagine you have two different classification problems: one involves identifying fraudulent credit card transactions, and the other involves diagnosing medical conditions based on patient symptoms. These two problems have distinct characteristics and requirements.
Now, let’s say you have Algorithm A, which performs exceptionally well on the credit card fraud detection problem. It has been extensively optimized and fine-tuned for this specific problem domain, resulting in high accuracy and low false positive rates.
On the other hand, you have Algorithm B, which excels in diagnosing medical conditions. It has been trained on a vast dataset of patient records and has been shown to provide accurate diagnoses with minimal errors.
If you were to switch the algorithms and apply Algorithm A to the medical diagnosis problem and Algorithm B to the credit card fraud detection problem, you may encounter subpar performance. Algorithm A, which was designed specifically for fraud detection, might struggle to correctly identify medical conditions based on symptoms. Similarly, Algorithm B, which was trained on medical data, may not be effective at detecting credit card fraud.
This example illustrates the essence of the No Free Lunch theorem. While Algorithm A and Algorithm B excel in their respective problem domains, they do not have universal superiority. Each algorithm is designed and optimized for a specific problem, taking into account its unique characteristics and requirements.
The NFL theorem reminds us that when approaching a new problem, it is essential to carefully analyze its specific characteristics, data distribution, and requirements. It is necessary to evaluate and select an algorithm or approach that aligns well with those specific factors, rather than assuming that a single algorithm can provide optimal performance across all problem domains.
In the context of the No Free Lunch (NFL) theorem, an algorithm refers to a specific computational method or procedure used to solve a problem or perform a task. Algorithms can be mathematical, statistical, heuristic, or machine learning-based, among others. Example being Logistic regression, CNN, RNN etc.
In summary, the No Free Lunch theorem emphasizes the importance of considering problem-specific factors and carefully selecting algorithms or approaches that suit the unique requirements of each problem. Different problems may require different algorithms, and there is no universally superior algorithm that can perform optimally for all possible problems.
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)
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.
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)
Target Table ($\mathbf{W}$): Used when a word acts as the “center” or target word.
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:
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.
The Comparison: The model takes the dot product of these two vectors to measure how “close” they are in vector space.
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)
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.
Even if you look at gradient descent below, error is multiplied by previous value. When input is higher it’s contribution to error is higher and will needs to change more.
importnumpyasnp
# 1. Activation and Loss Functions
defrelu(x):
returnnp.maximum(0,x)
defrelu_derivative(x):
return(x>0).astype(float)
defsoftmax_and_cross_entropy_loss(logits,y_true):
"""
Computes stable softmax and categorical cross-entropy loss together.