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.
Feed-forward NN

Figure 1-1 A three-layer feedforward network: Input layer → Hidden layer → Output layer; each arrow is a weight.
A single neuron: a function h = f(x)
x, compute a scalar hw to scale the input and add the bias bw and b are the model's parametersh = \tanh\!\left(\sum_j w_j x_j + b\right)Activation function | Formula | Characteristics |
|---|---|---|
Sigmoid |
| Output in (0,1), can be treated as a probability; saturation at both ends causes vanishing gradients |
Tanh |
| Output in (-1,1), zero-centered, easier to train than sigmoid |
ReLU |
| Fast to compute, mitigates vanishing gradients; the negative half-axis “dies” |
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)}(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)Reason for taking the log: it turns a product into a sum and reduces numerical underflow; after adding the negative sign, training can be done by minimizing the loss. This transformation does not make the neural network objective convex.
(b) Gradient descent
\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}(c) Regularisation
Method | Formula/approach | Effect |
|---|---|---|
L1-norm |
| Sparse weights (feature selection) |
L2-norm |
| Constrains 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
Task: given a document, classify it into a predefined set of topics (economy / politics / sport…). Input: bag-of-words.
Training
W and b\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 to C_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
W_1 is the vector of one word.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, where d_h is the hidden-layer dimension)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 |
s_i = f(s_{i-1}, x_i), \qquad s_{i+1} = f(s_i, x_{i+1})f is reused at all time steps.X has variable length, but the dimension of each input vector x_i and that of the state vector s_i are 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: bias
Figure 2-1 A single RNN node: the new state
s_iis jointly determined by the previous states_{i-1}and the current inputx_i.
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.
Figure 2-2 RNN unrolled over time: all time steps share the same set of parameters
W_s, W_x, W_y, b.
x at 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)Sentence: a cow eats grass
x_i is the current word (e.g. eats), first mapped to an embeddings_{i-1} contains information from the previous context (a, cow)y_i predicts the next word (grass)The network is unrolled over time:
a cow eats grass
↓ ↓ ↓ ↓
RNN → RNN → RNN → RNN
s1 s2 s3 s4
↓
y3 = P(·|a cow eats) → target grassNumerical example (vocabulary {a, cow, eats, grass})
Position | Input | State | Output distribution | Target | Loss |
|---|---|---|---|---|---|
1 | a |
| [0.40, 0.30, 0.20, 0.10] | cow |
|
2 | cow |
| [0.30, 0.20, 0.30, 0.20] | eats |
|
3 | eats |
| [0.50, 0.10, 0.20, 0.20] | grass |
|
L_{\text{total}} = L_1 + L_2 + L_3Problem | 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. |
Memory is controlled by gates:
The essence of a gate: a vector with values between 0 and 1 (generally generated using sigmoid), which is multiplied element-wise with the vector being controlled, thereby deciding “how much information to retain.” 0 = completely blocked, 1 = completely passed.
C_t.
Figure 3-1 The repeating module of a vanilla RNN has only one tanh layer, and the state is updated in an overwrite fashion.

