Skip to content

Concepts, Reasoning and Language

Human thought does far more than classify pixels or predict the next word. It carves reality into flexible concepts, combines them productively into infinite new ideas, and toggles between swift intuition and deliberate reasoning across conceptual representations, compositional thought, analogy, logic, dual-process cognition, biases, and Bayesian program induction.

How Minds Carve Reality into Concepts

  • Picture walking into an unfamiliar café. Within a fraction of a second, you spot a wooden bar stool, a sagging velvet armchair, a folding metal patio seat, and even a sturdy upturned crate, and you effortlessly recognise every single one as something you can sit on. Yet if someone hands you a pen and asks for an airtight dictionary definition of "chair" that includes every chair in existence and excludes every table, bench, and tree stump, you quickly get stuck.

  • This everyday puzzle is the starting point for the cognitive science of concepts, the mental building blocks that let us group infinitely varied experiences into reusable categories so we can generalise past knowledge to brand-new objects.

The Classical View and Why It Breaks

  • For over two thousand years, from Aristotle through early symbolic AI, the dominant model was the classical (definitional) view, which treats every concept as a crisp checklist of necessary and sufficient conditions. A "bachelor" is an unmarried adult male, and a "triangle" is a closed three-sided polygon. Under this view, membership is strictly binary. Either an object ticks every box or it does not, and all members count as equally good examples of the category.

  • In the 1950s, Ludwig Wittgenstein dismantled this neat picture with a deceptively simple question. What is a game? Chess has winners and boards, solitaire has no opponent, ring-a-ring-o'-roses has no score, Olympic sprinting has no ball, and a child bouncing a ball against a wall has no rules. No single feature is shared by all games. Instead, they form a criss-crossing network of overlapping similarities that Wittgenstein called family resemblance.

  • Everyday concepts also break binary membership in two glaring ways. First, they have fuzzy boundaries (is a beanbag a chair, and is a tomato a fruit or a vegetable?). Second, they show strong typicality gradients. People consistently judge a robin to be "more bird-like" than a penguin or an ostrich, verify "a robin is a bird" hundreds of milliseconds faster than "a penguin is a bird", and generalise new facts ("robins carry disease X") far more readily from typical members to the whole category.

Prototype Theory and Category Centroids

  • Think of meeting fifty golden retrievers over your life and gradually forming a blended mental composite of the "average dog" in your head. In the 1970s, Eleanor Rosch formalised this intuition as Prototype Theory, where a category \(C\) is represented not by rigid rules, but by a single central summary vector called its prototype \(\boldsymbol{\mu}_c\). Mathematically, this is the centroid (mean) of observed category members in a \(D\)-dimensional feature space, connecting directly to vectors and norms in Chapter 01 and \(k\)-means clustering in Chapter 06.
\[\boldsymbol{\mu}_c = \frac{1}{|C|} \sum_{\mathbf{x}_i \in C} \mathbf{x}_i\]
  • Here \(\mathbf{x}_i \in \mathbb{R}^D\) is the feature vector of the \(i\)-th observed member of category \(C\), and \(|C|\) is the number of members. When a new stimulus \(\mathbf{x}\) arrives, you measure its distance \(\|\mathbf{x} - \boldsymbol{\mu}_c\|\) to each category prototype and assign it to the nearest one. Typicality falls out naturally, because robins sit close to the avian centroid \(\boldsymbol{\mu}_{\text{bird}}\), while penguins sit far out in the tails.

  • Rosch also discovered basic-level categories. In a taxonomic hierarchy from animal (superordinate) to dog (basic) to border collie (subordinate), humans overwhelmingly prefer the middle level when naming objects, teaching toddlers, and organising memory. Basic-level categories sit at the information-theoretic sweet spot, maximising similarity within the category while maximising distinctiveness from neighbouring categories.

Exemplar Theory and Stored Instances

  • Now imagine trying to classify a penguin using only a single average bird prototype. Because a penguin is large, flightless, and swims, it may actually sit closer to the prototype of "seal" than to the prototype of "flying songbird"! Exemplar Theory, pioneered by Douglas Medin, Marguerite Schaffer, and Robert Nosofsky's Generalised Context Model (GCM), takes the opposite bet. Instead of compressing experiences into one summary prototype, the mind retains rich traces of specific remembered instances \(\{\mathbf{e}_1, \mathbf{e}_2, \ldots, \mathbf{e}_N\}\).

  • Picture a new creature \(\mathbf{x}\) walking up to you. You compare it simultaneously against every stored exemplar \(\mathbf{e}_i\) in memory using a weighted distance metric and an exponentially decaying similarity kernel.

