
Sign up to save your podcasts
Or


A machine learning tech stack: pandas cleans the data, NumPy hands it to a deep learning framework that runs on the GPU, and scikit-learn scales features and covers shallow algorithms. Also covers TensorFlow vs PyTorch, NVIDIA GPUs and CUDA, cloud GPUs and spot instances, Keras, and splitting a web app server from a GPU job server with a message queue.
LinksIt gives you the building blocks (layers, activation functions, optimizers), automatic differentiation so backpropagation is computed for you, and execution on a GPU. How much faster a GPU runs than a CPU depends on the model and on how much data moves between them.
Which framework?PyTorch is now the default deep learning framework for research and most new work (MLG 010). TensorFlow, usually through Keras, is still widely deployed, and Google's own research has largely moved to JAX. Keras 3 runs on JAX, TensorFlow or PyTorch. Theano stopped development in 2017 and lives on in the PyTensor fork. Caffe is retired.
TensorFlow 2 runs eagerlyThe graph-building the episode describes, placeholders and feed dicts passed to session.run, is TensorFlow 1. TensorFlow 2 runs eagerly, line by line like ordinary Python, as PyTorch does, and tf.function compiles a function into a graph when you want the speed. Starting in Keras's high-level API and dropping to lower-level code where you need control still works.
GPUs: NVIDIA, AMD and Apple siliconGPU deep learning still centers on NVIDIA's CUDA. You no longer download CUDA and cuDNN by hand: pip install tensorflow[and-cuda] installs them with TensorFlow, and PyTorch's install selector picks a build for your CUDA version. Building TensorFlow from source for speed is rarely worth it now.
The GTX 1080 Ti from the episode is several generations old. For a laptop, see Laptop for machine learning and gaming.
Cloud GPUsAWS no longer lists the p2 instances from the episode among its EC2 instance types. Single-GPU options now include G5 (NVIDIA A10G), G6 (L4) and G6e (L40S) instances, and P5/P5e (H100, H200) and P6 (B200, B300) instances handle large training jobs.
Spot Instances still cost up to 90% less than on-demand. EC2 interrupts a Spot Instance mainly when it needs the capacity back, so a high maximum price doesn't guarantee you keep it, and setting a maximum price makes interruptions more frequent. Save checkpoints so a training run can resume.
Google Cloud has rented TPUs since a beta in February 2018. For learning, hosted notebooks such as Google Colab and Kaggle Notebooks run on cloud GPUs without any setup. MLA 013 covers the tech stack for customer-facing machine learning products.
The data pipelineThe architecture in the episode still holds. A web app server takes user requests and puts jobs on a queue, and GPU job servers, called workers, take jobs off it. A job waits in the queue rather than getting lost while a worker is busy or down, and several workers can share the load. Celery runs the workers in Python, with RabbitMQ, Redis or Amazon SQS as its broker. ZeroMQ is a messaging library, not a broker, and isn't among Celery's brokers.
To serve models over HTTP, NVIDIA Triton and, for large language models, vLLM are common, and Amazon SageMaker hosts managed endpoints.
Reinforcement learningTensorforce is no longer maintained. For deep reinforcement learning, pair Gymnasium environments with Stable-Baselines3 agents.
Where to learn the stackNext: MLG 025, on convolutional neural networks.
Try a walking desk to stay healthy while you study or work!
Notes and resources at ocdevel.com/mlg/23
Neural Network Types in NLPVanilla Neural Networks (Feedforward Networks):
Convolutional Neural Networks (CNNs):
Recurrent Neural Networks (RNNs):
Supervised vs Reinforcement Learning:
Encoder-Decoder Models:
Gradient Problems & Solutions:
A recurrent neural network reads a sentence one word at a time, carrying a hidden state forward, and word2vec learns word vectors that place words used in similar contexts near each other. Also covers encoder-decoder translation, one-hot vs dense vectors, skip-gram and CBOW, GloVe and where to learn deep NLP.
LinksWords combine in ways a linear model can't add up: "not good" means something neither word means alone. A neural network learns these combinations from data (feature learning) instead of needing them engineered by hand, and each deeper layer combines the combinations below it. Deep models are also end-to-end: one network trained as a whole replaces the separately trained parsing, alignment and language models of classical machine translation (MLG 020).
How a recurrent neural network worksA feed-forward network maps one input to one output. A recurrent neural network (RNN) reads a sequence one step at a time, reusing the same weights at every step, and keeps a hidden state: a vector summarizing what it has read so far. At each step it combines the current input, such as a word, with the previous hidden state to make the new hidden state, and can emit an output.
h_t = tanh(W·x_t + U·h_(t−1) + b)"Recurrent" names this recurrence, the hidden state fed back in at each time step. It isn't function recursion. For training, the network is unrolled through time and trained by backpropagation through time.
Emitting one output per input word, an RNN can tag parts of speech or named entities, jobs that hidden Markov models did in MLG 019, with the hidden state carrying what came earlier in the sentence.
Encoder-decoder (sequence to sequence)For translation, an encoder RNN reads the whole source sentence into its final hidden state, a fixed-size vector, and a decoder RNN generates the translation from that vector one word at a time. Sentiment analysis and classification are the one-output case: read the whole sequence, emit one label.
Squeezing a long sentence into one vector loses information. Attention (Bahdanau et al., 2014) let the decoder look back at every encoder state, and the transformer (Vaswani et al., 2017) dropped recurrence and kept attention. Transformers and the large language models built on them have since replaced RNNs for translation and most other NLP (MLG 033, MLG 034).
From one-hot vectors to word embeddingsA one-hot vector represents a word as all zeros except a 1 at that word's index in the vocabulary. It carries no meaning: every word is equally far from every other. A word embedding is a dense vector, typically 100 to 300 numbers for word2vec and GloVe, learned so that words used in similar contexts sit near each other.
Closeness between embeddings is usually measured by cosine similarity, the angle between two vectors. Search uses the same measure on TF-IDF document vectors, ranking documents by highest cosine similarity to the query (MLG 019).
Vector arithmetic captures some relationships. In the word2vec paper, vector("King") − vector("Man") + vector("Woman") is closest to vector("Queen"). Because embeddings come from context, antonyms often land close together: "good" and "bad" both follow "the movie was".
word2vec and GloVeword2vec (Mikolov et al., 2013) is a shallow neural network trained to predict context, in one of two forms:
Predicting over the whole vocabulary at every step is expensive, so training uses hierarchical softmax or negative sampling, a simplified form of noise-contrastive estimation that teaches the model to tell real context words from random ones. The learned weights form the embedding matrix, one row per word.
Latent semantic analysis (LSA) factorizes a term-document count matrix with singular value decomposition (SVD); other count-based methods start from word-by-word co-occurrence counts. GloVe (Pennington, Socher and Manning, 2014) also works from global co-occurrence counts, but learns vectors by gradient descent so that their dot products fit the logarithm of those counts.
Both give static embeddings: one vector per word, whatever the sentence. Contextual embeddings from transformers, such as BERT (2018), give a word a different vector in each sentence, and most current text-embedding models are transformers.
Plotting embeddingsTo see embeddings in 2-D or 3-D you project them down. t-SNE is nonlinear and keeps each point's nearest neighbors close, so clusters of related words show up. PCA is linear: it projects onto the directions of greatest variance. UMAP is a common nonlinear alternative to t-SNE.
Vanishing gradients, LSTM and GRUA vanilla RNN's units typically use tanh. Backpropagating through many time steps makes gradients shrink toward zero (vanishing) or blow up (exploding). LSTM and GRU cells, covered in MLG 023, use gates to carry information across long spans and ease vanishing gradients; gradient clipping caps exploding ones.
Where to learn deep NLPFor RNNs within deep learning as a whole, Deep Learning by Goodfellow, Bengio and Courville covers them in chapter 10.
Next: MLG 023, on LSTM and GRU cells, bidirectional RNNs and the vanishing-gradient problem.
Syntax parsing turns a tagged sentence into a tree, by probabilistic context-free grammars with CKY or, more often today, dependency parsing; classical NLP then combines it with TF-IDF and named entity recognition to answer questions. Also covers the Penn Treebank, TextRank summarization, statistical vs neural machine translation and NLP data pipelines.
LinksText moves through stages, each feeding the next one downstream:
ingest documents -> clean (tokenize, lowercase, stem/lemmatize, drop stop words) -> POS tagging -> syntax parsing -> goalText classification with naive Bayes needs only the bag of words, and search uses TF-IDF with cosine similarity (MLG 019). Named entity recognition (NER) is both a goal and a tool for later stages. At scale each stage gets its own machines. Hadoop and Spark are the classic distributed data-processing frameworks, and Spark is the one still in wide use.
Constituency parsing with context-free grammarsSyntax parsing builds a tree over a part-of-speech-tagged sentence. A constituency parse groups words into phrases: in "The boy with blonde hair walked up the mountain", "the boy with blonde hair" is a noun phrase (NP) and "walked up the mountain" a verb phrase (VP), each breaking down further to POS tags. A context-free grammar (CFG) writes these groupings as production rules:
S -> NP VP VP -> V NP NP -> Det N | Adj NPHand-written rules fail on ambiguity: the headline "Pope's baby steps on gays" parses two ways. A probabilistic CFG (PCFG) learns how often each production occurs from parsed sentences. The CKY (Cocke–Kasami–Younger) algorithm, a dynamic-programming parser for grammars in Chomsky normal form, then finds the most likely tree.
Penn Treebank and WordNetThe Penn Treebank is an annotated corpus: sentences tagged with their parse trees in bracketed notation, used to train parsers and POS taggers. WordNet is a lexical database of English that groups words into synonym sets; NLTK includes it.
Dependency parsingA dependency parse draws arcs from head words to the words that depend on them, optionally labeled with the relation. In "Alice saw Bob reading in the hallway", "saw" is the root, with arcs to its subject "Alice" and to "Bob". Dependency parsing is the common approach today. Transition-based parsers read left to right with a stack and a buffer, at each step moving a word onto the stack or attaching words with an arc; a greedy parser takes the best-scoring move each time.
Google's SyntaxNet and its English model Parsey McParseface (2016) are retired. spaCy and Stanford's Stanza ship neural dependency parsers, and transformer models, LLMs included, are state of the art for parsing.
Relationship extraction and Google's knowledge panelA parse shows which entity does what to which, so relationship extraction can pull facts like spouse(A, B) out of a sentence. Google's knowledge panel, the card beside the results for a person, company or band, shows facts from its Knowledge Graph: birth date, spouse, founders, members.
Question answering with classical NLPFor "Who is the prime minister of the United Kingdom?":
That uses four tools: POS tagging, syntax parsing, TF-IDF with cosine similarity, and NER. Google shows answers like this as a featured snippet.
Text summarization: TF-IDF and TextRankThese are extractive: they splice existing sentences. Transformers and LLMs are state of the art for summarization and question answering, including abstractive summaries that write new sentences. TextRank remains a simple extractive baseline.
Statistical vs neural machine translationClassical statistical machine translation combined a translation model and a language model (the noisy-channel model), aligned words between the two languages, and used beam search to choose among candidate translations, with each component trained separately. Neural machine translation replaced it with one model trained end to end, first RNN encoder-decoders (MLG 022) and now transformers (MLG 033).
Deep learning now leads on most of the tasks in MLG 018 to 020: parsing, named entity recognition, classification, question answering, summarization and translation. BM25, a refinement of TF-IDF, remains a strong search baseline. The classical methods are still faster, need less data, and lay out the structure of each task.
Where to learn classical NLPThe same as MLG 018 and MLG 019:
Next: MLG 022, on deep NLP: word embeddings and recurrent neural networks.
Classical natural language processing (NLP) runs on n-gram language models, naive Bayes, MaxEnt, hidden Markov models and LDA, still fast baselines beside transformers. Also covers generative vs discriminative models and search with TF-IDF and cosine similarity.
LinksClassification and sentiment now run on fine-tuned transformers or LLMs (MLG 033); naive Bayes and TF-IDF remain fast baselines.
Levenshtein distance and the Porter stemmerLevenshtein distance counts the single-letter insertions, deletions and substitutions between two words. The Porter stemmer chops suffixes by rule, overstemming organizer and organization to "organ"; their lemma is "organize".
N-grams and n-gram language modelsAn n-gram is a run of n tokens: "hello how are you doing" has five unigrams and four overlapping bigrams (hello how, how are, …).
A language model scores how probable a sentence is: "I took my dog to the park" beats "I took my dog to the egg". The chain rule conditions each word on those before it; an n-gram model keeps only the previous n−1. A plain product of probabilities holds only for independent events (MLG 013).
bigram: P(w1 … wn) ≈ P(w1) × P(w2 | w1) × … × P(wn | wn−1) P(how | hello) = count(hello how) / count(hello)Conditioning on one previous word is a bigram model, on two a trigram model. Larger n is more accurate but costs storage and data. Uses: predictive text and spelling correction.
Naive Bayes for text classificationNaive Bayes classifies documents. Bayes' rule turns P(words | spam), easy to count, into P(spam | words). As a bag-of-words model it ignores order, missing "not pleasant", and its independence assumption counts "Hong Kong" twice.
Maximum entropy (MaxEnt) modelsMaxEnt is multinomial (softmax) logistic regression. For part-of-speech (POS) tagging and named entity recognition (NER) it classifies words from hand-built features: suffix (-ly suggests an adverb), neighbors, and a capital mid-sentence, which suggests a proper noun.
Hidden Markov models (HMM) for POS taggingA hidden Markov model is a Markov chain (MLG 014) whose states are hidden, each emitting what you observe, as weather shows in what people wear. For tagging, the hidden states are POS tags and the observations are words.
Generative vs discriminative modelsLatent Dirichlet allocation (LDA), unsupervised, models each document as a mixture of topics and each topic as a distribution over words: a document can be 30% pets and 20% baseball, where k-means gives one cluster. LSA/LSI instead factor the term-document matrix with SVD.
Bag of words and TF-IDFA bag-of-words vector has one column per vocabulary word, holding 0/1 or a count, mostly zeros: sparse. Raw counts reward keyword stuffing and common words. TF-IDF weights a term by its rarity across documents, so stop words sink without being removed.
tf-idf(t, d) = tf(t, d) × log(N / df(t)) N = documents, df(t) = documents containing tDense vectors are learned embeddings: word2vec (MLG 022), then transformer embeddings.
Cosine similarity vs Euclidean distance vs JaccardSearch ranks the documents containing the query terms by cosine similarity of TF-IDF vectors. Elasticsearch has scored with BM25, a refinement of TF-IDF, by default since 2016, and also runs dense-vector search.
Where to learn classical NLPNext: MLG 020, on syntax parsing and the larger NLP tasks.
Natural language processing (NLP) is machine learning applied to language, from tokenizing and tagging words up to search, translation and chatbots, now led by transformers and LLMs. Also covers stemming vs lemmatization, edit distance, named entity recognition, NLP libraries and where to learn NLP.
LinksNLP, also called computational linguistics, is machine learning applied to language. It moved from hand-coded linguistic rules to shallow machine learning to deep learning. The state of the art is now the transformer (MLG 033) and the large language models (LLMs) built on it, which replaced the recurrent neural networks and word2vec of MLG 022. Text must become numbers, and word order changes meaning.
Syntax vs semanticsSyntax is structure: parts of speech, phrases, word form. Semantics is meaning, which translation and question answering need.
Corpus, token and stop wordsBoth reduce variants to one form, so "hunting" matches "hunt". Stemming strips affixes by rule; it is fast, and its result need not be a word. Lemmatization returns the dictionary form using vocabulary and part of speech, so "better" becomes "good".
Edit distanceThe count of single-letter insertions, deletions or substitutions between two words: "cat" and "car" are one apart. Spell checkers propose the closest words and pick the likeliest in context.
Part-of-speech tagging, named entity recognition and parsingLLMs now handle translation, summarization, sentiment, question answering and chat. Google's answer box is the featured snippet, now joined by AI Overviews. Speech recognition and OCR are end-to-end neural models, such as OpenAI's Whisper for speech.
NLP libraries in PythonNext: MLG 019, on the classical NLP algorithms.
This checkpoint between shallow and deep learning lists the essential machine learning resources in order: Andrew Ng's course, Python, scikit-learn and PyTorch, then the textbooks. Also covers math study, whether you need a PhD, and Kaggle competitions for a portfolio.
LinksIn order, 30 to 45 minutes a day:
The full roadmap is in the resources.
Math and supplementsAdd 15 minutes a day, or one day a week, of linear algebra, statistics and calculus, from Khan Academy (MLG 008). For lighter reading or listening, there's the book The Master Algorithm, plus The Great Courses' Mathematical Decision Making and its statistics and calculus courses, which work as audio.
When to read AIMA and Sutton's Reinforcement LearningLater. Artificial Intelligence: A Modern Approach and Sutton and Barto's Reinforcement Learning cover advanced topics.
Do you need a PhD for a machine learning job?Not for a machine learning engineer job, and maybe not even a master's. A PhD is for research roles at labs like DeepMind and OpenAI. The host got his interviews on a bachelor's in computer science and was turned down for lacking experience and a portfolio (MLG 006).
Kaggle competitions for a portfolioBuild a portfolio with weekend projects, or on Kaggle, where companies post problems they haven't solved and winners get swag, cash up to hundreds of thousands of dollars, or a job. Any entry is a portfolio piece companies look for.
Next: MLG 018, on natural language processing.
Try a walking desk to stay healthy while you study or work!
Full notes at ocdevel.com/mlg/16
Inspiration in AI DevelopmentEarly inspirations for AI development centered around solving challenging problems, but recent advancements like self-driving cars and automated scientific discoveries attract professionals due to potential economic automation and career opportunities.
The SingularityThe singularity suggests exponential technological growth leading to a point where AI and robotics automate all technology development, potentially achieving 'seed AI' capable of self-improvement and escaping human intervention.
Defining ConsciousnessConsciousness distinguishes intelligence by awareness. Perception, self-identity, learning, memory, and awareness might all contribute to consciousness, but awareness or subjective experience (quaia) is viewed as a core component.
Hard vs. Soft Problems of ConsciousnessThe soft problems are those we know through sciences — like brain regions being associated with specific functions. The hard problem, however, is explaining how subjective experience arises from physical processes in the brain.
Theories and DebatesOpinions vary widely on whether AI can achieve consciousness, depending on theories around biological plausibility and arguments like John Searl's Chinese Room. The matter of consciousness remains deeply philosophical, touching on human identity itself. The expansion of machine learning and AI might be humanity's next evolutionary step, potentially culminating in the creation of conscious entities.
Machine learning performance is graded with metrics like accuracy, precision, recall and F1 on held-out data, and improved with regularization against overfitting, tuned hyperparameters and cleaner data. Also covers confusion matrices, bias vs variance, and validation and test sets.
LinksEach algorithm trains by minimizing its own loss function, such as cross-entropy for logistic regression. An evaluation metric is an objective grade that compares algorithms on held-out data. The loss trains; the metric grades.
Accuracy and class imbalanceAccuracy is correct predictions over all predictions. It fails when one class is rare: if 1% of patients have cancer, a model that always answers "no cancer" is 99% accurate and useless.
Confusion matrixA table of predicted against actual classes: true and false positives, true and false negatives. With spam as the positive class, a legitimate email flagged as spam is a false positive, and spam let through is a false negative.
Precision vs recall precision = TP / (TP + FP) recall = TP / (TP + FN)Precision is how many of your positive calls were right; recall, how many actual positives you caught. Raising one usually lowers the other.
An F-score combines precision and recall into one number. F1, their harmonic mean, is the balanced one; F2 weights recall more.
F1 = 2 × precision × recall / (precision + recall) Fβ = (1 + β²) × precision × recall / (β² × precision + recall) Training, validation and test setsSplit the data, for example 60/20/20:
One fixed split like this is a hold-out split. k-fold cross-validation instead divides the training data into k folds, trains k times holding out a different fold each time, and averages the scores.
Parameters vs hyperparametersThe algorithm learns its parameters; you set its hyperparameters, such as polynomial degree, or the layers and neurons of a neural network. A bigger network needs more data and compute, so use the smallest that does the job. MLG 027 goes deeper.
Overfitting vs underfitting (bias and variance)Aim for the simplest model that fits.
RegularizationRegularization reduces overfitting. It adds a penalty on large weights to the loss, which shrinks terms like high-degree polynomials, trading a little bias for less variance; too strong a penalty underfits. With an L2 penalty on linear regression, where λ is a hyperparameter:
J(θ) = cost(θ) + λ × Σ θj² Other ways to improve performanceNext: MLG 016, on consciousness.
Anomaly detection, recommender systems and Markov chains end the shallow learning series: anomaly detection flags outliers on a bell curve, recommenders predict ratings, and Markov chains model state transitions. Also covers content vs collaborative filtering, and Monte Carlo simulation vs MCMC.
LinksFinding the rare example that doesn't fit, such as a fraudulent credit card charge or a misbehaving server: fit a bell curve to normal behavior and flag whatever lands far out in its tails.
The normal distribution (bell curve)Also called the Gaussian distribution. Its mean sets the center and its standard deviation the width. Not all data is normal: house prices are right-skewed, so a log-normal fits them better.
How the anomaly detection algorithm worksBoth predict a user's rating of an item, as linear regression predicts a house price (MLG 005).
Production recommenders blend both, now mostly with deep learning.
Recommender systems vs market basket analysisA recommender suggests a substitute: you liked a Hershey bar, try a Kit Kat. Market basket analysis (Apriori, MLG 012) suggests a complement: marshmallows and graham crackers go with chocolate.
What is a Markov chain?A probabilistic model of a process: states joined by arrows, each carrying a transition probability. Under the Markov property the next state depends only on the current one, because the current state (a player's level, position and velocity) sums up whatever in the past still matters. Arrows can loop back, so a chain is a graph, not a tree. It is stored as a transition matrix, with probabilities counted from observed transitions.
A restaurant, from The Great Courses' Mathematical Decision Making (Lecture 21):
enter → wait for a table (50% stay, 50% get seated) → decide → order → wait for food → …
The likelier a state loops back to itself, the longer people wait there: a bottleneck.
A Markov chain is a model, not a learning algorithm. Reinforcement learning (MLG 029) builds on Markov decision processes, which add actions and rewards.
Monte Carlo simulation vs MCMCWhen a question about a chain, like a player's expected final score, is too complex for a formula, run the process many times, picking each next state at random by its probabilities, and average the outcomes. That is Monte Carlo simulation.
Markov chain Monte Carlo (MCMC) samples from a distribution too hard to sample directly, by running a Markov chain whose long-run distribution is that target. Metropolis–Hastings is the classic algorithm.
Where to learn anomaly detection and recommendersCourse 3 of Andrew Ng's Machine Learning Specialization: anomaly detection in week 1, collaborative filtering and a deep learning version of content-based filtering in week 2.
Next: MLG 015, on measuring and improving performance.