Categories & Functors
Objects, morphisms, and functors — the abstract language that unifies disparate ML structures through composition
Overview & Motivation
Machine learning is built on composition. A neural network is a sequence of layers applied one after the other. A data pipeline chains transformations end-to-end. A probabilistic model threads random variables through a sequence of conditional distributions. In every case, the structure that matters is not what the individual pieces are but how they compose.
Category theory makes composition the central idea. A category is a collection of objects and morphisms (structure-preserving maps) between them, equipped with a composition operation that satisfies two axioms: associativity and the existence of identities. That’s it — and from these two axioms, an enormous amount of structure follows.
Why should an ML practitioner care? Because the categories that matter to us are the ones we already work in:
- Vec — the category of vector spaces and linear maps. Every neural network layer is a morphism in Vec (or a nonlinear enrichment of it). The Spectral Theorem guarantees that symmetric endomorphisms in Vec have complete eigenbases.
- Meas — the category of measurable spaces and measurable functions. Every random variable is a morphism in Meas. The entire apparatus of measure-theoretic probability is the study of this category’s structure.
- Set — the category of sets and functions. Data transformations, feature maps, and loss functions are all morphisms in Set.
- Top — the category of topological spaces and continuous maps. Topological data analysis works in Top and its subcategories.
The power of category theory is not that it replaces these concrete settings — it is that it reveals the compositional patterns they share. A functor is a structure-preserving map between categories: it takes objects to objects and morphisms to morphisms, preserving composition and identities. The forgetful functor from Vec to Set “forgets” the linear structure and remembers only the underlying set. The adjacency matrix construction is a functor from the category of graphs to Vec. Recognizing these as instances of the same concept — functor — is what lets us transfer techniques across domains.
What we cover:
- Categories — objects, morphisms, composition, identity, and the two axioms.
- A gallery of categories — the concrete categories that ML practitioners work in daily.
- Morphism types — isomorphisms, monomorphisms, epimorphisms, endomorphisms, automorphisms.
- Functors — covariant and contravariant structure-preserving maps between categories.
- Opposite categories, Cat, and endofunctors — the category of categories, duality, and self-maps.
- Products, coproducts, and universal properties — characterizing constructions by what they do.
- The Hom functor — the functor that reframes linear algebra.
- Computational notes — categories and functors in Python, neural networks as categorical composition.
Categories: Objects, Morphisms, and Composition
The central idea is composition. Before we give the formal definition, consider what composition means concretely: if is a function from set to set , and is a function from to , then the composite is the function that first applies , then applies . This composite is associative — — and every set has an identity function that acts as a no-op for composition. A category axiomatizes exactly these two properties.
Definition 1 (Category).
A category consists of:
- A collection of objects.
- For each pair of objects , a set of morphisms (also called arrows) from to . We write to mean .
- For each triple of objects , a composition operation
that sends to .
- For each object , an identity morphism .
These data satisfy two axioms:
- Associativity. For all , , :
- Identity. For every morphism :
The definition requires remarkably little: objects, arrows between them, a way to compose arrows, identity arrows, and two axioms. Notice what it does not require — it says nothing about what objects or morphisms “are” internally. A morphism is not required to be a function, and an object is not required to be a set. This generality is the source of the theory’s power.
Proposition 1 (Uniqueness of Identity).
In any category , the identity morphism on each object is unique.
Proof.
Suppose and are both identity morphisms on object . Then:
The first equality holds because is an identity (so ), and the second holds because is an identity (so ).
∎The following explorer lets you build small categories from scratch and verify the axioms interactively. Try the presets to see how different structures — a simple chain of arrows, a partially ordered set, even a monoid — all satisfy the same two axioms.
Composition table (g ∘ f)
| g ∖ f | id_A | id_B | f |
|---|---|---|---|
| id_A | id_A | — | — |
| id_B | — | id_B | f |
| f | f | — | — |