\[d_{\mathbf{w}}(\mathbf{x}, \mathbf{e}_i) = \left( \sum_{k=1}^{D} w_k \, |x_k - e_{ik}|^r \right)^{1/r}, \qquad s(\mathbf{x}, \mathbf{e}_i) = \exp\!\left(-c \, d_{\mathbf{w}}(\mathbf{x}, \mathbf{e}_i)\right)\]
  • Every symbol plays a clear psychological role. The selective attention weights \(w_k \ge 0\) (with \(\sum_k w_k = 1\)) stretch dimensions relevant to the task and shrink irrelevant ones. The exponent \(r\) sets the geometry (\(r = 1\) for separable dimensions like colour and shape, and \(r = 2\) for Euclidean distance on integral dimensions, from Chapter 01), while \(c > 0\) is a specificity parameter controlling how rapidly similarity drops with distance. The probability of assigning \(\mathbf{x}\) to category \(C\) is simply the normalised sum of similarities to category-\(C\) exemplars.
\[P(C \mid \mathbf{x}) = \frac{\sum_{i \in C} s(\mathbf{x}, \mathbf{e}_i)}{\sum_{j=1}^{N} s(\mathbf{x}, \mathbf{e}_j)}\]
  • Notice how closely this mirrors machine learning. Prototype Theory behaves like a nearest-centroid linear classifier, whereas Exemplar Theory is a kernel-weighted \(k\)-nearest-neighbours classifier (Chapter 06). It even resembles the soft key-value retrieval of Transformer attention (Chapter 07), where a query attends over stored memory keys weighted by exponentiated similarity!

Comparison of Prototype Theory and Exemplar Theory in a 2D feature space

  • Which theory is right? Decades of experiments suggest the brain runs both, echoing the complementary learning systems from earlier in Chapter 11. Early in learning, or for irregular bimodal categories (like "animals that fly", which spans birds, bats, and bees), stored exemplars shine by carving curved, non-linear boundaries. After massive repetition, cortical abstraction distils compact prototypes for lightning-fast recognition.

Theory-Theory and Causal Concepts

  • Imagine a mad scientist painting white stripes onto a raccoon, fitting it with a pouch of foul-smelling liquid, and teaching it to waddle like a skunk. On every surface feature (colour, smell, and gait), it now sits dead centre in the "skunk" cluster. Yet when Frank Keil asked young children what animal it really was, they insisted it was still a raccoon!

  • This reveals the limits of pure feature similarity. According to the Theory-Theory of concepts (championed by Susan Carey, Alison Gopnik, and Frank Keil), human concepts live inside intuitive causal theories of how the world works, spanning naive physics, naive biology, and naive psychology. We exhibit psychological essentialism, treating natural kinds as defined by hidden internal causes (DNA, developmental origin, internal structure) that generate the observable surface features, rather than as mere bags of correlated pixels.

Conceptual Spaces and Meaning Geometry

  • Picture a colour spindle where hue wraps around a circle, saturation runs radially outward, and brightness runs bottom to top. Peter Gärdenfors proposed Conceptual Spaces as a geometric bridge between low-level neural representations and high-level symbols, defining natural concepts as convex regions carved out of continuous quality dimensions.

  • A region \(C\) is convex if, whenever two points \(\mathbf{x}, \mathbf{y} \in C\), every weighted blend on the line segment between them also lies in \(C\).

\[\lambda \mathbf{x} + (1 - \lambda)\mathbf{y} \in C \qquad \text{for all } \lambda \in [0, 1]\]
  • If two colours both count as "red", then any intermediate shade between them also counts as "red", which is why natural colour categories form clean convex Voronoi cells around prototypes. In modern AI, this geometry reappears directly in semantic vector embeddings (Chapter 01 and Chapter 07), where concepts occupy smooth manifolds in high-dimensional space, directions encode attributes, and linear interpolation glides smoothly between meanings.

