Machine Learning Guide

Machine Learning Guide

Download on the App Store

All Machine Learning Guide episodes

  • MLG 024 Tech Stack

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/24
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    What does a deep learning framework do?

    It 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 eagerly

    The 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 silicon

    GPU 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.

    • AMD: PyTorch runs on supported AMD GPUs through ROCm.
    • Apple silicon: Macs train on their own GPU through PyTorch's MPS backend, Apple's tensorflow-metal plugin or Apple's MLX, so a Mac works for learning and small models. Official TensorFlow builds have no macOS GPU support of their own.
    • Windows: TensorFlow's GPU support needs WSL2, since native Windows GPU builds ended after TensorFlow 2.10. Ubuntu remains a common choice. MLA 012 covers Docker for machine learning.

    The GTX 1080 Ti from the episode is several generations old. For a laptop, see Laptop for machine learning and gaming.

    Cloud GPUs

    AWS 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 pipeline
    • Source: a CSV, a folder of images, a database such as Postgres, or an API. Quandl, the financial data API from the episode, is now Nasdaq Data Link.
    • pandas (or Polars) loads and cleans it: read_csv, read_sql, and null handling with fillna, ffill, which carries yesterday's price forward over a missing day, and bfill.
    • scikit-learn scales features with StandardScaler (zero mean, unit variance) or MinMaxScaler (a set range, often 0 to 1), and supplies toy data: load_iris ships with it, and fetch_openml downloads MNIST as 'mnist_784'. torchvision and Keras have MNIST loaders too. It also covers the shallow algorithms deep learning frameworks leave out, such as support vector machines, naive Bayes and random forests.
    • NumPy arrays are the hand-off format. PyTorch and TensorFlow accept them and convert their tensors back with .numpy(), but they compute with their own compiled kernels on CPU as well as GPU, not with NumPy. Keep the math inside framework operations so it runs on the GPU.
    App server and job server

    The 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 learning

    Tensorforce is no longer maintained. For deep reinforcement learning, pair Gymnasium environments with Stable-Baselines3 agents.

    Where to learn the stack
    1. Aurélien Géron's Hands-On Machine Learning, the book praised in the episode. The 3rd edition (2022) uses Scikit-Learn, Keras and TensorFlow; the PyTorch edition (2025) switches to PyTorch and Hugging Face.
    2. Andrew Ng's Machine Learning Specialization on Coursera, now taught in Python; the original course the episode mentions used Octave and MATLAB.
    3. Daniel Bourke's Learn PyTorch for Deep Learning, a free online book and video course.

    Next: MLG 025, on convolutional neural networks.

    1 hr
  • MLG 023 Deep NLP 2

    Try a walking desk to stay healthy while you study or work!

    Notes and resources at ocdevel.com/mlg/23

    Neural Network Types in NLP
    • Vanilla Neural Networks (Feedforward Networks):

      • Used for general classification or regression tasks.
      • Examples include predicting housing costs or classifying images as cat, dog, or tree.
    • Convolutional Neural Networks (CNNs):

      • Primarily used for image-related tasks.
    • Recurrent Neural Networks (RNNs):

      • Used for sequence-based tasks such as weather predictions, stock market predictions, and natural language processing.
      • Differ from feedforward networks as they loop back onto previous steps to handle sequences over time.
    Key Concepts and Applications
    • Supervised vs Reinforcement Learning:

      • Supervised learning involves training models using labeled data to learn patterns and create labels autonomously.
      • Reinforcement learning focuses on learning actions to maximize a reward function over time, suitable for tasks like gaming AI but less so for tasks like NLP.
    • Encoder-Decoder Models:

      • These models process entire input sequences before producing output, crucial for tasks like machine translation, where full context is needed before output generation.
      • Transforms sequences to a vector space (encoding) and reconstructs it to another sequence (decoding).
    • Gradient Problems & Solutions:

      • Vanishing and Exploding Gradient Problems occur during training due to backpropagation over time steps, causing information loss or overflow, notably in longer sequences.
      • Long Short-Term Memory (LSTM) Cells solve these by allowing RNNs to retain important information over longer time sequences, effectively mitigating gradient issues.
    LSTM Functionality
    • An LSTM cell replaces traditional neurons in an RNN with complex machinery that regulates information flow.
    • Components within an LSTM cell:
      • Forget Gate: Decides which information to discard from the cell state.
      • Input Gate: Determines which information to update.
      • Output Gate: Controls the output from the cell.
    44 min
  • MLG 022 Deep NLP 1

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/22
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Why deep learning for NLP?

    Words 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 works

    A 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 embeddings

    A 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 GloVe

    word2vec (Mikolov et al., 2013) is a shallow neural network trained to predict context, in one of two forms:

    • Skip-gram predicts the surrounding words from the center word.
    • CBOW (continuous bag of words) predicts the center word from the surrounding words.

    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 embeddings

    To 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 GRU

    A 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 NLP
    1. Andrej Karpathy's The Unreasonable Effectiveness of Recurrent Neural Networks (2015), a visual, conceptual read with character-level LSTM examples.
    2. Stanford's CS224N: NLP with Deep Learning, taught by Christopher Manning, which absorbed Richard Socher's CS224D in 2017. Its latest public lectures on YouTube are from Spring 2024. The lectures lean on slides, so watch rather than listen.
    3. Dan Jurafsky and James H. Martin's Speech and Language Processing, the book from the earlier NLP episodes, free online as a third-edition draft: chapter 5 covers embeddings and chapter 14 RNNs and LSTMs. Manning taught Stanford's earlier NLP lectures with Jurafsky but isn't an author of this book.

    For 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.

    50 min
  • MLG 020 Natural Language Processing 3

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/20
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Classical NLP pipeline

    Text moves through stages, each feeding the next one downstream:

    ingest documents -> clean (tokenize, lowercase, stem/lemmatize, drop stop words) -> POS tagging -> syntax parsing -> goal

    Text 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 grammars

    Syntax 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 NP

    Hand-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 WordNet

    The 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 parsing

    A 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 panel

    A 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 NLP

    For "Who is the prime minister of the United Kingdom?":

    1. TF-IDF and cosine similarity retrieve documents containing the rare query words. Common words like "who" and "the" score low, so they needn't be removed.
    2. TF-IDF narrows each document to a few candidate sentences.
    3. Parse the question, replace the question word ("who") with a blank, and score candidate sentences by how well their parse trees match, in either word order ("_ is the prime minister" or "the prime minister is _").
    4. The question word sets the entity type NER must find: who means a person, when a date.
    5. The answer most sentences agree on wins: in 2017, Theresa May, prime minister from 2016 to 2019.

    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 TextRank
    • TF-IDF: score each sentence by the rare words it carries, take the top few, and drop near-duplicates by cosine similarity.
    • TextRank (Mihalcea and Tarau, 2004): sentences become nodes in a graph, edges carry their similarity, and a PageRank-style ranking picks the most central sentences.
    • Query-based summarization: pick the sentences relevant to a query, such as those that answered the question.

    These 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 translation

    Classical 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 NLP

    The same as MLG 018 and MLG 019:

    1. Speech and Language Processing by Jurafsky and Martin.
    2. Stanford CS224N.
    3. The NLTK book, Natural Language Processing with Python.

    Next: MLG 022, on deep NLP: word embeddings and recurrent neural networks.

    41 min
  • MLG 019 Natural Language Processing 2

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/19
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Classical NLP vs transformers

    Classification 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 stemmer

    Levenshtein 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 models

    An 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 classification

    Naive 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) models

    MaxEnt 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 tagging

    A 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 models
    • Discriminative models learn P(y | x), a decision boundary: logistic regression, MaxEnt, SVMs, neural networks.
    • Generative models learn the joint P(x, y), usually as P(x | y)·P(y), so they can generate data: naive Bayes, HMMs, LDA. They need less training data.
    Topic modeling with LDA

    Latent 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-IDF

    A 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 t

    Dense vectors are learned embeddings: word2vec (MLG 022), then transformer embeddings.

    Cosine similarity vs Euclidean distance vs Jaccard
    • Jaccard: overlap over union.
    • Euclidean: straight-line distance, so a long document on the topic lands far from a short one.
    • Cosine: the angle between vectors, independent of length.

    Search 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 NLP
    1. Speech and Language Processing by Jurafsky and Martin.
    2. Stanford CS224N.
    3. The NLTK book, Natural Language Processing with Python.

    Next: MLG 020, on syntax parsing and the larger NLP tasks.

    1 hr 6 min
  • MLG 018 Natural Language Processing 1

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/18
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    What is natural language processing (NLP)?

    NLP, 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 semantics

    Syntax is structure: parts of speech, phrases, word form. Semantics is meaning, which translation and question answering need.

    Corpus, token and stop words
    • Corpus: a collection of documents. The Penn Treebank is a corpus of parsed, part-of-speech-tagged sentences, mostly Wall Street Journal text.
    • Token: a word, punctuation mark or emoticon. Tokenization splits a document into tokens.
    • Stop words: frequent words like "the" and "of", dropped for keyword search and kept when grammar matters.
    Stemming vs lemmatization

    Both 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 distance

    The 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 parsing
    • Part-of-speech (POS) tagging labels each word noun, verb, adjective and so on.
    • Named entity recognition (NER) pulls out what a task needs. "Add lunch with John to my calendar on May 15th" yields what = lunch, who = John, when = May 15th; intent extraction adds the action.
    • Relationship extraction turns "Steve Jobs co-founded Apple" into cofounded(Steve Jobs, Apple).
    • Syntax tree parsing nests constituents: "the boy with blonde hair" (noun phrase) + "jumped into the water" (verb phrase), down to POS tags.
    NLP applications
    • Classification: spam and sentiment; sarcasm and negation ("not excellent") defeat word counts.
    • Topic modeling: latent Dirichlet allocation (LDA) tags a document with several topics.
    • Search and document similarity: TF-IDF. Kaggle's Quora Question Pairs competition asked for duplicate questions.
    • Natural language understanding: question answering, textual entailment, machine translation.
    • Natural language generation: chatbots, image captioning, summarization.

    LLMs 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 Python
    • NLTK: tokenizers, stemmers, taggers and corpora, for teaching and preprocessing.
    • spaCy: production pipelines (tokens, tags, NER, dependency parses, lemmas), with transformer pipelines since v3.
    • Hugging Face Transformers: pretrained transformer models.
    • Stanza: Stanford's neural Python pipeline, which also wraps the Java CoreNLP.
    • Apache OpenNLP: a maintained Java toolkit.
    Where to learn NLP
    1. Speech and Language Processing by Daniel Jurafsky and James H. Martin; the third-edition draft is free online.
    2. The NLTK book, Natural Language Processing with Python, by Steven Bird, Ewan Klein and Edward Loper: free, shorter and hands-on.
    3. Stanford CS224N, whose YouTube lectures work as audio (convert video to mp3).

    Next: MLG 019, on the classical NLP algorithms.

    58 min
  • MLG 017 Checkpoint

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/17
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Essential machine learning resources, in order

    In order, 30 to 45 minutes a day:

    1. Andrew Ng's Machine Learning Specialization on Coursera, plus his Stanford CS229 lectures, which cover more and work as audio.
    2. Python, from any good book, course or video series (Python picks).
    3. scikit-learn for shallow learning, then PyTorch, now the most used deep learning framework, starting with its tutorials.
    4. The Elements of Statistical Learning and Pattern Recognition and Machine Learning, the theory behind shallow learning, both free as PDFs.
    5. Deep Learning by Goodfellow, Bengio and Courville, free online.

    The full roadmap is in the resources.

    Math and supplements

    Add 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 Learning

    Later. 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 portfolio

    Build 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.

    8 min
  • MLG 016 Consciousness

    Try a walking desk to stay healthy while you study or work!

    Full notes at ocdevel.com/mlg/16

    Inspiration in AI Development

    Early 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 Singularity

    The 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 Consciousness

    Consciousness 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 Consciousness

    The 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 Debates
    • Emergence: Consciousness as an emergent property of intelligence.
    • Computational Theory of Mind (CTM): Any computing device could exhibit consciousness as it processes information.
    • Biological Plausibility vs. Functionalism: Whether AI must biologically resemble brains or just functionally replicate brain output.
    The Future of Artificial Consciousness

    Opinions 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.

    1 hr 15 min
  • MLG 015 Performance

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/15
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Loss function vs evaluation metric

    Each 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 imbalance

    Accuracy 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 matrix

    A 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.

    • Cancer screening wants high recall: a false alarm beats a missed case.
    • A spam filter wants high precision: some spam in the inbox beats a real email in the spam folder.
    F1 and F2 scores

    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 sets

    Split the data, for example 60/20/20:

    1. Training set: the algorithm learns its parameters.
    2. Validation set: the midterm. Check the score, adjust hyperparameters, retrain.
    3. Test set: the final exam, used once at the end.

    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 hyperparameters

    The 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)
    • Underfitting (high bias): the model is too simple, like a straight line through curved data. More data alone won't fix it; a more flexible model or more features will.
    • Overfitting (high variance): the model is too complex, like a polynomial through every training point. It does well in training and fails on new data.

    Aim for the simplest model that fits.

    Regularization

    Regularization 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 performance
    • Collect more data, which helps an overfit model.
    • Fill in missing values.
    • Normalize features, such as bedrooms and distance in feet, to a common scale.
    What to learn next
    1. Finish Andrew Ng's Machine Learning Specialization. Course 1, week 3 covers overfitting and regularization; Course 2, week 3 covers validation and test sets, bias and variance, and precision and recall.
    2. The Deep Learning book by Goodfellow, Bengio and Courville: chapter 5 for these basics, 7 for regularization, 11 for metrics.
    3. Start coding in Python with PyTorch, now the usual first framework.

    Next: MLG 016, on consciousness.

    41 min
  • MLG 014 Shallow Algos 3

    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.

    Links
    • Notes and resources at ocdevel.com/mlg/14
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    What is anomaly detection?

    Finding 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 works
    1. Fit a Gaussian to training data that is almost all normal examples.
    2. Score a new example by its probability p(x) under that fit.
    3. Flag it as an anomaly when p(x) falls below a threshold ε.
    4. Tune ε on a validation set holding labeled anomalies; check it on a test set holding the rest.
    Content filtering vs collaborative filtering

    Both predict a user's rating of an item, as linear regression predicts a house price (MLG 005).

    • Content filtering (similar items): items come with features, and each user gets regression weights learned from their ratings. Pandora's Music Genome Project tags songs by attributes like vocals and genre, and Pandora describes trained musicologists analyzing each song, new releases included.
    • Collaborative filtering (users also liked): items have no features. It learns item features and user weights together from the ratings alone, two regressions in one cost function.

    Production recommenders blend both, now mostly with deep learning.

    Recommender systems vs market basket analysis

    A 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 MCMC

    When 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 recommenders

    Course 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.

    49 min