A Gallery of Categories
The power of the definition comes from the range of examples it encompasses. Here are the categories that ML practitioners encounter regularly. In every case, the pattern is the same: objects are mathematical structures, and morphisms are the maps that preserve that structure.
| Category | Objects | Morphisms | Composition | Identity |
|---|---|---|---|---|
| Set | Sets | Functions | Function composition | Identity function |
| Vec | Real vector spaces | Linear maps | Matrix multiplication | Identity matrix |
| Grp | Groups | Group homomorphisms | Composition of homomorphisms | Identity homomorphism |
| Top | Topological spaces | Continuous maps | Composition | Identity map |
| Meas | Measurable spaces | Measurable functions | Composition | Identity function |
Set is the most familiar category. Its objects are sets, its morphisms are functions between sets, and composition is ordinary function composition. For an ML practitioner, Set is the category of data transformations: feature maps, loss functions, and evaluation metrics are all morphisms in Set.
Vec is the workhorse of machine learning. Its objects are finite-dimensional real vector spaces, and its morphisms are linear maps. Every fully connected neural network layer (before the activation function) is a morphism in Vec — a matrix multiplication . The Spectral Theorem tells us that symmetric endomorphisms in Vec have complete eigenbases — a fact that drives spectral methods throughout ML.
Meas is the category of measure-theoretic probability. Its objects are measurable spaces , and its morphisms are measurable functions. A random variable is a morphism in Meas. Composition of random variables corresponds to chaining probabilistic transformations.
Beyond these standard examples, there are categories built from algebraic structures:
-
Posets as categories. Any partially ordered set defines a category: the objects are the elements of , and there is exactly one morphism from to if and only if . Composition is transitivity: if and , then . The identity morphism on is the reflexivity .
-
Monoids as one-object categories. A monoid — a set with an associative binary operation and an identity element — is a category with a single object . The morphisms are the elements of , composition is the monoid operation , and the identity morphism is . The integers form a one-object category with morphisms
-
Discrete categories. A set with no structure beyond its elements forms a discrete category: the objects are the elements of , and the only morphisms are the identities. Every object is an island.

Morphism Types
Within a category, morphisms have special properties that generalize familiar notions from set theory — injectivity, surjectivity, and bijectivity — to the abstract setting.
Definition 2 (Isomorphism).
A morphism in a category is an isomorphism if there exists a morphism such that:
The morphism is called the inverse of , written . If an isomorphism exists between and , we write .
Proposition 2 (Uniqueness of Inverses).
If is an isomorphism, its inverse is unique.
Proof.
Suppose and are both inverses of . Then:
where we used associativity and the inverse properties.
∎Proposition 3 (Composition of Isomorphisms).
If and are isomorphisms, then is an isomorphism with inverse .
Proof.
We verify both conditions:
So is an isomorphism with inverse .
∎Definition 3 (Monomorphism).
A morphism is a monomorphism (or is monic) if it is left-cancellable: for all morphisms ,
Definition 4 (Epimorphism).
A morphism is an epimorphism (or is epic) if it is right-cancellable: for all morphisms ,
In Set, monomorphisms are exactly injective functions and epimorphisms are exactly surjective functions. But this correspondence does not hold in every category.
Proposition 4 (Every Isomorphism is Mono and Epi).
If is an isomorphism, then is both a monomorphism and an epimorphism.
Proof.
Mono: Suppose . Applying on the left: , so .
Epi: Suppose . Applying on the right: , so .
∎Remark (Mono + Epi ≠ Iso in General).
The converse of Proposition 4 fails in general. The inclusion is both monic and epic in the category Ring of rings and ring homomorphisms, but it is not an isomorphism — there is no ring homomorphism that inverts the inclusion. The categorical notions of “injective” and “surjective” are genuinely more general than their set-theoretic counterparts.
Proposition 5 (Composition of Monomorphisms).
If and are monomorphisms, then is a monomorphism.
Proof.
Suppose for some . By associativity, . Since is monic, . Since is monic, .
∎Definition 5 (Endomorphism and Automorphism).
A morphism (with the same source and target) is an endomorphism. The set of all endomorphisms of is denoted .
An endomorphism that is also an isomorphism is an automorphism. The set of automorphisms forms a group under composition.
In Vec, an endomorphism of is an matrix. An automorphism is an invertible matrix — an element of the general linear group .

Functors: Structure-Preserving Maps Between Categories
If categories are mathematical universes with their own objects and composition laws, then functors are the translations between universes. A functor maps objects to objects and morphisms to morphisms, preserving the composition structure.
Definition 6 (Functor (Covariant)).
A (covariant) functor between categories and consists of:
- A mapping on objects: for each object , an object .
- A mapping on morphisms: for each morphism in , a morphism in .
These mappings satisfy two axioms:
- Preservation of composition. For all composable morphisms and :
- Preservation of identities. For every object :
Definition 7 (Contravariant Functor).
A contravariant functor reverses the direction of morphisms: for each in , the image is in . The composition axiom becomes:
Equivalently, a contravariant functor is a covariant functor .
Key examples:
-
Forgetful functor . Sends each vector space to its underlying set (forgetting the linear structure) and each linear map to the underlying function . This “forgets” the algebraic structure — a vector space is just a set with extra properties, and a linear map is just a function that happens to be linear.
-
Free functor . Sends each set to the free vector space (with basis elements indexed by ) and each function to the linear extension . This “freely adds” linear structure.
-
Power set functor . Sends each set to its power set and each function to the direct image map defined by .
Theorem 1 (Functors Preserve Isomorphisms).
If is a functor and is an isomorphism in , then is an isomorphism in with inverse .
Proof.
Since and , applying :
So is an isomorphism with inverse .
∎The following visualizer shows how functors map objects and morphisms between categories. Select a functor from the dropdown to see the mapping in action — notice how the connecting arrows show which objects and morphisms correspond, and how the axiom verifier confirms that composition and identities are preserved.