Compositionality, Productivity and Systematicity

  • Imagine hearing the sentence "the purple giraffe rode a unicycle across the frozen harbour" for the very first time in your life. You have almost certainly never seen that image or heard those words strung together before, yet within a heartbeat a vivid mental movie plays in your head. How?

  • The answer is compositionality (introduced in Chapter 07's compositional semantics), where the meaning of a complex thought or sentence is systematically built from the meanings of its constituent concepts and the syntactic rules combining them. Compositionality unlocks two defining superpowers of human cognition.

  • Productivity allows a mind to generate and understand an effectively infinite number of novel thoughts from a finite vocabulary (tens of thousands of words) and a compact set of grammatical rules.

  • Systematicity means cognitive abilities arrive in structured clusters rather than isolated coincidences. Anyone who can entertain the thought "the dog chased the postman" can automatically entertain "the postman chased the dog", swapping the agent and patient fillers in the same relational frame with zero extra training.

  • In 1988, Jerry Fodor and Zenon Pylyshyn threw down a famous gauntlet to neural network researchers. Classical symbolic systems get productivity and systematicity for free through explicit variable binding (filling slots like CHASE(agent=X, patient=Y)), whereas early distributed neural networks struggled with the superposition catastrophe, where activating {red, blue, square, circle} simultaneously blurs which colour belongs to which shape.

  • Modern Transformers (Chapter 07) make dramatic strides past early connectionism by using positional encodings and multi-head self-attention to route bindings dynamically across tokens. Even so, rigorous out-of-distribution compositional generalisation, recombining known primitives into unseen depths or unfamiliar role swaps, remains one of the sharpest diagnostic tests separating true systematic understanding from statistical memorisation.

Analogical Reasoning and Structure-Mapping

  • Think of how physics teachers explain an electric circuit by comparing it to water flowing through pipes. Voltage behaves like water pressure, current behaves like flow rate, and a resistor behaves like a narrow pinch in the pipe. Notice that electrons are nothing like water molecules on the surface (they are not wet, blue, or drinkable!), yet the comparison immediately unlocks deep predictions about parallel and series circuits.

  • Dedre Gentner's Structure-Mapping Theory (SMT) explains why analogy is the engine of scientific insight and rapid transfer. Analogy is not about matching isolated surface attributes like colour or size. Instead, it aligns relational structure between a familiar base domain and an unfamiliar target domain, producing three distinct kinds of comparison.

  • Mere appearance shares surface attributes only (a round red apple and a round red billiard ball), which is shallow and unhelpful for inference.

  • Literal similarity shares both surface attributes and underlying relations (two different solar systems).
  • True analogy shares deep relational structure despite wildly different surface objects (the solar system and the Rutherford model of the atom).

  • Gentner's systematicity principle adds a crucial twist. When multiple alignments are possible, human minds strongly prefer mappings that preserve higher-order causal relations, meaning relations that connect other relations together.

\[\text{CAUSE}\!\Big(\text{ATTRACT}(\text{sun}, \text{planet}),\; \text{REVOLVE\_AROUND}(\text{planet}, \text{sun})\Big)\]
  • Once the causal skeleton aligns, you can project candidate inferences from base to target automatically ("if planets orbit because of a central force, maybe electrons orbit the nucleus because of electrical attraction!"). For AI, relational structure-mapping explains why humans transfer across domains in a single shot while purely associative models often get fooled by superficial texture or wording cues.

Deductive, Inductive and Abductive Reasoning

  • Picture waking up, pulling back the curtains, and spotting a glistening wet pavement outside your flat. Three fundamentally different modes of reasoning operate in everyday thought and scientific discovery.

  • Deduction moves from general rules to guaranteed conclusions ("Whenever it rains, the pavement gets wet; it rained last night; therefore, the pavement is wet"). Valid deduction is truth-preserving, meaning if the premises hold, the conclusion cannot be false.

  • Induction moves from specific observations to general rules ("Every swan I have ever seen on the Thames is white; therefore all swans are white"). Induction is the engine of statistical generalisation (Chapter 04 and Chapter 06), powerful yet always fallible the moment a black swan swims by.
  • Abduction (Charles Sanders Peirce's inference to the best explanation) reasons backwards from a surprising effect to its most plausible hidden cause ("The pavement is wet and commuters are carrying umbrellas, so it probably rained rather than a street-sweeper passing by"). Mathematically, abduction maps straight onto Bayesian posterior inference (Chapter 05), picking the hypothesis \(h\) that maximises \(P(h \mid d) \propto P(d \mid h)\,P(h)\).

The Wason Selection Task and Mental Models

  • Imagine four cards lying on a table showing A, K, 4, and 7. Every card has a letter on one side and a number on the other. Your job is to test the rule "If a card has a vowel on one side (\(p\)), then it has an even number on the other (\(q\))." Which cards must you flip over?

  • Over 80% of university students immediately pick A (\(p\)) and 4 (\(q\)), and get it wrong! Turning over 4 cannot falsify \(p \to q\), because a consonant on the back is completely fine. The logically mandatory cards are A (\(p\), to check for an odd back) and 7 (\(\neg q\), the contrapositive, since a vowel on its back would disprove the rule). People fall into confirmation bias, hunting for supporting instances instead of falsifying counterexamples.

  • Now keep the exact same logical structure (\(p \to q\)) but change the story. Imagine you are a pub bouncer enforcing "If a customer is drinking beer, they must be at least 18." The four cards show Beer, Lemonade, 24, and 16. Suddenly almost everyone effortlessly flips Beer (\(p\)) and 16 (\(\neg q\))!

  • Philip Johnson-Laird's Mental Models Theory explains this striking contrast. Rather than running an internal theorem prover over abstract symbols like \(p \to q\), humans construct concrete, small-scale mental simulations ("models") of situations consistent with the premises and scan them for counterexamples. Familiar social rules make violations vividly easy to simulate, whereas abstract letters overload working memory (earlier in Chapter 11) so we skip representing the \(\neg q\) case altogether.

Dual-Process Theory of Fast Intuition and Slow Deliberation

  • Think of driving home along a route you have commuted for five years. Your hands steer, your foot feathers the brake, and you chat happily with a passenger without a shred of conscious strain. Now picture parallel-parking a hired van into a tight London space in pouring rain. Instantaneously you turn off the radio, ask your passenger to pause, and devote every ounce of conscious effort to mirrors and steering angles.

  • Cognitive psychologists (Jonathan Evans, Keith Stanovich, Richard West, and Daniel Kahneman) organise this contrast into Dual-Process Theory, famously popularised as System 1 and System 2.

  • System 1 (fast intuition) is automatic, parallel, associative, effortless, and largely opaque to introspection. It reads emotional expressions on a face, finishes familiar phrases, spots a friend in a crowd, and instantly outputs \(2 + 2 = 4\).

  • System 2 (slow deliberation) is serial, effortful, rule-guided, consciously inspectable, and tightly throttled by the capacity bottleneck of working memory. It multiplies \(17 \times 24\), checks a legal contract, and crucially monitors and overrides System 1 when an intuitive reflex looks suspicious.

  • Test the two systems on Shane Frederick's famous bat-and-ball puzzle. "A bat and a ball cost £1.10 in total. The bat costs £1.00 more than the ball. How much does the ball cost?" System 1 screams "10p!" before you finish reading, splitting £1.10 neatly into £1.00 and 10p. Only when System 2 steps in to check the algebra, setting \(x + (x + £1.00) = £1.10\) to find \(2x = £0.10\) and \(x = £0.05\), do you catch the slip. The ball costs 5p and the bat costs £1.05.

Dual-Process Cognition comparing System 1 fast intuition and System 2 slow deliberation with LLM forward passes and test-time compute

  • The parallel to modern AI is uncanny, and it has become one of the biggest architectural shifts in machine learning.
  • A single forward pass of a Large Language Model (Chapter 07) behaves remarkably like System 1. It spends a fixed budget of compute per token, draws on vast associative patterns compressed into its neural weights, generates fluent answers instantaneously, and notoriously falls for bat-and-ball style wording traps when forced to answer in one token.
  • Test-time compute, including chain-of-thought scratchpads, self-consistency sampling, step-by-step verifiers, and tree search such as Monte Carlo Tree Search (Chapter 06 and Chapter 07), behaves like System 2. It allocates variable, adaptive serial compute at inference time to decompose hard problems, explore alternatives, check intermediate constraints, and override a tempting but flawed first impulse.

Heuristics, Biases and the Rational Mind

  • Why does System 1 produce predictable errors on probability puzzles? Amos Tversky and Daniel Kahneman showed that intuition relies on fast, frugal rules of thumb called heuristics, shortcuts that work remarkably well in everyday life yet misfire systematically in statistical edge cases.

  • The availability heuristic estimates how likely an event is by how easily vivid examples leap to mind. After watching dramatic news coverage of a shark attack, beachgoers dramatically overestimate shark risk while underestimating far deadlier everyday hazards like car accidents.

  • The representativeness heuristic judges probability by how closely something matches a stereotype or prototype. In the classic Linda problem, participants read about Linda (outspoken, philosophy major, anti-nuclear activist) and routinely rate "Linda is a bank teller and is active in the feminist movement" as more probable than "Linda is a bank teller". This commits the conjunction fallacy, directly violating \(P(A \cap B) \le P(A)\) from Chapter 05!
  • Anchoring and adjustment lets an arbitrary starting number tug subsequent estimates toward it. Even spinning a rigged wheel of fortune before estimating how many African nations sit in the United Nations measurably biases people's guesses, just as a "was £100, now £60" price tag makes £60 feel like a bargain.
  • Base-rate neglect ignores the prior probability \(P(H)\) when interpreting diagnostic evidence \(P(E \mid H)\). Suppose a rare disease affects \(1\) in \(1{,}000\) people and a test has \(99\%\) sensitivity and a \(1\%\) false-positive rate. Even if you test positive, Bayes' theorem (Chapter 05) shows your true probability of being ill is only about \(9\%\), because false alarms among the \(999\) healthy people swamp the single true positive!

Bounded Rationality and Resource-Rational Analysis

  • Reading a catalogue of biases can make humans sound hopelessly irrational. Yet Herbert Simon (bounded rationality), John Anderson (rational analysis), and modern resource-rational cognitive scientists (Thomas Griffiths and Falk Lieder) flip the question on its head. What is optimal for an agent with finite memory, finite time, and a 20-watt metabolic budget?

  • Exact Bayesian inference over combinatorially huge hypothesis spaces is NP-hard. A heuristic like availability or anchoring is not a bug when viewed through metareasoning, which maximises expected decision quality minus the cognitive cost of computation. In fact, many classic "biases" emerge naturally as approximate Bayesian inference algorithms (such as importance sampling with very few samples, or noisy MCMC chains initialised at an anchor).

The Language of Thought and Bayesian Program Induction

  • Still, how does a four-year-old child learn a brand-new concept, such as a novel geometric rule or the meaning of a word like "tufa", from just two or three positive examples, whereas standard deep networks often need thousands?

  • Jerry Fodor proposed the Language of Thought (LoT) hypothesis, arguing that mental representations have a compositional, symbol-like grammar (a "mentalese" built from primitive concepts and combinators). Modern computational cognitive scientists (Joshua Tenenbaum, Noah Goodman, and Brenden Lake) combined this symbolic grammar with probability theory into Bayesian Program Induction.

  • Imagine playing Joshua Tenenbaum's Number Game. I tell you I am thinking of a secret mathematical concept over the integers \(1\) to \(100\), and I give you the example 16. Which other numbers belong? Your mind effortlessly entertains structured hypotheses like powers of 2, even numbers, multiples of 4, and numbers near 16. Given a dataset \(D = \{x_1, \ldots, x_N\}\), you update your beliefs over candidate programs \(h \in \mathcal{H}\) by Bayes' rule (Chapter 05).

\[P(h \mid D) = \frac{P(D \mid h)\,P(h)}{\sum_{h' \in \mathcal{H}} P(D \mid h')\,P(h')}\]
  • Two elegant ingredients make one-shot generalisation work.
  • A simplicity prior \(P(h) \propto \exp(-\beta \, |h|)\) scores hypotheses by their description length \(|h|\) in the Language of Thought (mirroring Occam's razor and Minimum Description Length from Chapter 05), giving short, elegant rules much higher prior probability than convoluted ad-hoc lists.
  • The size principle (strong sampling likelihood) assumes examples are sampled uniformly at random from the true extension \(h_{\text{ext}}\) (of size \(|h_{\text{ext}}|\)), yielding the likelihood below for \(N\) consistent examples.
\[P(D \mid h) = \begin{cases} \dfrac{1}{|h_{\text{ext}}|^N} & \text{if } D \subseteq h_{\text{ext}} \\[6pt] 0 & \text{otherwise} \end{cases}\]
  • Look at the quiet brilliance of that denominator! If you see {16, 8, 2, 64}, both "even numbers" (\(|h_{\text{ext}}| = 50\)) and "powers of 2" (\(|h_{\text{ext}}| = 6\)) are 100% consistent with the data. Yet "powers of 2" assigns \((1/6)^4 \approx 7.7 \times 10^{-4}\), whereas "even numbers" assigns \((1/50)^4 = 1.6 \times 10^{-7}\), nearly 5,000 times less likely! Seeing four powers of two in a row without a single non-power-of-two would be an astonishing coincidence if the true rule were merely "all even numbers". Bayesian program induction therefore tightens automatically to the narrowest simple rule supported by the data, uniting symbolic compositionality with probabilistic reasoning.

Take-Home

  • Concepts are far richer than rigid checklists. Human categories blend compact prototypes (centroids), vivid exemplars (similarity kernels over stored memories), intuitive causal theories, and convex geometric regions in conceptual space.
  • Compositionality is what powers infinite thought. Productivity and systematicity arise when minds bind fillers cleanly to relational roles, offering a sharp diagnostic test for both cognitive theories and modern neural architectures.
  • Analogy aligns deep relations rather than surface paint. Gentner's structure-mapping transfers higher-order causal systems across domains, enabling rapid scientific and everyday generalisation.
  • System 1 and System 2 map directly onto modern AI. Fast associative intuition mirrors a single LLM forward pass, whereas slow, serial deliberation in working memory mirrors adaptive test-time compute such as chain-of-thought, tree search, and verification.
  • Cognitive biases and rapid learning are two sides of resource-rational inference. Frugal heuristics trade statistical perfection for speed under biological limits, while Bayesian program induction over a Language of Thought explains how minds generalise sharply from just a handful of examples.

Coding Tasks (use CoLab or notebook)

  1. Build a Prototype vs Exemplar (GCM) classifier on a 2D synthetic dataset where Category A has two separate subclusters (like flying birds and flightless birds) flanking Category B (small mammals). Compare a Prototype (nearest-centroid) classifier against Nosofsky's Exemplar GCM classifier, visualise both decision boundaries side by side, and print test accuracy.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(42)
    k1, k2, k3 = jax.random.split(key, 3)
    
    # Category A: bimodal (two subclusters); Category B: nestled between them
    cat_a1 = jax.random.normal(k1, (25, 2)) * 0.45 + jnp.array([-1.6, 1.4])
    cat_a2 = jax.random.normal(k2, (25, 2)) * 0.45 + jnp.array([1.6, -1.4])
    cat_a = jnp.concatenate([cat_a1, cat_a2], axis=0)
    cat_b = jax.random.normal(k3, (40, 2)) * 0.55 + jnp.array([0.0, 0.0])
    
    X = jnp.concatenate([cat_a, cat_b], axis=0)
    y = jnp.concatenate([jnp.zeros(len(cat_a)), jnp.ones(len(cat_b))])
    
    # Prototype centroids
    mu_a = jnp.mean(cat_a, axis=0)
    mu_b = jnp.mean(cat_b, axis=0)
    
    def predict_prototype(points):
        d_a = jnp.linalg.norm(points - mu_a, axis=-1)
        d_b = jnp.linalg.norm(points - mu_b, axis=-1)
        return jnp.where(d_b < d_a, 1.0, 0.0)
    
    def predict_exemplar_prob(points, c=2.5):
        # Pairwise Euclidean distance between points (M, 2) and exemplars (N, 2)
        diff = points[:, None, :] - X[None, :, :]
        dists = jnp.sqrt(jnp.sum(diff ** 2, axis=-1) + 1e-12)
        sim = jnp.exp(-c * dists)
        sim_a = jnp.sum(sim * (1.0 - y[None, :]), axis=-1)
        sim_b = jnp.sum(sim * y[None, :], axis=-1)
        return sim_b / (sim_a + sim_b + 1e-12)
    
    acc_proto = float(jnp.mean(predict_prototype(X) == y))
    acc_exemp = float(jnp.mean((predict_exemplar_prob(X) >= 0.5) == y))
    print(f"Prototype accuracy: {acc_proto:.1%} | Exemplar (GCM) accuracy: {acc_exemp:.1%}")
    
    # Visualise decision regions on a 2D grid
    gx = jnp.linspace(-3.2, 3.2, 120)
    gy = jnp.linspace(-3.2, 3.2, 120)
    XX, YY = jnp.meshgrid(gx, gy)
    grid = jnp.stack([XX.ravel(), YY.ravel()], axis=-1)
    
    Z_proto = predict_prototype(grid).reshape(XX.shape)
    Z_exemp = predict_exemplar_prob(grid).reshape(XX.shape)
    
    fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
    for ax, Z, title in [
        (axes[0], Z_proto, f"Prototype Classifier ({acc_proto:.0%})"),
        (axes[1], Z_exemp, f"Exemplar GCM Classifier ({acc_exemp:.0%})"),
    ]:
        ax.contourf(XX, YY, Z, levels=20, cmap="RdBu", alpha=0.25)
        ax.contour(XX, YY, Z, levels=[0.5], colors="#333", linewidths=1.8, linestyles="--")
        ax.scatter(cat_a[:, 0], cat_a[:, 1], color="#3498db", edgecolor="white", label="Category A (bimodal)")
        ax.scatter(cat_b[:, 0], cat_b[:, 1], color="#27ae60", edgecolor="white", label="Category B")
        ax.set_title(title)
        ax.set_xlabel("Feature 1"); ax.set_ylabel("Feature 2")
        ax.legend(fontsize=8)
    
    axes[0].scatter([mu_a[0], mu_b[0]], [mu_a[1], mu_b[1]], marker="*", s=220,
                    c=["#3498db", "#27ae60"], edgecolor="black", zorder=5)
    plt.tight_layout(); plt.show()
    

  2. Implement Bayesian Concept Learning (Tenenbaum's Number Game) over a structured hypothesis space of integer concepts in \(\{1, \ldots, 100\}\) using the size principle and a simplicity prior. Watch how the posterior predictive generalisation sharpens dramatically as you observe {16} versus {16, 8, 2, 64}.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    nums = jnp.arange(1, 101)
    
    # Define candidate concepts as binary masks over 1..100 with description lengths
    hypotheses = [
        ("Even numbers",         (nums % 2 == 0),                     1.0),
        ("Odd numbers",          (nums % 2 == 1),                     1.0),
        ("Multiples of 4",       (nums % 4 == 0),                     1.5),
        ("Multiples of 8",       (nums % 8 == 0),                     1.8),
        ("Powers of 2",          jnp.isin(nums, jnp.array([1, 2, 4, 8, 16, 32, 64])), 2.0),
        ("Perfect squares",      jnp.isin(nums, jnp.arange(1, 11) ** 2), 2.0),
        ("All numbers 1..100",   jnp.ones_like(nums, dtype=bool),     0.8),
        ("Interval 10..20",      (nums >= 10) & (nums <= 20),         2.2),
        ("Interval 1..30",       (nums >= 1) & (nums <= 30),          2.2),
        ("Interval 1..70",       (nums >= 1) & (nums <= 70),          2.2),
    ]
    
    names = [h[0] for h in hypotheses]
    masks = jnp.stack([h[1].astype(jnp.float32) for h in hypotheses])  # (H, 100)
    lengths = jnp.array([h[2] for h in hypotheses])
    sizes = jnp.sum(masks, axis=1)
    
    # Simplicity prior P(h) proportional to exp(-beta * |h|)
    beta = 0.6
    log_prior = -beta * lengths
    log_prior = log_prior - jnp.log(jnp.sum(jnp.exp(log_prior)))
    
    def infer_posterior_and_predictive(observed):
        obs_idx = jnp.array(observed) - 1  # 0-based indices
        # Check which hypotheses contain ALL observed examples
        consistent = jnp.all(masks[:, obs_idx] > 0.5, axis=1)
        # Size principle: log P(D | h) = -N * log(|h_ext|) if consistent else -inf
        log_lik = jnp.where(consistent, -len(observed) * jnp.log(sizes), -1e9)
        log_post = log_prior + log_lik
        log_post = log_post - jnp.max(log_post)
        post = jnp.exp(log_post)
        post = post / jnp.sum(post)
        # Predictive probability for every number 1..100: P(x in C | D) = sum_h P(h|D) I(x in h)
        pred = jnp.dot(post, masks)
        return post, pred
    
    datasets = [
        ("After observing {16}", [16]),
        ("After observing {16, 8, 2, 64}", [16, 8, 2, 64]),
    ]
    
    fig, axes = plt.subplots(2, 1, figsize=(11, 6), sharex=True)
    for ax, (title, obs) in zip(axes, datasets):
        post, pred = infer_posterior_and_predictive(obs)
        top_idx = int(jnp.argmax(post))
        print(f"{title} -> Top hypothesis: {names[top_idx]} (posterior={float(post[top_idx]):.3f})")
        ax.bar(nums, pred, color="#3498db", alpha=0.8)
        ax.scatter(obs, [1.03] * len(obs), color="#e74c3c", s=45, zorder=5, label="Observed")
        ax.set_ylim(0, 1.12)
        ax.set_ylabel("P(x in concept | D)")
        ax.set_title(f"{title}  [MAP: {names[top_idx]}, p={float(post[top_idx]):.2f}]")
        ax.grid(alpha=0.25); ax.legend(loc="upper right", fontsize=8)
    
    axes[-1].set_xlabel("Number (1 to 100)")
    plt.tight_layout(); plt.show()
    

  3. Simulate the System 1 vs System 2 test-time compute tradeoff on a multi-step reasoning task where a single System 1 forward pass gets the right answer with modest probability \(p_{\text{correct}} = 0.35\) (spreading errors across distractors). Compare single-shot System 1 against System 2 strategies using \(K \in \{1, 3, 5, 9, 15, 25, 41\}\) test-time samples with majority voting (self-consistency) and a noisy process verifier (best-of-\(K\)), then plot accuracy versus compute budget \(K\).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(7)
    n_problems = 1000
    # 5 candidate answers: index 0 is correct, indices 1..4 are distractors (1 is a seductive trap!)
    answer_probs = jnp.array([0.35, 0.30, 0.15, 0.12, 0.08])
    cdf = jnp.cumsum(answer_probs)
    
    budgets = [1, 3, 5, 9, 15, 25, 41]
    acc_majority = []
    acc_verifier = []
    
    for K in budgets:
        key, k_samp, k_ver = jax.random.split(key, 3)
        # Sample K answers per problem via inverse CDF (Pyodide-safe, no .at updates)
        u = jax.random.uniform(k_samp, (n_problems, K, 1))
        samples = jnp.minimum(jnp.sum(u > cdf[None, None, :], axis=-1), 4)  # shape (n_problems, K) in 0..4
    
        # (a) Self-consistency (majority vote over the K samples)
        counts = jnp.stack([jnp.sum(samples == c, axis=1) for c in range(5)], axis=1)
        maj_pred = jnp.argmax(counts, axis=1)
        acc_majority.append(float(jnp.mean(maj_pred == 0)))
    
        # (b) Noisy verifier (best-of-K): true answer gets mean score +1.0, wrong gets 0.0, + noise
        true_signal = jnp.where(samples == 0, 1.0, 0.0)
        verifier_scores = true_signal + jax.random.normal(k_ver, (n_problems, K)) * 0.85
        best_idx = jnp.argmax(verifier_scores, axis=1)
        # Gather chosen sample using one-hot mask dot product
        one_hot = (jnp.arange(K)[None, :] == best_idx[:, None]).astype(jnp.int32)
        ver_pred = jnp.sum(samples * one_hot, axis=1)
        acc_verifier.append(float(jnp.mean(ver_pred == 0)))
    
    print(f"System 1 (K=1) accuracy:          {acc_majority[0]:.1%}")
    print(f"System 2 Majority Vote (K=41):    {acc_majority[-1]:.1%}")
    print(f"System 2 Best-of-K Verifier (41): {acc_verifier[-1]:.1%}")
    
    plt.figure(figsize=(8.5, 4.5))
    plt.axhline(acc_majority[0], color="#e74c3c", linestyle=":", linewidth=1.6, label="System 1 (1 forward pass)")
    plt.plot(budgets, acc_majority, "o-", color="#3498db", linewidth=2, label="System 2: Majority Vote (Self-Consistency)")
    plt.plot(budgets, acc_verifier, "s-", color="#27ae60", linewidth=2, label="System 2: Best-of-K (Noisy Verifier)")
    plt.xlabel("Test-Time Compute Budget (Number of Samples K)")
    plt.ylabel("Reasoning Accuracy")
    plt.title("Scaling Accuracy with Test-Time Compute: System 1 vs System 2")
    plt.ylim(0.25, 1.02)
    plt.grid(alpha=0.3); plt.legend(); plt.tight_layout(); plt.show()