-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcomp550.tex
More file actions
2299 lines (1860 loc) · 77.8 KB
/
comp550.tex
File metadata and controls
2299 lines (1860 loc) · 77.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[]{article}
\usepackage{etex}
\usepackage[margin = 1.5in]{geometry}
\setlength{\parindent}{0in}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{listings}
\usepackage{color}
\usepackage{mathtools}
\usepackage{multicol}
\usepackage[lined]{algorithm2e}
\usepackage{float}
\usepackage[T1]{fontenc}
\usepackage{ae,aecompl}
\usepackage[pdftex,
pdfauthor={Michael Noukhovitch},
pdftitle={},
pdfsubject={Lecture notes from },
pdfproducer={LaTeX},
pdfcreator={pdflatex}]{hyperref}
\usepackage{cleveref}
\usepackage{enumitem}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\DeclareMathOperator*{\argmax}{arg\,max}
\DeclareMathOperator*{\argmin}{arg\,min}
\lstset{
language=C,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=4
}
\theoremstyle{definition}
\newtheorem*{defn}{Definition}
\newtheorem{ex}{Example}[section]
\newtheorem*{theorem}{Theorem}
\setlength{\marginparwidth}{1.5in}
\setlength{\algomargin}{0.75em}
\DeclarePairedDelimiter{\set}{\lbrace}{\rbrace}
\definecolor{darkish-blue}{RGB}{25,103,185}
\usepackage{hyperref}
\hypersetup{
colorlinks,
citecolor=darkish-blue,
filecolor=darkish-blue,
linkcolor=darkish-blue,
urlcolor=darkish-blue
}
\newcommand{\lecture}[1]{\marginpar{{\footnotesize $\leftarrow$ \underline{#1}}}}
\makeatletter
\def\blfootnote{\gdef\@thefnmark{}\@footnotetext}
\makeatother
\begin{document}
\let\ref\Cref
\title{\bf{Natural Language Processing}}
\date{Fall 2020, McGill\\ \center Notes written from Jackie Cheung's lectures}
\author{Michael Noukhovitch}
\maketitle
\newpage
\tableofcontents
\newpage
\section{Introduction}%
\label{sec:introduction}
\subsection{Overview}%
\label{sub:overview}
\textbf{language} is a form of communication
\begin{itemize}
\item \textit{arbitrary} pairing between form and meaning
\item very expressive and productive
\item nearly universal
\item uniquely human*
\end{itemize}
\textbf{computational linguistics} modelling natural language with computational models
\begin{itemize}
\item acoustic signals
\item NL understanding (comprehension)
\item NL generation (production)
\end{itemize}
goals of the field
\begin{itemize}
\item practical technologies (NLP)
\item understanding how language works (CL)
\end{itemize}
models and techniques
\begin{itemize}
\item gathering data
\item evaluation
\item statistical methods (ML)
\item rule-based systems
\end{itemize}
some example problems
\begin{itemize}
\item is language an instinct? (Chomsky)
\item language processing to understand meaning of sentence
\item can we learn mathematical properties of language
\end{itemize}
types of language
\begin{itemize}
\item \textbf{text} an idealization of spoken language
\begin{itemize}
\item luckily English is similar between writing and speaking, and there is lots of data on it
\item older work used ``clean'' language but recent work ventures into messy data (e.g. Twitter)
\end{itemize}
\item \textbf{speech} is much messier
\begin{itemize}
\item automatic speech recognition (ASR)
\item text-to-speech generation (TTS)
\end{itemize}
\end{itemize}
\subsection{Domains of Language}%
\label{sub:domains_of_language}
\textbf{phonetics} study of speech sounds
\begin{itemize}
\item articulation, transmission
\item how each sound is made in the mouth
\end{itemize}
\textbf{phonology} rules that govern sound patterns
\begin{itemize}
\item how the sounds are organized
\item ``p'' in peach and speach are the same phoneme but phonetically distinct (aspiration)
\end{itemize}
\textbf{morphology} word formation and meaning
\begin{itemize}
\item anti-dis-establish-ment-arian-ism
\end{itemize}
\textbf{syntax} structure of language
\begin{itemize}
\item ``I a woman saw park in the'' is \textbf{ungrammatical}
\item \textbf{ambiguity} different possible meaning for the same phrase
\end{itemize}
\textbf{semantics} meaning of language
\begin{itemize}
\item ``Ross wants to marry \textbf{a} Swedish woman''
\end{itemize}
\textbf{pragmatics} meaning of language in context
\begin{itemize}
\item different from literal meaning
\item \textbf{deixis} interpretation that relies on extra-linguistic context
\item ``dessert would be delicious''
\end{itemize}
\textbf{discourse} structure of larger spans of language
\begin{itemize}
\item do large spans of text form a coherent story
\end{itemize}
\subsection{Technology}%
\label{sub:technology}
combination of hand-crafted knowledge and ML on data
\begin{itemize}
\item rule-based systems
\item machine learning
\item knowledge representation
\end{itemize}
\section{Text Classification}%
\label{sec:text_classification}
\subsection{Basics}%
\label{sub:basics}
\textbf{text classification} assign a label or category to a piece of text
\begin{itemize}
\item sentiment analysis
\item spam detection
\item language identification
\item authorship attribution
\end{itemize}
\textbf{supervised} output data is labelled
\begin{itemize}
\item learn a function, minimize $\theta$ with loss on data
\item e.g. spam classificaiton, predict POS
\item \textbf{regression} $y$ is continuous
\item \textbf{classification} $y$ is discrete
\end{itemize}
\textbf{unsupervised} output data is unlabelled
\begin{itemize}
\item learn a density
\item e.g. grammar induction, word-relatedness (word2vec)
\end{itemize}
\subsection{Building a text classifier}%
\label{ssub:building_a_text_classifier}
\begin{itemize}
\item define problem, collect data
\item extract feats
\item train a classifier on train data
\item apply classifier to test data
\end{itemize}
problem definition
\begin{itemize}
\item problem
\item input
\item output categories
\item how to annotate
\end{itemize}
\subsection{Feature Extraction}%
\label{ssub:feature_extraction}
\textbf{feature extraction} get ``important'' properties of documents
\begin{itemize}
\item convert text into numerical format
\item e.g. word counts as features \textit{unigram counts}
\end{itemize}
\textbf{lemma} remove affixes get dictionary word ``flies $\to$ fly''
\textbf{stemming} remove affix get stem ``airliner $\to$ airlin''
\begin{itemize}
\item rule-based e.g. (Porter, 1980) ``ies $\to$ i''
\end{itemize}
\textbf{n-grams} sequences of adjacent words
\begin{itemize}
\item presence or absence
\item counts
\item proportion of total document
\item scaled version (tf-idf)
\end{itemize}
\textbf{POS tags} crudely capture syntactic pattern (PTB dataset)
\textbf{stop-word removal} remove common uninformative words
sentence representation
\begin{itemize}
\item vector addition $v_{hello} + v_{world}$
\item vector multiplication $v_{hello} \cdot v_{world}$
\item \textbf{max pooling} choose the max of vectors
\end{itemize}
\subsection{Models}%
\label{sub:models}
\textbf{training} select parameters $\theta^*$ according to some objective
types of models
\begin{itemize}
\item \textbf{generative} models joint distribution $P(x, y)$
\begin{itemize}
\item less flexible features as they need to be consistent with each other
\end{itemize}
\item \textbf{discriminative} models conditional $P(y|x)$
\begin{itemize}
\item can be more flexible in terms of features
\end{itemize}
\end{itemize}
\subsubsection{Naive Bayes}%
\label{ssub:naive_bayes}
\textbf{Naive Bayes} probabilistic classifier that uses Bayes' Rule $P(y|x) = \frac{P(y)P(x|y)}{P(x)}$
\begin{itemize}
\item generative
\item assumes data $x$ is generated independently conditioned on class $P(x_i | y)$
\item graphical assumption $P(x,y) = P(y) \prod_i P(x_i|y)$
\end{itemize}
In NLP, we can assume NB over a \textit{categorical} distribution and train
\begin{itemize}
\item loss $L = \prod_{(x,y) \in D} P(y) \prod_i P(x_i|y)$
\item learn $P(Y=y)$ proportion of samples with class $y$
\item learn $P(X_i = x| Y= y)$ proportion of samples with feature $x$ given class $y$
\end{itemize}
Inference time we want $P(y|x)$
\begin{align}
P(y|x) &= P(x,y) | P(x) \\
&= P(y) \prod_i P(x_i|y) / P(x)
\end{align}
where $P(x)$ is the marginalized over all classes
\subsubsection{Logistic Regression}%
\label{ssub:logistic_regression}
\textbf{logistic regression} linear regression with a logit activation
\begin{itemize}
\item $P(y|x) = \frac{1}{Z} \exp (\sum_i a_i x_i)$
\item squash output between $(0,1)$
\end{itemize}
train log-likelihood with \textit{gradient descent}
\begin{align}
\log L(\theta) &= \prod_{(x,y) \in D} \log P(y|x;\theta) \\
&= \prod_{(x,y) \in D} (\sum_i a_i x_i - \log Z)
\end{align}
\subsubsection{Support Vector Machines}%
\label{ssub:support_vector_machines}
SVM learns linear decision to maximize margin to nearest sample in each of two classes
\begin{itemize}
\item can be non-linear using \textit{kernels}
\end{itemize}
\subsubsection{Neural Network}%
\label{ssub:neural_network}
\textbf{Perceptron} logistic regression with Perceptron learning rule
$f(x) = \begin{cases} 1 & \text{if } wx+b > 0 \\ 0 & \text{else} \end{cases}$
\textbf{Stacked Perceptron} stacks perceptron neurons
\textbf{Artificial Neural Network} stacked neurons with non-linear activation functions
\begin{itemize}
\item can learn complex functions
\item need lots of data and computational power
\item given enough neurons can compute any function
\item highly flexible, generic architecture
\item \textbf{multi-task learning} train model to solve multiple tasks simultaneously
\item \textbf{transfer learning} use a network on a task different from its training
\end{itemize}
\textbf{Feed-forward} network
\begin{align}
h_1 &= g_1(W_1 x + b_1) \\
h_2 &= g_2(W_2 h_1 + b_2) \\
y &= W_2 h_2
\end{align}
\textbf{Activation function} on the output of a neuron
\begin{itemize}
\item sigmoid
\item tanh
\item ReLU
\item softmax $\frac{exp(x_i)}{\sum_j \exp(x_j)}$
\end{itemize}
Training neural network done with \textbf{gradient descent} on loss function
\begin{itemize}
\item \textbf{backpropogation} (Rumelhart et al, 1986) uses chain rule to pass gradient
\item \textbf{SGD} apply gradient iteratively over mini-batches of data
\end{itemize}
\subsection{Model Selection}%
\label{sub:model_selection}
How to choose preprocessing, model, etc.. evaluate on unseen data!
Data split
\begin{itemize}
\item \textbf{training} learning the model, 60-90\%
\item \textbf{dev/validation} evaluating while learning the model
\item \textbf{testing} evaluate once at the end to see how well you do
\end{itemize}
\textbf{k-fold cross-validation} split training data into $k$ folds, train on $k-1$ fold and test on the last
Evaluation measures
\begin{itemize}
\item \textbf{accuracy} correct / total samples
\item \textbf{precision} true positives / all predicted positives
\item \textbf{recall} true positives / true number of positives
\item \textbf{F1} $\frac{2 * P * R}{P+R}$, can average with P, R, F1
\end{itemize}
You can average evaluation method across classes
\begin{itemize}
\item \textbf{macro-average} takes the average after computing P, R, F1 for each class
\begin{itemize}
\item $\frac{P_{spam} + P_{not-spam}}{2}$
\item weighs each \textit{class} equally
\end{itemize}
\item \textbf{micro-average} sum of counts first then compute P, R, F
\begin{itemize}
\item $P_{micro} = \frac{TP_{spam} + TP_{not-spam}}{AP_{spam} + AP_{not-spam}}$
\item weighs each \textit{sample} equally
\end{itemize}
\end{itemize}
key issues
\begin{itemize}
\item which eval measure to use
\item stastical significance of test
\item do these tests matter?
\end{itemize}
\section{Language Modelling}%
\label{sec:language_modelling}
\subsection{Words}%
\label{sub:words}
\textbf{word} smallest unit that can appear in isolation
\begin{itemize}
\item philosophically not so clear e.g. ``peanut butter'' vs ``football''
\item practically: \textit{spaces delimit words}
\end{itemize}
word features
\begin{itemize}
\item \textbf{type} identity of a word (count each word once)
\item \textbf{token} instance of a word (count number of occurences)
\end{itemize}
counting words
\begin{itemize}
\item \textbf{term frequency} $TF(w,S) = $number of $w$ in corpus $S$
\item \textbf{relative frequency} $RF(w,S) = \frac{TF(w,S)}{|S|}$
\end{itemize}
\textbf{corpus} of text to use, e.g.
\begin{itemize}
\item Brown
\item British National Corpus
\item WSJC
\end{itemize}
\textbf{Zipf's law} on the ``long tail'' $f \propto \frac{1}{r}$
\begin{itemize}
\item frequency of word is inversely proportional to its rank (by frequency in the corpus)
\item 100th most common word appears 100x less than most common word
\item \textbf{Zipf-Mandelbrot} $f = \frac{P}{(r + \rho)^B}$
\item proportion differs by language
\end{itemize}
\subsection{N-gram Language Models}%
\label{sub:ngram_language_models}
\textbf{language modelling} predicting the next word in a context $P(W = w| C)$
\begin{itemize}
\item can break down with chain rule $P(w_1,2) = P(w_2|w_1)P(w_1)$
\item should assign higher probability to grammatical sentence
\item shouldn't be used to predict grammaticality
\item captures linguistic knowledge and maybe facts about world
\end{itemize}
\textbf{n-grams} feature using $N-1$ previous words as context using MLE
\begin{itemize}
\item \textbf{unigram} 1 word, $P(cats) = \frac{\text{count(cats)}}{\text{count(all words}}$
\item \textbf{bigram} 2 word $P(cats | the) = \frac{\text(counts(the cats)}{\text{count(the)}}$
\item \textbf{trigram} $N=3$ word context
\end{itemize}
evaluation measure
\begin{itemize}
\item \textbf{likelihood} of generating the test corpus
\item \textbf{cross-entropy} $H(p, q) = - \sum_i p_i \log_2 q_i$ with model distribtuion $q$
\begin{itemize}
\item information $I(x) = \log_2 \frac{1}{P(x)}$
\item entropy $H(p) = -\sum_i p_i \log_2 p_i$
\item approx cross entropy with $H(p,q) = -\frac{1}{N} \log_2 q(w_1,\ldots, w_N)$
\end{itemize}
\item \textbf{perplexity} $2^{H(p,q)}$ to make differences larger
\end{itemize}
\subsubsection{Learning}%
\label{ssub:learning}
\textbf{maximum likelihood estimation} choose parameters $\theta$ to maximize likelihood training corpus $X$
\begin{itemize}
\item i.i.d assumption of words in corpus $P(C;\theta) = \prod_n P(x_n;\theta)$
\item for a Bernoulli $P(C;\theta) = \theta^{N_1}(1-\theta)^{N_0} \ldots \theta_{MLE} = \frac{N_1}{N_0 + N_1}$
\end{itemize}
two issues with learning
\begin{itemize}
\item \textbf{overfitting} with high train accuracy, low test data accuracy
\item \textbf{underfitting} low train accuracy
\end{itemize}
model complexity tradeoff
\begin{itemize}
\item highly expressive models overfit easier
\item choose a model class and regularization/smoothing technique
\end{itemize}
\subsubsection{Smoothing}%
\label{ssub:smoothing}
out-of-vocabulary (OOV) at test time is a real problem
simple solution
\begin{itemize}
\item replace all words less than freq threshold with \texttt{<UNK>}
\item treat \texttt{<UNK>} as a vocabulary item
\end{itemize}
\textbf{smoothing} probability distribution, move mass to unseen cases
\begin{itemize}
\item don't trust frequency counts entirely
\item no longer doing MLE but can use $\theta_{MLE}$ prior
\item $\theta_{smooth} = \max_\theta P(X;\theta)P(\theta) $
\end{itemize}
\textbf{add-$\delta$ smoothing} add frequency to each word ( \textit{pseudocount}(
\begin{itemize}
\item for unigram $P(w) = \frac{count(w) + \delta}{N+\delta *|Lexicon|}$
\item with $\delta=1$ called \textbf{laplace discounting}
\end{itemize}
\textbf{interpolation} lower $N$ in $N$-gram to alleviate data sparsity
\begin{itemize}
\item combine $\hat P = \lambda_1 P_{unigram}^{MLE} + \lambda_2 P_{bigram}^{MLE} + \lambda_3 P_{trigram}^{MLE}$
\end{itemize}
\textbf{Good-Turing Smoothing} assume probability based on zipf's law, assuming all UNK appear once and readjust others accordingly
\begin{itemize}
\item build a histogram of event frequency $f_c$ (e.g. 1000 words appear once $f_1 = 1000$, 600 words appear twice $f_2 = 600$)
\item total number of observed event-tokens $N = \sum_i f_i * i$
\item $w_c$ is event that occurs $c$ times
\item choose probability for all unseen $P(UNK) = \frac{f_1}{N}$
\item readjust other mass $c^* = \frac{(c+1)f_{c+1}}{f_c},P(w_c) = \frac{c^*}{N}$
\end{itemize}
\textbf{GT-refinement} estimate linear regression $f_c^{LR} = a \log c + b$ for higher values of $c$
\begin{itemize}
\item Good-Turing fails for higher $c$ where $f_{c+1} = 0$
\item use linear regression estimate for $c >$ threshold
\item use regular $f_c$ for $c < $ threshold
\end{itemize}
\subsection{Hidden Markov Models}%
\label{ssec:hidden_markov_models}
\subsubsection{POS Tagging}%
\label{ssub:pos_tagging}
\textbf{part of speech} syntactic category that tells you grammatical properties of a word
\begin{itemize}
\item nouns
\item verbs
\item adjectives
\item prepositions
\item adverbs
\item determiners ``the, a, an''
\end{itemize}
other POS
\begin{itemize}
\item modals and auxiliary verbs ``*did* you see him?''
\item conjunctions ``and, or, but, yet''
\item particles ``look *up* and *down*''
\end{itemize}
classes of POS
\begin{itemize}
\item open class: where new words (\textbf{neologism}) can be added to the language
\begin{itemize}
\item e.g. nouns like "Kleenex", adjectives like "sick"
\item tend to be content words
\end{itemize}
\item closed class: new words \textit{tend} not to be added
\begin{itemize}
\item function words that convey grammatical info
\end{itemize}
\end{itemize}
corpora
\begin{itemize}
\item Penn Treebank (45 tags)
\item Brown corpus (87 tags)
\end{itemize}
language differences
- japanese doesn't differ between nouns and pronouns but verbs are closed class
- wolof doesn't conjugate verbs for person and tense but pronouns are
- Salishan languages may not distinguish between nouns and verbs
POS tagging is a \textbf{sequence labelling} problem since it uses context
\subsubsection{Markov Chains}%
\label{ssub:markov_chains}
We assume a \textbf{markov process}
\begin{itemize}
\item $N$ states
\item weighted transitions between states
\item transition only dependent on current state
\end{itemize}
Model POS as \textbf{hidden variable} aka state, words are visible \textbf{emissions}
\begin{itemize}
\item independence assumption allows you to factorize
\item $P(O,Q) = P(Q_1) \prod_t P(Q_{t+1}|Q_t) \prod_t P(O_t | Q_t)$
\item $P(the text) = P(DT) P(the | DT) P(NN | DT) P (text | NN)$
\end{itemize}
HMM for $N$ tags, $W$ words, parameters $\theta$
\begin{itemize}
\item initial prob $Q_1$
\item transition probs $a_{t,t+1}: Q_t \to Q_{t+1}$
\item emission probs $b_t(O_t): Q_t \to O_t$
\end{itemize}
Choosing the most likely POS tag for each output is naive!
\begin{itemize}
\item $P(O|\theta)$ computing likelihood of a sequence (forward/backward algorithm)
\item $\argmax_Q P(Q, O|\theta)$ what state sequence best explains observations (Viterbi)
\item Given an observation sequence, what is the best model? (Forward-Backward, Baum-Welch, EM)
\end{itemize}
\subsubsection{Forward Algorithm}%
\label{ssub:forward_algorithm}
$P(O|\theta) = \sum_Q P(O,Q|\theta)$
since there are $N^T$ possible paths so use DP to avoid recalculations (see Trellis in \ref{fig:forward-trellis})
\begin{figure}[h]
\centering
\includegraphics[width=0.8\linewidth]{comp550/forward.png}
\caption{Trellis for Forward Algorithm}%
\label{fig:forward-trellis}
\end{figure}
Current tag,previous words given previous tags $\alpha_i(t) = P(O_{1:t},Q_t = i | \theta)$
\begin{itemize}
\item initial prob $\alpha_j(1) = \pi_j b_j(O_1)$
\item recurrent sum over prev $\alpha_j(t) = \sum_i \alpha_i(t-1) a_{ij} b_j(O_t)$
\item final $P(O|\theta) = \sum_j \alpha_j(T)$
\item runtime $O(N^2T)$
\end{itemize}
\subsubsection{Backward Algorithm}%
\label{ssub:backward_algorithm}
Subsequent words given current tag $\beta_(t) = P(O_{t+1:T} | Q_t = i, \theta)$
\begin{itemize}
\item excludes the current word unlike $\alpha$
\item initial prob $\beta_j(T) = 1$
\item recurrent sum over prev $\beta_i(t) = \sum_j a_{ij} b_j(O_{t+1}) \beta_j(t + 1) $
\item final $P(O|\theta) = \sum_i \pi_i b_i(O_i) \beta_i(1)$
\item runtime $O(N^2T)$
\end{itemize}
\subsubsection{Forward-Backward}%
\label{ssub:forward_backward}
Double-check forward using backward
\begin{itemize}
\item $\alpha_i(t) \beta_i(t) = P(O, Q_t = i | \theta)$
\item therefore $P(O | \theta) = \sum_i \alpha_i (t) \beta_i (t)$ for any $t \in [1\ldots T]$
\end{itemize}
Work in log probs for numerical stability
\begin{itemize}
\item $\prod p_i \to \sum \log p_i$
\item $\sum p_i \to \log \sum p_i = b + \log \sum e^{a_i - b}$ where $b = \max \log p_i$
\end{itemize}
\subsubsection{Viterbi}%
\label{ssub:viterbi}
Find most likely state sequence $Q* = \argmax_Q P(Q,O|\theta)$, like forward algorithm, but take the $\max$
\begin{itemize}
\item initial $\delta_j(1) = \pi_j b_j(O_1) \forall j \in [1,N]$
\item recurrence $\delta_j(t) = \max_i \delta_i (t-1) a_{ij} b_j(O_t)$
\item final $\max_i \delta_i(T)$
\item runtime $O(N^2T)$
\end{itemize}
Recover best $i$ for each $T$ by keeping track of $\argmax_i$ (\ref{fig:viterbi-alg})
\begin{figure}[ht]
\centering
\includegraphics[width=0.8\linewidth]{comp550/viterbi.png}
\caption{Viterbi backpointers}
\label{fig:viterbi-alg}
\end{figure}
\subsubsection{Baum-Welch}%
\label{ssub:baum_welch}
How to deal with unsupervised learning? \textbf{Hard EM} or Viterbi EM
\begin{enumerate}
\item initialize randomly
\item predict current state sequence using current model
\item update current parameters based on current predictions
\item repeat from 2
\end{enumerate}
\textbf{Baum-Welch} or soft EM uses soft predictions
\begin{itemize}
\item expectation: get expected counts for hidden structures using $\theta_k$
\item maximization: find $\theta_{k+1}$ to maximize likelihood on expected counts
\item finds a local optimum in $P(O|\theta)$
\end{itemize}
Expectation of \textbf{responsabilities}: prob distribution over tags
\begin{itemize}
\item state prob $\gamma_i(t) = P(Q_t = i|O, \theta^k) = \frac{\alpha_i(t)\beta_i(t)}{P(O|\theta^k)} $
\item transition prob $\xi_{ij}(t) = P(Q_t = i, Q_{t+1} = j| O, \theta^k) = \frac{\alpha_i(t) a_{ij} b_j(O_{t+1})\beta_j(t+1)}{P(O|\theta^k)} $
\end{itemize}
Maximization of Soft MLE update
\begin{itemize}
\item $\pi_i^{k+1} = \gamma_i(1)$
\item $a_{ij}^{k+1} = \frac{\sum_t \xi_{ij}(t)}{\sum_t \gamma_i(t)} \approx \frac{count(i,j)}{count(i)} $
\item $b_i^{k+1}(w_k) = \frac{\sum_t \gamma_{ij}(t)|_{O_t = w_k}}{\sum_t \gamma_i(t)} \approx \frac{count(w_k, i)}{count(i)}$
\end{itemize}
Practical training
\begin{itemize}
\item stop iteration using performance on held-out set
\item \textbf{random restarts} train different models from different inits
\item biased initialization using some external supervised knowledge
\item \textbf{semi-supervised} with small labelled data and large unlablled
\end{itemize}
\subsubsection{Multiword Tasks}%
\label{ssub:multiword_tasks}
Similar HMM tasks can require multiple words per tag
\begin{itemize}
\item \textbf{Chunking} find syntactic chunks e.g. \texttt{[The chicken] [crossed] [the road]}
\item \textbf{Named Entity Recognition} (NER) identify elements corresponding to high-level categories e.g. \texttt{[McGill University] is located in [Montreal, Canada]}
\end{itemize}
\textbf{IOB tagging} label whether word is at beginning, inside, or outside a span of tags e.g. McGill\texttt{[B-ORG]} University\texttt{[I-ORG]} is located in Montreal\texttt{[B-LOC]} Canada\texttt{[I-LOC]}
\subsection{Linear-chain CRF}%
\label{ssub:linear_chain_crf}
\subsubsection{Discriminative}%
\label{ssub:discriminative}
Shortcoming of HMMs
\begin{itemize}
\item adding a feature requires adding an emission e.g. word position, capitalization...
\end{itemize}
\textbf{LC-CRF} linear chain conditional random field
\begin{itemize}
\item HMM-like task-specific discriminative model $P(Y|X;\theta)$ using features, not probs
\item $P(Y|X) = \frac{1}{Z(X)} \exp \sum_t \sum_k \theta_k f_k(y_t, y_{t-1}, x_t)$
\item $Z(X) = \sum_y P(Y|X)$ is a normalization constant
\item sum over all timesteps $t$, features $k$
\end{itemize}
Examples of features
\begin{itemize}
\item HMM probs e.g. emit "the" from DT $1(y_t = DT) 1(x_t = "the")$
\item capitalization $1(y_t = ?) 1(x_t \text{is capitalized})$
\end{itemize}
\subsubsection{Inference}%
\label{ssub:inference}
Forward algorithm computes $Z(X)$
\begin{itemize}
\item initial prob $\alpha_j(1) = \exp \sum_k \theta_k^{init} f_k^{init}(y_1 = j, x_1)$
\item recurrent sum over prev $\alpha_j(t) = \sum_i \alpha_i(t-1)\exp \sum_k \theta_k f_k(y_t = j, y_{t-1}, x_1) $
\item final $Z(X) = \sum_j \alpha_j(T)$
\end{itemize}
Viterbi algorithm computes $\argmax_Y P(Y|X,\theta)$
\subsubsection{Training}%
\label{ssub:training}
Use gradient descent $\theta_{t+1} \gets \theta_t + \alpha \nabla l(\theta)$
\begin{itemize}
\item no analytic solution
\item $l(\theta)$ is concave
\item can use conjugate gradient and L-BFGS
\end{itemize}
Gradient $\nabla l(\theta)$ = empirical count of features - expected feature count using current model
\begin{itemize}
\item minimized when model matches empirical distribution
\item regularization $\sum_k \frac{\theta_k^2}{2\sigma^2}$
\item SGD used in practice
\end{itemize}
\subsection{Recurrent Neural Networks}%
\label{sub:recurrent_neural_networks}
\subsubsection{Neural Networks}%
\label{ssub:neural_networks}
Feed-forward NN
\begin{itemize}
\item all computations flow forward
\end{itemize}
Time-delay NN
\begin{itemize}
\item feed context window around word into FF
\item requires fixed horizon
\item sequence interaction learned indirectly, not sequence model!
\end{itemize}
\subsubsection{RNN}%
\label{ssub:rnn}
RNN: NN sequence model
\begin{itemize}
\item modelling long-range dependencies
\item $RNN(s_0, x_{1:n}) = s_{1:n}, y_{1:n}$
\item $s_i = R(s_{i-1}, x_i)$
\item $y_i = O(s_i)$
\end{itemize}
comparison to LC-CRF
\begin{itemize}
\item LCCRF is linear, RNN is more expressive
\item LCCRF uses feature engineering, RNN discovers features
\item LCCRF assumes local independence, fast inference, RNN need approx (e.g. beam-search)
\end{itemize}
\subsubsection{LSTM}%
\label{ssub:lstm}
vanishing and exploding gradient
\begin{itemize}
\item gradients wrt time 1 $ \frac{\partial L}{\partial W^1} =
\frac{\partial L}{\partial f^N}
\frac{\partial f^{N-1}}{\partial f^{N-2}} \ldots
\frac{\partial f^1}{\partial W^1} $
\item if gradient norm $<1$, it will vanish
\item if gradient norm $>1$, it will explode to infinity
\end{itemize}
Long Short-Term Memory (Hochreiter and Schmidhuber, 1997)
\begin{itemize}
\item explicitly model memory $C_t = f_t * C_{t-1} + i_t * \tilde C_t$
\item forget $f_t = \sigma(W_f \cdot [h_{t-1},x_t]) $
\item input $i_t = \sigma(W_i \cdot [h_{t-1},x_t]), \tilde C = \tanh (W_C \cdot [h_{t-1}, x_t]) $
\item output $o_t = \sigma(W_o \cdot [h_{t-1},x_t])$
$h_t = o_t * \tanh(C_t)$
\end{itemize}
BiLSTM, a layer for forward and backward
\begin{itemize}
\item concatenate $h_{forward},h_{backward}$ to get output
\end{itemize}
LSTM-CRF, LCCRF layer on top of a BiLSTM
\begin{itemize}
\item using features: output scores of LSTM $P$, transition probabilities b/w tags (learned) $A$
\item total score $s(X,y) = \sum_i A_{y_i,y_{i+1}} + \sum_i P_{i,y_i}$
\end{itemize}
training
\begin{enumerate}
\item forward pass for BiLSTM
\item forward CRF to get predictions
\item backward pass CRF to get loss
\item backprop loss through BiLSTM
\end{enumerate}
\subsection{Pretrained LMs}%
\label{sub:pretrained_lms}
\subsubsection{Transfer Learning}%
\label{ssub:transfer_learning}
\textbf{transfer learning} using knowledge from one task to improve performance on another
\begin{itemize}
\item don't start task from scratch, transfer knowledge of words, syntax,...
\item use language modelling as a source task
\end{itemize}
ELMo (Peters et al, 2018) large-scale LM pretrained BiLSTM
\begin{itemize}
\item generate contextual word embeddings
\item $ELMo(w_k)$ = weighted sum of BiLSTM layers
\end{itemize}
\subsubsection{Transformer}%
\label{ssub:transformer}
Attention is all you need (Vaswani et al, 2017)
\begin{itemize}
\item allow information flow between any pair of words
\item Transformer architecture uses only attention, no recurrence
\item $O(N^2)$ connections but better parallelism
\end{itemize}
attention, three views of a word
\begin{itemize}
\item query: word we want to compute in the next layer
\item key: how important the word is to another word
\item value: value associated with the key once attention is computed
\end{itemize}
\subsubsection{Large Scale Pretrained Models}%
\label{ssub:large_scale_pretrained_models}
BERT - transformer encoder model
\begin{itemize}
\item pretraining MLM (masked language modelling) and next sentence prediction
\item trained on ~3B words
\item 340M parameters
\end{itemize}
GPT-3 (OpenAI, 2020) - transformer decoder model
\begin{itemize}
\item pretraining on language modelling
\item trained on ~500B words
\item up to 175B model parameters
\item success in 0-shot and few-shot learning
\end{itemize}
Problems
\begin{itemize}
\item generated text can be incoherent or repetitive
\item reasoning about physics + commonsense
\item arguments about memorization vs understanding
\item misuse of language models (spam, fake news)
\item fairness, bias, cost!
\end{itemize}
\section{Syntax}%
\label{sec:syntax}
\subsection{Form of Language}%
\label{sub:form_of_language}
\textbf{syntax} words arranged to form a grammatical sentence
\begin{itemize}
\item generate all and exactly those sentences which are grammatical ( \textbf{grammaticality} )
\item \textbf{descriptive} not \textbf{prescriptive}
\end{itemize}
\textbf{contituency} group of words that behave as a unit, e.g for noun phrases
\begin{itemize}
\item can appear in similar syntactic envs
\item can be replaced as a unit or rearranged
\item can be used to answer a question
\end{itemize}
\textbf{grammatical relations} between contituents e.g.
\begin{itemize}
\item subject
\item (direct) object e.g. he kicked \textit{the ball}
\item indirect object e.g. she gave \textit{him} a good beating
\end{itemize}
\textbf{subcategorization} different number and type of args mandatory for a verb or adj
\begin{itemize}
\item (subj) relax
\item (subj) steal (obj)
\item (subj) want (obj / inf clause)
\item different (from / than / to)
\end{itemize}
\subsection{Formal Grammars}%
\label{sub:format_grammars}
\textbf{formal grammar} rules that generate a set of strings to make up a language
\textbf{finite state automata} generates a regular language
\begin{itemize}
\item correspond to \textbf{regular grammars}
\item used for stemming, lemmatization, ...