Opposite Categories, Cat, and Endofunctors
Definition 8 (Opposite Category).
Given a category , the opposite category has:
- The same objects as .
- Reversed morphisms: for each in , there is a morphism in .
- Reversed composition: if is defined in , then in .
The opposite category is a powerful tool for duality. Every theorem about categories has a dual theorem obtained by replacing with . Under this substitution, source and target swap, monomorphisms become epimorphisms, products become coproducts, and initial objects become terminal objects. We get two theorems for the price of one.
A contravariant functor is the same thing as a covariant functor . This reformulation often simplifies proofs — instead of tracking arrow reversals, we simply work with the opposite category.
The category Cat. Small categories themselves form a category, written Cat:
- Objects: Small categories (those whose objects and morphisms form sets).
- Morphisms: Functors between categories.
- Composition: Functor composition — on objects, on morphisms.
- Identity: The identity functor sending every object and morphism to itself.
Endofunctors. A functor from a category to itself is an endofunctor. Endofunctors can be iterated: , , and so on. The power set functor is an endofunctor.
A functor is:
- Faithful if is injective on each Hom set: for all .
- Full if is surjective on each Hom set: every morphism in is of the form for some in .
- Fully faithful if is bijective on each Hom set. A fully faithful functor is an “embedding” — it identifies with a subcategory of .
The forgetful functor is faithful (distinct linear maps are distinct as functions) but not full (not every function between vector spaces is linear).
Remark (Endofunctors and Monads (Preview)).
An endofunctor equipped with two natural transformations — a unit and a multiplication — satisfying associativity and unit laws is a monad. Monads are the categorical structure underlying probabilistic programming (the Giry monad on Meas), Haskell’s IO, and computational effects more generally. Monads & Comonads develops monads as monoids in the category of endofunctors — the culmination of the Category Theory track.

Products, Coproducts, and Universal Properties
Category theory characterizes mathematical constructions not by what they are made of but by what they do. The tool for this is the universal property: a construction is defined by being the best solution to a particular mapping problem. This is a profound shift in perspective — from internal structure to external relationships.
Definition 9 (Product (Universal Property)).
Let and be objects in a category . A product of and is an object together with morphisms and (called projections) such that for every object and morphisms and , there exists a unique morphism satisfying:
We write .
The word “unique” in the definition is doing all the work. Many objects might come equipped with morphisms to and , but the product is the one through which all such morphisms factor uniquely.
Definition 10 (Coproduct (Universal Property)).
The coproduct is the dual construction. It comes with inclusions and such that for every object and morphisms and , there exists a unique morphism satisfying:
We write .
Proposition 6 (Product Uniqueness).
If and are both products of and , then via a unique isomorphism compatible with the projections.
Proof.
By the universal property of , there is a unique with and . By the universal property of , there is a unique with and . Then satisfies and . But also satisfies these equations, so by uniqueness . Similarly .
∎The concrete meaning of products and coproducts depends on the category:
| Category | Product | Coproduct |
|---|---|---|
| Set | Cartesian product | Disjoint union |
| Vec | Direct sum | Direct sum |
| Grp | Direct product | Free product |
| Top | Product topology | Disjoint union topology |
| Poset | Meet (greatest lower bound) | Join (least upper bound) |
In Vec, the product and coproduct coincide — both are the direct sum. This is a special property of abelian categories.
Definition 11 (Initial and Terminal Objects).
An object is initial if for every object , there exists a unique morphism .
An object is terminal if for every object , there exists a unique morphism .
In Set, the initial object is the empty set (there is exactly one function for any set — the empty function), and the terminal object is any singleton set (for any set , the unique function sends everything to ). In Vec, the zero vector space is both initial and terminal — a zero object.