Figure 3-2 The LSTM repeating module contains four interacting layers (3 sigmoid gates + 1 tanh), plus an additional cell state channel running through it
C_t.
How to understand memory: C_t provides 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 |
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 |
Forget gate
f_t = \sigma\left(W_f\,[h_{t-1}, x_t] + b_f\right)f_t controls how much information in the old memory cell C_{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.
[h_{t-1}, x_t]means concatenating the previous hidden state and the current input into one vector.

Figure 3-3 Inside the memory cell: the three arrows correspond to the direct cell state path, the previous hidden state
h_{t-1}, and the current inputx_t;\sigmaand\tanhare connected in parallel to form the gates.
Let
\text{Hidden}_{dim} = dimension of memory (also the dimension of h_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{,}368Application | 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) |
Variant | Key points |
|---|---|
Peephole connections | Allow gates to "see" the cell state ( |
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) |
Pros
Cons

Figure 4-1 Overall Transformer architecture (Encoder on the left, Decoder on the right, each stacked
Nlayers; at the bottom are Input/Output Embedding + Positional Encoding). Source: Vaswani et al., Attention Is All You Need, NeurIPS 2017, Figure 1.
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.
Intuitive analogy:
Use the target word's Query to compare relevance with all words' Keys, then use these scores to weight the corresponding Values.
Example: sentence I made her duck, target word her
Role | Content |
|---|---|
Query | The query vector of the target word her |
Key | Context words (I, made, duck) and the target word's own key/value |

Figure 4-2 Self-attention weight allocation: after comparing the Query of the target word her with the Keys of each word, a weighted sum of the Value vectors gives the new representation of her.
Steps
x_i is written as a row vector and multiplied by three projection matrices W_Q, W_K, W_V:q_i = x_i W_Q,\qquad k_i = x_i W_K,\qquad v_i = x_i W_Vq is compared with each word's k using a dot product to obtain relevance scores;v to obtain the target word's output vector z;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.

Figure 4-3 Left: Scaled Dot-Product Attention (MatMul → Scale → Mask → Softmax → MatMul); right: Multi-Head Attention (multiple sets of linear projections computed in parallel, then concatenated and linearly transformed). Source: Vaswani et al., 2017, Figure 2.
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_i by row into Q, 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_k is 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).
Figure 4-4 Computing Q/K/V word by word: each embedding
x_iis multiplied byW_Q, W_K, W_V, then the target word'sqis compared via dot products with allkvectors, and softmax is applied to obtain weights.
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:
h times (different heads have their own W_Q^{(i)}, W_K^{(i)}, W_V^{(i)});z^{(i)} and concatenate them together;W_O, mapping the concatenated result back to the model dimension d, 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)})Multiple Transformer layers repeat these modules. The original Transformer adds positional encoding once to the input embeddings; other positional encoding schemes may inject it differently.
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 ( |
Normalisation layer (LayerNorm) | 2× | Normalizes the hidden features at each position and learns scaling and bias, helping stabilize training |
Note: this uses Layer Normalization, normalizing over each position's own feature dimension and not depending on statistics from other samples in a batch. The figure below uses the original Transformer's Post-LN order; other variants may also use Pre-LN.
Figure 4-5 Inside a Transformer Block: the two sublayers Self-Attention and Feed Forward, each wrapped with a residual connection + LayerNorm.
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)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 |
Problem: using raw counts directly, high-frequency words (the, of) dominate the vectors; moreover, the vector dimension equals the number of documents, making vectors very sparse and high-dimensional.
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 word w.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 |
| 500 | 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 |
SVD (singular value decomposition)
A = U \Sigma V^\topA is the \vert V\vert \times \vert D\vert word–document matrixU: \vert V\vert \times m, new word matrix (each row is the representation of one word)\Sigma: m \times m singular-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)
k singular values and their corresponding directions, and use the rows of U_k or U_k\Sigma_k as word vectors;k is often 100–300);Complete TF-IDF word-vector pipeline
tf-idf matrix → SVD → U → pick k → keep the first k dimensions → word embedding → LSTM (or a downstream model)
Figure 5-1 Apply singular value decomposition to the TF-IDF matrix
A=U\Sigma V^\top, takeU's firstkcolumns to obtaink-dimensional word vectors (LSA).
\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.61Here heaven and hell have a count of 3, so PMI is positive. In the table below, -inf corresponds to fun and hell, whose co-occurrence count is 0: when the marginal probabilities are nonzero,
P(x,y)=0 \Rightarrow \log 0=-\infty.
PMI 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 |
Technique | Approach | Reason |
|---|---|---|
Replace |
| Retains co-occurrence relations above the independence assumption and reduces the impact of unreliable negative-association estimates for low-frequency pairs |
Normalised PMI (NPMI) |
| The numerator and denominator use the same logarithm base; for |
PMI can also be simplified with SVD | Apply SVD to the PMI matrix and take the first | Reduce dimensionality and denoise, obtaining dense low-dimensional word vectors |
Note: PMI for low-frequency word pairs tends to be inflated, so association strength cannot be judged by the score alone. Minimum co-occurrence frequency filtering or smoothing can reduce noise. If using
\log\frac{P(x,y)^k}{P(x)P(y)}as a PMI^kvariant, only whenk>1does it suppress word pairs with low co-occurrence probabilities more strongly than ordinary PMI.
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 |
The range of “surrounding words” (window
L) depends on the situation; the example below usesL=2.

Figure 6-1 Two Word2Vec structures: CBOW (uses context to predict the center word) and Skip-gram (uses the center word to predict context). Source: Mikolov et al., 2013, Figure 1.
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.
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, v is the input (center word) vector and v' is the output (context word) vector.
It can be transformed into a neural network:
one-hot x (1×|V|) → W (|V|×d) → h (1×d) → C (d×|V|) → softmax → P(·|w_t)
input embedding output embeddingKey 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)After training, usually only
W(or the average of both) is kept as the final word vector.
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\vert can reach millions), and every training sample has to traverse all words.
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_w is the input vector, and u_c is 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.
In practice, take k negative samples for each positive sample (commonly k=5\sim20, adjusted according to the corpus). Below, T denotes the number of positive sample word pairs, c_t is the center word, and o_t is 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:
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 }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)}Method: directly apply the embeddings to real tasks (classification, NER, translation…), and use task performance to measure embedding quality in turn.
Practical advice: intrinsic evaluation is fast and cheap, suitable for rapid iteration; final conclusions must be based on downstream tasks.