Stationarity Conditions for MA(q) and AR(p) Processes

Sequence and Series

Convergent Sequence

1/2, 2/3, 3/4, . . . , n/(n+1)

Divergent Sequence

3, 9, 27, . . . . , 3^n

Series => Partial Sum of sequence

Convergent Series => if sum converges

Convergence Test

  • Integral Test
  • Comparison Test
  • Limit comparison test
  • Alternating Series Test
  • Ratio test
  • Root test
Geometric Series

  • a, ar, ar^2, . . . , ar^n
  • Convergent if r < 1
Representing function as (geometric) series

seriesRepresntation

Backward shift operator

  • B^kX(t) = X(t – k)

backOp

Invertibility

  • Two models have same ACF
  • Given ACF how to find out the model
  • We will go for model that is invertible
  • We can invert MA(1) into AR(∞)
  • Inverting is basically act of expanding function in geometric series
  • It is possible when growth r<1
  • Out of two models only one satisfies this condition
  • We will select that model given ACF

Conditions for Invertibility[MA(q)] and Stationarity [AR(p)]

dual

How to check if series is both invertible and stationary

  • Check AR(p) polynomial for stationarity
  • Check MA(q) polynomial for invertibility
  • Both should hold

Reference

https://www.coursera.org/learn/practical-time-series-analysis/exam/ITocA/series-backward-shift-operator-invertibility-and-duality

 

[Time Series] Correlation and Stationarity

Co-variance vs Correlation

  • Correlation is co-variance divided by standard deviation of both variables
  • Hence it is independent of units and is always between -1 and 1, which makes comparison easier
  • Formula on the right is time series specific
    • It is auto correlation coefficient at lag k
    • It is define as ration of auto-correlation at lag k divide by auto-correlation at lag 0
    • This values are plotted on correlogram  (See one for MA(2) process below)

acf

 

Stationary Time Series

  • No systematic change in mean (No trend)
  • No systematic change in Variance
  • No periodic variation (Seasonality)

If time series is not stationary we apply several transformation to make it stationary.

For example applying difference operator to random walk makes it stationary.

 

 

Random Walk

  • Previous value of noise
  • If first value is zero then current value is summation of all the noises so far
  • X(t) = X(t-1) + Z(t)
  • Z(t) = Normal (mu, sigma2)
  • if X(0) = 0 then X(t) = sum(Z(k)) k form 0 to t
  • Expectation[X(t)] = t*mu   – –  Changes with time
  • Variance[X(t)] = t*sigma2   – – Changes with time
  • Not a stationary process
  • let Y(t) = X(t) – X(t-1) = Z(t)  – – Y(t) is a stationary process

 

Example of Stationary Process

Moving average and Auto regressive processes described here can be stationary under conditions described here.

 

 

References

 

Further reading

 

 

 

 

Iterative Method for Unconstrained Optimization

There are two things

  1. Newton method for finding roots
    1. Does not have second order derivative in denominator
  2. Using 1 to solve for minima problem
    1. Minima problem is same as finding root of derivative  
    2. Has second order derivative in denominator
  3. There is a nice derivation starting from taylor series [3]

Newton’s Method

newton
  • 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:

3

In optimization we are essentially finding roots of derivative.

1
2

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.

4

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 property is used in binary search
  • What is special about golden ration ?
from math import sqrt
phi = (1 + sqrt(5))/2
resphi = 2 – phi
# a and b are the current bounds; the minimum is between them.
# c is the center pointer pushed slightly left towards a
def goldenSectionSearch(f, a, c, b, absolutePrecision):
if abs(a – b) < absolutePrecision:
return (a + b)/2
# Create a new possible center, in the area between c and b, pushed against c
d = c + resphi*(b – c)
if f(d) < f(c):
return goldenSectionSearch(f, c, d, b, absolutePrecision)
else:
return goldenSectionSearch(f, d, c, a, absolutePrecision)
f = lambda x: x**2
def test_search():
assert abs(goldenSectionSearch(f, -1, (-1 + resphi*2), 1, 1e-10)) < 1e-10
print "OK!"
if __name__ == '__main__':
test_search()

Reference

[0] http://www.ece.mcmaster.ca/~xwu/part4.pdf

*[1] https://www.youtube.com/watch?v=42zJ5xrdOqo

*[2] https://www.youtube.com/watch?v=iwO0JPt59YQ

[3] https://suzyahyah.github.io/calculus/optimization/2018/04/06/Taylor-Series-Newtons-Method.html