The Hom Functor
The Hom functor is one of the most important constructions in category theory. It takes two objects and produces their “space of maps” — and this construction is itself functorial.
Definition 12 (Hom Functor).
Let be a locally small category (one where each is a set). Fix an object .
The covariant Hom functor is defined by:
- On objects: .
- On morphisms: given , the map is post-composition: .
The contravariant Hom functor is defined by:
- On objects: .
- On morphisms: given , the map is pre-composition: .
Theorem 2 (Hom is a Bifunctor).
The combined construction is a functor — contravariant in the first argument and covariant in the second. Given morphisms and , the induced map:
sends .
Proof.
We verify functoriality. For identities: , so .
For composition: given , , , :
so .
∎The Hom functor concretizes linear algebra. In Vec, is the space of all linear maps from to — which is isomorphic to , the space of -by- matrices. The covariant Hom functor sends a vector space to the matrix space and sends a linear map to post-composition by — which is matrix multiplication on the left.
A functor is representable if it is naturally isomorphic to for some object . The representing object is unique up to isomorphism. Representable functors are ubiquitous: the functor sending a group to its underlying set is representable (represented by ), and the functor sending a vector space to its dual is represented by the ground field.
The Yoneda Lemma — the deepest result in basic category theory — says that natural transformations from to any functor are in bijection with elements of . We develop the Yoneda Lemma fully in Natural Transformations.

Computational Notes
Categories and functors are not only abstract mathematics — they have direct computational implementations. Here we show how to represent finite categories in Python and verify functorial properties programmatically.
A Python category class. A finite category can be represented as a dictionary of Hom sets with a composition function:
class Category:
"""A finite category with explicit objects, morphisms, and composition."""
def __init__(self, objects, hom, comp_table, identity):
self.objects = objects # list of object labels
self.hom = hom # dict: (A, B) -> list of morphism labels
self.comp_table = comp_table # dict: (g, f) -> g ∘ f label, or absent
self.identity = identity # function: A -> id_A label
def compose(self, g, f):
"""Return g ∘ f if composable, else None."""
return self.comp_table.get((g, f))
# Example: the triangle category {A, B, C}
triangle = Category(
objects=['A', 'B', 'C'],
hom={
('A','A'): ['id_A'], ('B','B'): ['id_B'], ('C','C'): ['id_C'],
('A','B'): ['f'], ('B','C'): ['g'], ('A','C'): ['gf'],
},
comp_table={
('g','f'): 'gf', ('id_B','f'): 'f', ('g','id_B'): 'g',
('id_A','id_A'): 'id_A', ('gf','id_A'): 'gf',
('id_C','gf'): 'gf', ('id_C','g'): 'g', ('f','id_A'): 'f',
('id_B','id_B'): 'id_B', ('id_C','id_C'): 'id_C',
},
identity=lambda A: f'id_{A}',
)
A functor class with axiom verification:
class Functor:
"""A functor F: C -> D with axiom checking."""
def __init__(self, source, target, on_objects, on_morphisms):
self.source = source
self.target = target
self.on_obj = on_objects # dict: src_obj -> tgt_obj
self.on_mor = on_morphisms # dict: src_mor -> tgt_mor
def verify_identities(self):
"""Check F(id_A) = id_{F(A)} for all objects. Returns (ok, violations)."""
violations = []
for A in self.source.objects:
src_id = self.source.identity(A)
tgt_id = self.target.identity(self.on_obj[A])
if self.on_mor[src_id] != tgt_id:
violations.append(A)
return len(violations) == 0, violations
def verify_composition(self):
"""Check F(g ∘ f) = F(g) ∘ F(f) for composable pairs. Returns (ok, violations)."""
violations = []
for g_label in sum(self.source.hom.values(), []):
for f_label in sum(self.source.hom.values(), []):
gf = self.source.compose(g_label, f_label)
if gf is not None:
Fgf = self.on_mor[gf]
Fg_Ff = self.target.compose(self.on_mor[g_label], self.on_mor[f_label])
if Fgf != Fg_Ff:
violations.append((g_label, f_label))
return len(violations) == 0, violations
Neural networks as categorical composition. A feedforward neural network is a sequence of morphisms in (an enrichment of) Vec:
import torch.nn as nn
# A 3-layer network: R^784 → R^256 → R^128 → R^10
# Each layer is a morphism in Vec (before activation)
network = nn.Sequential(
nn.Linear(784, 256), # f: R^784 → R^256
nn.ReLU(),
nn.Linear(256, 128), # g: R^256 → R^128
nn.ReLU(),
nn.Linear(128, 10), # h: R^128 → R^10
)
# The composite h ∘ g ∘ f: R^784 → R^10 is associative
# by construction — (h ∘ g) ∘ f = h ∘ (g ∘ f)
Remark (Neural Networks as Categorical Composition).
Strictly speaking, a ReLU network is not a morphism in Vec because the activation function is nonlinear. The precise categorical setting is the category of smooth manifolds (for differentiable activations) or the category of Lipschitz functions. But the compositional structure — the fact that the whole network is built by composing layers — is the categorical pattern. The linear parts are honest morphisms in Vec, and backpropagation respects the composition via the chain rule: .
The following explorer demonstrates associativity concretely. Select a category — Set, Vec, or Poset — and step through the composition of three morphisms. Both parenthesizations produce the same result, making associativity visceral rather than axiomatic.

