NLP Study Notes (2): Neural Networks and Word Representations
Wednesday, June 3, 2026 / , ,
Before reading this article, you may want to read the following articles first to better understand the context.
AI TranslationSimplified ChineseEnglish
Summary:
My NLP study notes from COMP90042 at the University of Melbourne: feedforward networks, RNNs, LSTMs and Transformers, along with TF-IDF, PMI, Word2Vec and word-vector evaluation.
These are my notes from taking COMP90042 NLP at the University of Melbourne; this part covers neural networks and word representations: from FFNNs, RNNs and LSTMs to Transformers, then count-based word vectors, Word2Vec and evaluation methods.
1. Feedforward Neural Network (FFNN)
1.1 Fundamentals of Deep Learning
Feed-forward NN
A single neuron: a function
h = f(x)x, compute a scalarhwto scale the input and add the biasbwandbare the model's parametersh = \tanh\!\left(\sum_j w_j x_j + b\right)Activation function
Formula
Characteristics
Sigmoid
\sigma(z)=\dfrac{1}{1+e^{-z}}Output in (0,1), can be treated as a probability; saturation at both ends causes vanishing gradients
Tanh
\tanh(z)=\dfrac{e^z-e^{-z}}{e^z+e^{-z}}Output in (-1,1), zero-centered, easier to train than sigmoid
ReLU
\max(0, z)Fast to compute, mitigates vanishing gradients; the negative half-axis “dies”
1.2 Output Layer
Binary classification
P(y=1\mid x)\in(0,1).Multi-class classification
\text{softmax}(z_i) = \frac{\exp(z_i)}{\sum_j \exp(z_j)}1.3 Training Methods
(a) Loss function
L:L = \prod_{i=1}^{m} P(y_i \mid x_i)-\log L(negative log-likelihood / cross-entropy) to optimize the parameters:-\log L = -\sum_{i} \log P(y_i \mid x_i)(b) Gradient descent
\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}(c) Regularisation
Method
Formula/approach
Effect
L1-norm
\lambda\sum\vert \theta\vertSparse weights (feature selection)
L2-norm
\lambda\sum\theta^2Constrains weight magnitude; under ordinary SGD it corresponds to weight decay
Dropout
Randomly set some neuron outputs to 0 during training
Reduces neuron co-adaptation; can be understood as approximately combining many subnetworks that share parameters
(d) Dropout
1.4 Application 1: Topic Classification
Task: given a document, classify it into a predefined set of topics (economy / politics / sport…). Input: bag-of-words.
Training
Wandb\vec{x} = [0,2,3,0] \;\rightarrow\; \vec{h} = \tanh(W_2\vec{x} + \vec{b}_1) \;\rightarrow\; \vec{y} = \text{softmax}(W_3\vec{h})\vec{y} = [0.1, 0.6, 0.3], corresponding toC_1, C_2, C_3C_1:L = -\log(0.1) \approx 2.303Prediction
\vec{x} = [1,3,5,0]\vec{y} = [0.2, 0.1, 0.7]= C_3(take argmax)Directions for improvement
1.5 Application 2: Word Embedding
W_1is the vector of one word.1.6 Application 3: FFNN Language Model
Predict
P(w_i = \text{grass} \mid w_{i-3}=\text{a},\, w_{i-2}=\text{cow},\, w_{i-1}=\text{eats})Procedure:
W_1)\vec{h} = \tanh(W_2\vec{x} + \vec{b}_1),\vec{y} = \text{softmax}(W_3\vec{h})\vec{y}gives a probability distribution over the entire vocabularyParameter distribution:
W_1(size= d_1 \times \vert V\vert)W_3(size= \vert V\vert \times d_h, whered_his the hidden-layer dimension)1.7 FFNN Language Model vs Count-based N-gram
Dimension
Count-based N-gram
FFNN N-gram
Training cost
Extremely low (only requires counting occurrences)
Relatively high (requires gradient descent)
Sparsity
Severe (unseen n-grams have probability 0)
Mitigated (similar words share parameters, allowing generalization to unseen combinations)
Long context
As context grows longer, parameter/sparsity problems worsen
Can scale smoothly (but still limited by a fixed window)
Word properties
Cannot capture syntactic/semantic similarity between words (film vs movie are treated as two unrelated symbols)
Automatically captures word properties, yielding more robust estimates
2. Recurrent Neural Networks (RNNs)
2.1 Definition
s_i = f(s_{i-1}, x_i), \qquad s_{i+1} = f(s_i, x_{i+1})fis reused at all time steps.2.2 Node
Xhas variable length, but the dimension of each input vectorx_iand that of the state vectors_iare still fixed by the model.Two formulas of a Simple RNN
s_i = \tanh(W_s s_{i-1} + W_x x_i + b)y_i = \text{softmax}(W_y s_i)W_s: state-to-state weights (how memory is passed)W_x: input-to-state weightsW_y: state-to-output weightsb: bias2.3 Network
W_s, W_x, b, W_y), and positions are connected through the state, so the number of parameters does not grow directly with sequence length.2.4 Training
xat a time (one word in an LM);y(because the state is different);L = L(y_1) + L(y_2) + L(y_3) + \dots = \sum_t L(y_t)2.5 Training Example (Language Model)
Sentence: a cow eats grass
x_iis the current word (e.g. eats), first mapped to an embeddings_{i-1}contains information from the previous context (a, cow)y_ipredicts the next word (grass)The network is unrolled over time:
Numerical example (vocabulary {a, cow, eats, grass})
Position
Input
State
sOutput distribution
yTarget
Loss
1
a
s_1[0.40, 0.30, 0.20, 0.10]
cow
-\log(0.30)2
cow
s_2[0.30, 0.20, 0.30, 0.20]
eats
-\log(0.30)3
eats
s_3[0.50, 0.10, 0.20, 0.20]
grass
-\log(0.20)L_{\text{total}} = L_1 + L_2 + L_32.6 Problems with RNNs
Problem
Description
a) Mismatch between training and decoding
During training, teacher forcing is used (feeding the true previous word); at inference, the model is fed its own predictions, causing a distribution mismatch (exposure bias).
b) Error propagation and difficulty locating intermediate errors
Errors propagate and accumulate along time steps, and it is difficult to locate which step went wrong.
c) Tends to generate "blank" or "generic" language
Tends to generate vague, safe high-frequency expressions lacking specific information.
d) Vanishing gradient
Gradients decay exponentially when backpropagated along time, so long-distance dependencies cannot be learned.
2.7 Vanishing Gradient
3. Long Short-Term Memory Network (LSTM)
3.1 Definition and Motivation
Memory is controlled by gates:
3.2 RNN vs LSTM Structure
C_t.3.3 Understanding and Controlling Memory
How to understand memory:
C_tprovides an additive update path through time steps. When the forget gate is close to 1, information and gradients are easier to retain; long-term memory still depends on the gate values and training results.How to control memory: four steps
Step
Role
Forget
Decides how much of the old cell state
C_{t-1}to discard.Input
Decides how much new information to write
Update
Updates the cell state using the results of forget and input
Output
Decides how much to extract from the cell state as the current hidden state
h_t3.4 Three Gates and State Update Formulas
Forget gate
f_t = \sigma\left(W_f\,[h_{t-1}, x_t] + b_f\right)f_tcontrols how much information in the old memory cellC_{t-1}is retained: discard when close to 0, retain when close to 1.Input gate
i_t = \sigma\left(W_i\,[h_{t-1}, x_t] + b_i\right)\tilde{C}_t = \tanh\left(W_C\,[h_{t-1}, x_t] + b_C\right)i_t: controls how much new information is written into the memory cell;\tilde{C}_t: new candidate information (distilled information), e.g. information about boy.Update the cell state
C_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_tC_t→ mitigating vanishing gradients.Output gate
o_t = \sigma\left(W_o\,[h_{t-1}, x_t] + b_o\right)h_t = o_t \odot \tanh(C_t)h_t.3.5 Number of Parameters
Let
\text{Hidden}_{dim}= dimension of memory (also the dimension ofh_t)\text{Input}_{dim}= dimension of word embedding\#\text{params} = 4 \times (\text{Hidden}_{dim} + \text{Input}_{dim}) \times \text{Hidden}_{dim} + 4 \times \text{Hidden}_{dim}W_f, W_i, W_C, W_o, each with the same dimensions (rows, columns).\text{Hidden}_{dim};\text{Hidden}_{dim} + \text{Input}_{dim};4 \times \text{Hidden}_{dim}accounts for the 4 sets of bias constants.Example: Hidden = 256, Input = 300
4 \times (256+300)\times 256 + 4\times256 = 569{,}344 + 1{,}024 = 570{,}3683.6 Applications of RNN / LSTM
Application
Description
Wikipedia Generator
Generates encyclopedic text from a consistently structured training corpus
Code Generator
Generates code (highly structured and easy to evaluate)
Speech recognition
Maps acoustic feature sequences to text
Text Classification
Use the final hidden state or pooling as the document representation
Sequence Labelling
POS, NER (output one label per position)
3.7 Variants
Variant
Key points
Peephole connections
Allow gates to "see" the cell state (
C_{t-1}also participates in gate computation)GRU (Gated Recurrent Unit)
Simplified version: only 2 gates (reset / update), no separate memory cell, fewer parameters, faster training, often comparable to LSTM
Multi-layer LSTM
Stack multiple layers for layer-by-layer abstraction (but in practice it is not easy to stack too deep)
Bidirectional LSTM
Forward + backward LSTMs, concatenating hidden states from both directions → each position has both left and right context (cannot be used for autoregressive generation)
3.8 Pros and Cons
Pros
Cons
4. Transformer
4.1 Definition
4.2 Motivation: From RNN to Attention
4.3 Use Cases
Any task of the form "input text → output text":
Essentially all are "a piece of input text → another piece of output text", which Transformer is very well suited to.
4.4 Self-Attention: Query / Key / Value
Intuitive analogy:
Example: sentence I made her duck, target word her
Role
Content
Query
qThe query vector of the target word her
Key
k/ ValuevContext words (I, made, duck) and the target word's own key/value
Steps
x_iis written as a row vector and multiplied by three projection matricesW_Q, W_K, W_V:q_i = x_i W_Q,\qquad k_i = x_i W_K,\qquad v_i = x_i W_Vqis compared with each word'skusing a dot product to obtain relevance scores;vto obtain the target word's output vectorz;z, arranged by position to form the output of one attention head.Core conclusion: The final representation of the target word = the weighted sum of the value vectors of the context words (including itself), with weights determined by query–key similarity.
4.5 Formulas
Single-query form
\text{SelfAttention}(q, K, V) = \sum_i \frac{\exp(q \cdot k_i)}{\sum_j \exp(q \cdot k_j)}\, v_iMatrix form (stack the
q_i,k_i,v_iby row intoQ,K,V)\text{SelfAttention}(Q, K, V) = \text{softmax}(QK^\top)\,VScaled Dot-Product Attention (used in practice)
\text{SelfAttention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V\sqrt{d_k}?d_kis the dimension of the key vector. The variance of the dot product grows with dimension; when the dimension is large, softmax inputs become too large → an extreme distribution (close to one-hot) → extremely small gradients. Dividing by\sqrt{d_k}scales the scores to stabilize the values (avoiding overly large values/vanishing gradients).4.6 Multi-Head Attention
Motivation: different words in a sentence can be related in multiple ways:
Relation type
Example
Syntactic
subject–verb agreement (noun–verb agreement)
Semantic
synonyms
Discourse
it refers to the earlier the dog
Multi-head attention allows the model to attend to different relations in parallel in different representation subspaces, therefore:
htimes (different heads have their ownW_Q^{(i)}, W_K^{(i)}, W_V^{(i)});z^{(i)}and concatenate them together;W_O, mapping the concatenated result back to the model dimensiond, fusing multi-head information;\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)W_O\text{head}_i = \text{Attention}(QW_Q^{(i)}, KW_K^{(i)}, VW_V^{(i)})4.7 Transformer Block
Taking the original Transformer's Encoder block as an example, besides self-attention it also contains:
Component
Count
Role
Feedforward layer
1×
A position-wise two-layer MLP (first increase dimension, then reduce it), providing nonlinear transformation capability
Residual connection
2×
Adds the input and the sublayer output (
x + f(x)), preserving a direct propagation path for information and gradients, making deep networks easier to trainNormalisation layer (LayerNorm)
2×
Normalizes the hidden features at each position and learns scaling and bias, helping stabilize training
4.8 Stack Them Up
4.9 Positional Information
Problem: without adding position information, self-attention itself cannot distinguish word order. Applying the same permutation to the input only permutes the output accordingly; it does not magically know which word comes first and which comes later. Therefore, additional position representations are needed to distinguish dog bites man from man bites dog.
Learnable Positional Embeddings
X= word embeddings + position embeddings (the two are added);Static Functions (sinusoidal positional encoding)
PE_{(pos, 2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \qquad PE_{(pos, 2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)4.10 Decoder-only Architecture
5. Word Vectors: Count-based Methods
5.1 Overview of Word Vector Embedding
5.2 Documents as Context: Vector Space Model (VSM)
Perspective
Row/column
Meaning
Document perspective
Each row is a document
A document is represented by the words it contains
Word perspective
Each column is a word
A word is represented by the documents in which it appears (the column vector is the word vector)
Word–document matrix example (rows = document id, columns = words)
state
fun
heaven
425
0
1
0
426
3
0
0
427
0
0
0
5.3 TF-IDF
Term Frequency
tf_{t,d}(one may also take\log(1+tf)or normalize).Inverse Document Frequency
idf_w = \log \frac{\vert D\vert }{df_w}\vert D\vert= total number of documentsdf_w= number of documents containing wordw.Combination
\text{TF-IDF} = TF \times IDF\log\frac{1+\vert D\vert }{1+df_w}+1);Example (tf matrix → tf-idf matrix)
tf matrix (rows 425/426/427, columns the/country/hell):
the
country
hell
425
43
5
1
426
24
1
0
427
37
0
3
df500
14
7
Shown here are three document rows from the full corpus; let the total number of documents be
\vert D\vert=500, use base-2 logarithms, and approximate the IDFs of country, hell as 5.2 and 6.2 respectively before multiplying.→ the appears in all 500 documents, so
idf=0; while hell appears in only 7, so its weight is relatively higher.the
country
hell
425
0
26.0
6.2
426
0
5.2
0
427
0
0
18.6
5.4 Dimensionality Reduction
SVD (singular value decomposition)
A = U \Sigma V^\topAis the\vert V\vert \times \vert D\vertword–document matrixU:\vert V\vert \times m, new word matrix (each row is the representation of one word)\Sigma:m \times msingular-value diagonal matrix (in descending order of importance)V^\top:m \times \vert D\vert, the new document matrixm = \text{Rank}(A)When all nonzero singular values are retained, this is an equivalent decomposition; in practice, dimensionality reduction and denoising usually rely on the truncated version below.
Latent Semantic Analysis (LSA)
ksingular values and their corresponding directions, and use the rows ofU_korU_k\Sigma_kas word vectors;kis often 100–300);Complete TF-IDF word-vector pipeline
5.5 Word as Context
5.6 Pointwise Mutual Information (PMI)
\text{PMI}(x, y) = \log_2 \frac{P(x, y)}{P(x)\,P(y)}Meaning: the ratio of the actual co-occurrence probability to "the co-occurrence probability if the two words were independent".
\text{PMI} > 0: co-occurrence is more than chance, positive correlation (related words)\text{PMI} = 0: the co-occurrence probability of this word pair equals the probability under the independence assumption\text{PMI} < 0: co-occurrence is less than chance, negative correlation (complementary/repulsive)Example: compute PMI(heaven, hell)
Co-occurrence matrix (window co-occurrence counts, excerpt)
the
country
hell
Σ
state
1973
10
1
12786
fun
54
2
0
633
heaven
55
1
3
627
Σ
1047519
3817
780
15871304
P(\text{heaven}) = 627 / 15871304P(\text{hell}) = 780 / 15871304P(\text{heaven}, \text{hell}) = 3 / 15871304(if the count for this cell is 3)Substitute back into the formula:
\text{PMI}(\text{heaven},\text{hell})=\log_2\frac{3\times15871304}{627\times780}\approx6.61PMI matrix (excerpt)
the
country
hell
state
1.22
1.78
0.63
fun
0.37
3.79
-inf
heaven
0.41
2.80
6.61
5.7 Three Additional PMI Techniques
Technique
Approach
Reason
Replace
-\inftyor negative values with 0\text{PPMI} = \max(\text{PMI}, 0)Retains co-occurrence relations above the independence assumption and reduces the impact of unreliable negative-association estimates for low-frequency pairs
Normalised PMI (NPMI)
\text{NPMI}(x,y) = \dfrac{\text{PMI}(x,y)}{-\log_2 P(x,y)}The numerator and denominator use the same logarithm base; for
0<P(x,y)<1, normalize to[-1,1], making comparisons across word pairs easierPMI can also be simplified with SVD
Apply SVD to the PMI matrix and take the first
kdimensionsReduce dimensionality and denoise, obtaining dense low-dimensional word vectors
6. Word Vectors: Neural Word2Vec
6.1 Word2Vec Overview
Model
Direction
Description
Skip-gram
Use the target word to predict surrounding words
In practice, better at low-frequency words
CBOW (Continuous Bag of Words)
Use surrounding words to predict the target word
Faster, and better at high-frequency words
6.2 Skip-gram Model
Objective: maximize the probability that the correct words appear in the context given the target word.
Sentence example: ... Bereft of life he rests in peace! If you hadn't nailed him ..., target word rests,
L=2, the context is {he, in, life, peace}.Probabilistic modeling: the probability of context words = the joint probability conditioned on the target word:
P(\text{context} \mid w_t) = \prod_{i \in [-L, \dots, -1, 1, \dots, L]} P(w_{t+i} \mid w_t)Assumption: given the center word, context words are treated as conditionally independent, so their probabilities can be multiplied; this basic version does not distinguish the order of context words.
6.3 Implementation with Logistic Regression (Softmax Form)
P(w_O \mid w_I) = \frac{\exp(v'_{w_O}{}^\top v_{w_I})}{\sum_{w \in V} \exp(v'_{w}{}^\top v_{w_I})}Here,
vis the input (center word) vector andv'is the output (context word) vector.It can be transformed into a neural network:
6.4 Embedding Parameterization: Two Matrices
Key detail: Word2Vec has two sets of word-vector matrices:
W(\vert V\vert \times d): target word embedding (center word/input embedding)C(d \times \vert V\vert): context word embedding (context/output embedding)How to choose
d? Treat the dimension as a hyperparameter and tune it according to corpus size, downstream tasks and computational budget; 100–300 dimensions is a common starting point.Training objective: given any input word, obtain “the probability that each word is its context word,” and hope that the correct context word has the highest probability.
Problem: too slow—the denominator must sum over the entire vocabulary (
\vert V\vertcan reach millions), and every training sample has to traverse all words.6.5 Optimization: Negative Sampling
Transform “predicting
P(\text{context} \mid \text{word})” into a binary classification problem:Why is negative sampling needed?
Maximum likelihood estimation
\max \ \sum_{(w,c)\in D} \log \sigma(u_c^\top v_w) + \sum_{(w,c)\in D'} \log \sigma(-u_c^\top v_w)where
D,D'are the positive and negative word-pair sets respectively,v_wis the input vector, andu_cis the output vector.P(+\mid \text{word},\text{context});P(-\mid \text{word},\text{context}), i.e. suppress the probability that it is judged as a true co-occurrence.Intuition for embeddings: input words and output context vectors that often co-occur tend to have larger dot products; words with similar contexts may learn similar representations. The dot product is also affected by vector length and cannot be directly equated with cosine similarity.
6.6 Loss function
In practice, take
knegative samples for each positive sample (commonlyk=5\sim20, adjusted according to the corpus). Below,Tdenotes the number of positive sample word pairs,c_tis the center word, ando_tis the observed context word:J(\theta) = -\frac{1}{T}\sum_{t=1}^{T}\left[\log \sigma(u_{o_t}^\top v_{c_t}) + \sum_{i=1}^{k} \mathbb{E}_{w_i \sim P_n(w)}\log \sigma(-u_{w_i}^\top v_{c_t})\right]P_n(w)(usually proportional to word frequency raised to the 3/4 power), preventing high-frequency words from dominating while avoiding too many rare words.Advantages:
7. Word Vector Evaluation
7.1 Intrinsic Evaluation 1: Word Similarity
Question: how do we know whether a word's embedding is good?
Method: use cosine similarity between the vectors of two semantically similar words (e.g. well & good), then compare these scores with human similarity ratings using correlation (Spearman correlation).
\cos(u, v) = \frac{u \cdot v}{\Vert u\Vert \,\Vert v\Vert }7.2 Intrinsic Evaluation 2: Word Analogy
Method: perform vector arithmetic in the embedding space and see whether the nearest neighbors conform to the semantic relation.
\text{king} - \text{man} + \text{woman} \approx \text{queen}Vector addition can also illustrate semantic composition, but this is not a standard analogy evaluation:
\text{breakfast} + \text{lunch} + \text{dinner} \approx \text{a direction associated with meal} \quad\text{(an intuition for semantic composition, not an identity)}7.3 Extrinsic Evaluation: Downstream Tasks
Method: directly apply the embeddings to real tasks (classification, NER, translation…), and use task performance to measure embedding quality in turn.