Time series week 1

  • Plotting in R
  • Linear regression properly fitted or not
    • Residue are important thing to observed
    • Q-Q plots for normality test
    • Residues over time
      • Zoomed in residues over time
  • Hypothesis test
    • One, two sided t test
    • Confidence interval
      • Where we think mean lies
      • If it dose not contain 0 we tend to reject null hypothesis (Very broad statement, but I think you got the concept)
  • Correlation function
    • Which quarter data false

 

Ref : https://www.coursera.org/learn/practical-time-series-analysis/home/welcome

 

 

 

On Clustering

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.

Scikit also supports variety of clustering algorithms including DBSCAN and lists which one suits when. http://scikit-learn.org/stable/modules/clustering.html

 

References:

https://stats.stackexchange.com/questions/133656/how-to-understand-the-drawbacks-of-k-means

 

No Free Lunch (NFL)

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.

http://www.no-free-lunch.org/

http://scholar.google.com/scholar?q=”no+free+lunch”+Wolpert&#8221;

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/

Quadratic Programming CVXOPT

This is taken from https://courses.csail.mit.edu/6.867/wiki/images/a/a7/Qp-cvxopt.pdf

General algorithms for QP (from wikipedia)

 

Standard form

qp1

Converting to standard form

qp2

Python Code



Loading

Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

view raw

QP_CVXOPT.ipynb

hosted with ❤ by GitHub

 

 

Derivation of backpropagation

Quick Summary:

 

 

back_prop

 

Detailed Derivation:

 

 

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.

gd

 

import numpy as np
# 1. Activation and Loss Functions
def relu(x):
return np.maximum(0, x)
def relu_derivative(x):
return (x > 0).astype(float)
def softmax_and_cross_entropy_loss(logits, y_true):
"""
Computes stable softmax and categorical cross-entropy loss together.
logits: (batch_size, num_classes)
y_true: (batch_size, num_classes) - One-hot encoded labels
"""
# Log-Sum-Exp trick for numerical stability
shifted_logits = logits - np.max(logits, axis=1, keepdims=True)
exps = np.exp(shifted_logits)
softmax_probs = exps / np.sum(exps, axis=1, keepdims=True)
# Compute Cross-Entropy Loss
batch_size = logits.shape[0]
# Add a tiny epsilon to prevent log(0)
loss = -np.sum(y_true * np.log(softmax_probs + 1e-15)) / batch_size
# The gradient of loss with respect to logits simplifies beautifully to: (probs - target)
d_logits = (softmax_probs - y_true) / batch_size
return loss, d_logits
# 2. Network Initialization
np.random.seed(42) # For reproducible results
input_dim = 3 # e.g., 3 features
hidden_dim = 4 # 4 neurons in the hidden layer
output_dim = 2 # 2 classes (Binary/Multiclass)
# Xavier/Glorot Initialization for weights
W1 = np.random.randn(input_dim, hidden_dim) * np.sqrt(2.0 / input_dim)
b1 = np.zeros((1, hidden_dim))
W2 = np.random.randn(hidden_dim, output_dim) * np.sqrt(2.0 / hidden_dim)
b2 = np.zeros((1, output_dim))
# Dummy Training Data (Batch of 2 samples)
X = np.array([[0.5, -0.2, 0.1],
[0.1, 0.8, -0.5]])
# One-hot encoded true targets
Y = np.array([[1.0, 0.0], # Class 0 is correct
[0.0, 1.0]]) # Class 1 is correct
learning_rate = 0.1
# 3. Training Iteration (Forward & Backward Pass)
for epoch in range(3):
# --- FORWARD PASS ---
# Hidden Layer
z1 = np.dot(X, W1) + b1
a1 = relu(z1)
# Output Layer (Generates Raw Logits)
logits = np.dot(a1, W2) + b2
# Compute Loss and the gradient at the final layer
loss, d_logits = softmax_and_cross_entropy_loss(logits, Y)
# --- BACKWARD PASS (Backpropagation) ---
# Gradients for Output Layer weights and biases
dW2 = np.dot(a1.T, d_logits)
db2 = np.sum(d_logits, axis=0, keepdims=True)
# Gradient flowing back into the hidden layer
da1 = np.dot(d_logits, W2.T)
dz1 = da1 * relu_derivative(z1) # Backprop through ReLU
# Gradients for Hidden Layer weights and biases
dW1 = np.dot(X.T, dz1)
db1 = np.sum(dz1, axis=0, keepdims=True)
# --- GRADIENT DESCENT ---
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
W1 -= learning_rate * dW1
b1 -= learning_rate * db1
print(f"Epoch {epoch+1} - Loss: {loss:.4f} | Raw Logits Sample 1: {logits[0]}")