Connections & Further Reading
Where this fits
Categories and functors are the foundation of the Category Theory track. Everything that follows builds on the definitions and examples introduced here:
-
Natural Transformations — Natural transformations are morphisms between functors — the next level of abstraction. The Yoneda lemma, which characterizes objects by their morphisms, is the deepest result in basic category theory. Equivariance of neural networks is precisely the naturality condition.
-
Adjunctions — formalizes the free-forgetful pair between Set and Vec as the prototypical adjunction. The unit-counit formulation, Galois connections, RAPL theorem, and connections to Lagrangian duality and attention mechanisms.
-
Monads & Comonads — develops monads as monoids in the category of endofunctors , with the Giry monad providing the categorical foundation of Bayesian probability and the neighborhood comonad unifying GNN message passing — the culmination of the Category Theory track.
Cross-track connections
The language of categories and functors connects to every prior track on formalML:
-
The Spectral Theorem guarantees that symmetric endomorphisms in Vec have complete eigenbases — the eigendecomposition of the graph Laplacian, the covariance matrix in PCA, and the kernel matrix in SVMs all rely on this fact about the category Vec.
-
Measure-Theoretic Probability works in the category Meas of measurable spaces. Random variables are morphisms, and the pushforward of probability measures is a functor.
-
The category of graphs and graph homomorphisms is a concrete example where the adjacency matrix construction is a functor from Graph to Vec.
-
Smooth Manifolds form a category Man where the tangent bundle construction is a functor.
-
Convex Analysis: convex sets and affine maps form a category where products are Cartesian products and the subdifferential is functorial.
Notation summary
| Symbol | Meaning |
|---|---|
| Categories | |
| Objects of | |
| Morphisms from to | |
| A morphism from to | |
| Composition (apply first, then ) | |
| Identity morphism on | |
| Functor from to | |
| Opposite category | |
| Product | |
| Coproduct | |
| Projections | |
| Inclusions | |
| Unique existence | |
| Endomorphisms of | |
| Automorphisms of | |
| is isomorphic to | |
| Named categories | |
| Category of small categories |
Connections
- The category Vec of finite-dimensional vector spaces over R is the primary running example. The Spectral Theorem guarantees that symmetric endomorphisms in Vec have complete eigenbases. Hom(R^m, R^n) = Mat(n x m) illustrates how the Hom functor concretely produces matrix spaces. spectral-theorem
- The category Meas of measurable spaces and measurable functions is the categorical setting for probability theory. Random variables are morphisms in Meas, probability measures are functorial, and conditional expectations are morphisms with specific universal properties. measure-theoretic-probability
- The category Man of smooth manifolds and smooth maps underlies differential geometry. The tangent bundle construction T: Man -> VectBund is a functor. Riemannian geometry studies Man equipped with additional structure (metrics) that must be preserved by morphisms. smooth-manifolds
- Convex sets and affine maps form a category. Products correspond to Cartesian products of convex sets. The subdifferential is functorial: it sends convex functions to set-valued maps in a composition-preserving way. convex-analysis
- Graphs and graph homomorphisms form a category Graph. The adjacency matrix construction is a functor from Graph to Vec. Graph neural networks compose morphisms in a learned category, and message passing is a natural transformation (coming in the next topic). graph-laplacians
References & Further Reading
- book Categories for the Working Mathematician — Mac Lane (1998) The standard graduate reference — Chapters I-IV cover categories, functors, natural transformations, and universal properties
- book Category Theory — Awodey (2010) A more accessible introduction with excellent examples from algebra, topology, and logic
- book Category Theory in Context — Riehl (2016) Modern treatment emphasizing the Yoneda lemma and adjunctions — freely available online
- book An Invitation to Applied Category Theory: Seven Sketches in Compositionality — Fong & Spivak (2019) The applied perspective — connects categories to databases, circuits, and ML pipelines
- paper Category Theory in Machine Learning — Shiebler, Gavranović & Wilson (2021) Survey of categorical methods in ML: functorial learning, categorical probability, gradient-based learning as lenses
- book Category Theory for the Sciences — Spivak (2014) Categories as a modeling language for scientific structures