# Encoder–decoder (autoencoder) diagram in TikZ, explained

> The encoder–decoder (autoencoder) template in TikZ, explained: parameters as macros, computed coordinates, trapezoid paths, and VAE and neuron variations.

URL: https://www.labcanvas.com/tikz/examples/machine-learning/encoder-decoder-template

Updated 2026-11-22. Original figure: Encoder–decoder template, by OpenTikZ contributors, CC0 1.0 (licence text: https://www.labcanvas.com/tikz-library/credits.html#opentikz), from https://github.com/opentikz/opentikz/blob/359befbf8e8af7ce08e7e387b2c2a198e0ca735d/templates/encoder-decoder/template.tex. Walkthrough and variations by LabCanvas; the variation code is CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/). Pictures typeset with TeX Live 2026 and PGF 3.1.12. Category: [TikZ neural network and machine learning examples](https://www.labcanvas.com/tikz/examples/machine-learning).

## Quick answer

This template draws the classic autoencoder picture: an input block, an encoder that narrows to a small latent code z, a decoder that widens again and the reconstructed output x̂, joined by arrows along the centre line. Every size is a macro at the top of the file, and the x positions of all five parts are computed from those sizes with `\pgfmathsetmacro`, so changing one width moves everything after it. The encoder and decoder are closed `\filldraw` paths through four corners, whose narrow end is exactly as tall as the latent block.

## The figure and its code

![Autoencoder diagram: a tall grey input block labelled Input x, a light blue trapezoid labelled Encoder narrowing to the right, a small orange block z, a light green trapezoid labelled Decoder widening to the right, and a tall grey output block labelled Output x hat, with grey arrows between them.](https://www.labcanvas.com/tikz-snippets/fig-encoder-decoder-template/original.webp)

By OpenTikZ contributors, CC0 1.0 (https://www.labcanvas.com/tikz-library/credits.html#opentikz). The code below is exactly the library's file (pdfLaTeX); its first lines name the source and the licence. Open it in the TikZ editor from the page: https://www.labcanvas.com/tikz/examples/machine-learning/encoder-decoder-template

```latex
% Encoder–decoder template
% Source: https://github.com/opentikz/opentikz/blob/359befbf8e8af7ce08e7e387b2c2a198e0ca735d/templates/encoder-decoder/template.tex
% By OpenTikZ contributors, dedicated to the public domain (CC0 1.0).
\documentclass[border=6pt]{standalone}

% --- packages (mirror these in template.meta.json "requires") ---
\usepackage{tikz}
\usetikzlibrary{positioning,arrows.meta}

% --- palette (canonical source: reference/color-palettes/color-palettes.md; light variant) ---
\definecolor{otblue}{HTML}{0072B2}
\definecolor{otorange}{HTML}{E69F00}
\definecolor{otteal}{HTML}{009E73}
\definecolor{otpurple}{HTML}{CC79A7}
\definecolor{otgray}{HTML}{5A5A5A}

\begin{document}
% ==== parameters (edit these) ============================================
\def\blockH{3.0}    % height of the input/output blocks (cm)
\def\latentH{1.1}   % height of the bottleneck z (cm); also the trapezoids' inner edge
\def\trapW{2.6}     % width of the encoder/decoder trapezoids (cm)
\def\blockW{1.0}    % width of the input/output blocks (cm)
\def\latentW{0.9}   % width of the bottleneck z (cm)
\def\gap{0.9}       % horizontal gap between parts (cm)
% labels
\def\inputlabel{Input $x$}
\def\encoderlabel{Encoder}
\def\latentlabel{$z$}
\def\decoderlabel{Decoder}
\def\outputlabel{Output $\hat{x}$}
% =========================================================================

\begin{tikzpicture}[
    >={Stealth[length=2.4mm]},
    ioblock/.style={draw=otgray!60, line width=0.7pt, fill=otgray!12, rounded corners=2pt},
    trap/.style={line width=0.8pt, rounded corners=1.5pt},
    latentblk/.style={draw=otorange!80!black, line width=0.8pt, fill=otorange!22, rounded corners=2pt},
    lbl/.style={font=\sffamily\small},
    flow/.style={draw=otgray!70, line width=0.9pt, ->},
  ]
  \pgfmathsetmacro{\bh}{\blockH/2}
  \pgfmathsetmacro{\lh}{\latentH/2}
  % Running left/right x edges of each part, laid out left to right.
  \pgfmathsetmacro{\xiL}{0}
  \pgfmathsetmacro{\xiR}{\xiL+\blockW}
  \pgfmathsetmacro{\xeL}{\xiR+\gap}
  \pgfmathsetmacro{\xeR}{\xeL+\trapW}
  \pgfmathsetmacro{\xzL}{\xeR+\gap}
  \pgfmathsetmacro{\xzR}{\xzL+\latentW}
  \pgfmathsetmacro{\xdL}{\xzR+\gap}
  \pgfmathsetmacro{\xdR}{\xdL+\trapW}
  \pgfmathsetmacro{\xoL}{\xdR+\gap}
  \pgfmathsetmacro{\xoR}{\xoL+\blockW}
  % Centres (for labels / trapezoid text).
  \pgfmathsetmacro{\xiC}{(\xiL+\xiR)/2}
  \pgfmathsetmacro{\xeC}{(\xeL+\xeR)/2}
  \pgfmathsetmacro{\xzC}{(\xzL+\xzR)/2}
  \pgfmathsetmacro{\xdC}{(\xdL+\xdR)/2}
  \pgfmathsetmacro{\xoC}{(\xoL+\xoR)/2}

  % --- encoder trapezoid: wide (left) -> narrow (right) ---
  \filldraw[trap, fill=otblue!18, draw=otblue!75!black]
    (\xeL,\bh) -- (\xeL,-\bh) -- (\xeR,-\lh) -- (\xeR,\lh) -- cycle;
  \node[lbl] (enc) at (\xeC,0) {\encoderlabel};
  % --- decoder trapezoid: narrow (left) -> wide (right) ---
  \filldraw[trap, fill=otteal!18, draw=otteal!70!black]
    (\xdL,\lh) -- (\xdL,-\lh) -- (\xdR,-\bh) -- (\xdR,\bh) -- cycle;
  \node[lbl] (dec) at (\xdC,0) {\decoderlabel};

  % --- input / output blocks ---
  \node[ioblock, minimum width=\blockW cm, minimum height=\blockH cm] (input)  at (\xiC,0) {};
  \node[ioblock, minimum width=\blockW cm, minimum height=\blockH cm] (output) at (\xoC,0) {};
  \node[lbl, below=3pt of input]  {\inputlabel};
  \node[lbl, below=3pt of output] {\outputlabel};

  % --- latent bottleneck ---
  \node[latentblk, minimum width=\latentW cm, minimum height=\latentH cm] (z) at (\xzC,0) {};
  \node[lbl] at (\xzC,0) {\latentlabel};

  % --- flow arrows along the centre line ---
  \draw[flow] (\xiR,0) -- (\xeL,0);
  \draw[flow] (\xeR,0) -- (\xzL,0);
  \draw[flow] (\xzR,0) -- (\xdL,0);
  \draw[flow] (\xdR,0) -- (\xoL,0);
\end{tikzpicture}
\end{document}
```

## Packages and a colour-blind-safe palette

*Lines 4–15 of the code.*

A `standalone` page with `border=6pt` of white space around the picture, TikZ with two libraries (`positioning` for the labels, `arrows.meta` for the `Stealth` tip) and five named colours. `\definecolor{otblue}{HTML}{0072B2}` defines a colour from its hex code; blue, orange, teal and purple are four colours of the Okabe–Ito palette, chosen so that they stay distinct for readers with colour-vision deficiency, and `otgray` is a dark grey for lines and text.

## Parameters and labels as macros

*Lines 18–31 of the code.*

Everything a user might change is a `\def` at the top: the heights of the input and output blocks (`\blockH`) and of the latent block (`\latentH`), the widths of the trapezoids, blocks and latent code, the gap between parts, and the five labels. The comment on `\latentH` is the important one: the same value is the height of the trapezoids’ narrow ends, so the encoder meets the code block edge to edge. The numbers carry no unit; they are centimetres because the picture’s default unit is 1 cm.

## Styles

*Lines 33–40 of the code.*

`>={Stealth[length=2.4mm]}` makes every `->` end in a Stealth tip 2.4 mm long, the new configurable kind of arrow tip. `ioblock`, `latentblk` and `trap` set line widths, fills and slightly rounded corners, `lbl` sets the sans-serif label font, and `flow` is the grey arrow, with `->` inside the style.

## Coordinates computed from the parameters

*Lines 41–59 of the code.*

`\pgfmathsetmacro{\bh}{\blockH/2}` stores half the block height (1.5) and `\lh` half the latent height, because the shapes are drawn around the centre line y = 0. Then the parts are laid out left to right as running edges: the input runs from `\xiL` = 0 to `\xiR`, the encoder starts one gap later (`\xeL`), and so on through the code, the decoder and the output, each left edge being the previous right edge plus `\gap`. The centres are averages of the edges. Because each value depends on the ones before, widening the encoder moves the code, the decoder and the output along with it.

## Trapezoids as closed paths

*Lines 61–68 of the code.*

The encoder is `(\xeL,\bh) -- (\xeL,-\bh) -- (\xeR,-\lh) -- (\xeR,\lh) -- cycle`: full block height on the left, latent height on the right, closed with `cycle` so that the last corner is joined properly. `\filldraw` fills and strokes it in one command, with a light fill (`fill=otblue!18`) and a darker border (`draw=otblue!75!black`, the blue mixed with 25% black). The decoder is the mirror image. Each label is a separate node at the trapezoid’s centre.

The `shapes.geometric` library has a `trapezium` node shape, but a path through four computed corners is easier to control here: the narrow end matches `\latentH` exactly, whatever the label.

## Blocks, the code and the arrows

*Lines 70–84 of the code.*

The input and output blocks are nodes sized with `minimum width=\blockW cm`: the macro expands to 1.0, so this reads 1.0 cm. Their labels go `below=3pt of input`. The latent block is a node of `\latentW` by `\latentH` at the code’s centre, with its label in a second node at the same point. The four arrows run along y = 0 from each part’s right edge to the next part’s left edge, for example `\draw[flow] (\xiR,0) -- (\xeL,0);`, so they always fill the gaps exactly.

## Techniques used

- [Closed paths: -- cycle and \filldraw](https://www.labcanvas.com/tikz/shapes): the trapezoids are four-corner polygons, filled and stroked in one command.
- [Colours by hex code](https://www.labcanvas.com/tikz/colors): `\definecolor{…}{HTML}{…}`, tints such as `otblue!18` and mixes such as `otblue!75!black`.
- [Computed coordinates](https://www.labcanvas.com/tikz/coordinates): positions from `\pgfmathsetmacro`, so the layout follows the parameters.
- [Arrow tips](https://www.labcanvas.com/tikz/arrows): `>={Stealth[length=2.4mm]}` sets one tip for the whole picture.
- [Neural network diagrams](https://www.labcanvas.com/tikz/neural-networks): encoders, decoders and bottlenecks in machine-learning figures.

## Variations

Our own code, CC0 1.0, each typeset with TeX Live 2026 in a standalone document with the preamble lines shown.

### A variational autoencoder: μ, σ and the sampled z

The variational version replaces the single code by a mean μ and a standard deviation σ and samples z = μ + σ ⊙ ε with noise ε from a standard normal (the reparameterisation trick). The trapezoids are drawn as in the template, as closed paths with fixed corners; μ, σ and z are nodes, and the arrows into the encoder and out of the decoder end at the paths’ edges, `(0,0)` and `(9,0)`.

![Variational autoencoder: a grey input block x, a blue encoder trapezoid, two orange boxes mu and sigma, arrows into a circle z with the formula z = mu + sigma times epsilon above and epsilon ~ N(0, I) below, a teal decoder trapezoid and a grey output block x hat.](https://www.labcanvas.com/tikz-snippets/fig-encoder-decoder-template/vae.webp)

*a variational autoencoder: the encoder outputs μ and σ, z is sampled with ε, the decoder reconstructs x̂*

Preamble: `\usepackage{tikz}`, `\usetikzlibrary{positioning, arrows.meta}`

```latex
\begin{tikzpicture}[
    >={Stealth[length=2.2mm]}, font=\sffamily\small,
    box/.style={draw, rounded corners=2pt, line width=0.7pt, minimum height=7mm, minimum width=9mm},
    flow/.style={->, line width=0.8pt, draw=black!60},
  ]
  % input and output blocks
  \node[box, fill=gray!12, minimum width=8mm, minimum height=28mm] (x) at (-1,0) {};
  \node[below=2pt of x] {$x$};
  \node[box, fill=gray!12, minimum width=8mm, minimum height=28mm] (xh) at (10,0) {};
  \node[below=2pt of xh] {$\hat{x}$};
  % encoder: wide on the left, narrow on the right
  \filldraw[fill=blue!15, draw=blue!60!black, line width=0.8pt, rounded corners=1.5pt]
    (0,1.4) -- (2.4,0.7) -- (2.4,-0.7) -- (0,-1.4) -- cycle;
  \node at (1.2,0) {Encoder};
  % the encoder outputs a mean and a standard deviation
  \node[box, fill=orange!25] (mu) at (3.6,0.55) {$\mu$};
  \node[box, fill=orange!25] (sg) at (3.6,-0.55) {$\sigma$};
  % sampling with the reparameterisation trick
  \node[circle, draw, line width=0.7pt, fill=gray!10, inner sep=1.5pt] (z) at (5.4,0) {$z$};
  \node[below=9mm of z] (eps) {$\varepsilon \sim \mathcal{N}(0, I)$};
  \node[above=4mm of z, font=\footnotesize] {$z = \mu + \sigma \odot \varepsilon$};
  % decoder: narrow on the left, wide on the right
  \filldraw[fill=teal!15, draw=teal!60!black, line width=0.8pt, rounded corners=1.5pt]
    (6.6,0.7) -- (9,1.4) -- (9,-1.4) -- (6.6,-0.7) -- cycle;
  \node at (7.8,0) {Decoder};
  \draw[flow] (x) -- (0,0);
  \draw[flow] (2.4,0.55) -- (mu);
  \draw[flow] (2.4,-0.55) -- (sg);
  \draw[flow] (mu) -- (z);
  \draw[flow] (sg) -- (z);
  \draw[flow] (eps) -- (z);
  \draw[flow] (z) -- (6.6,0);
  \draw[flow] (9,0) -- (xh);
\end{tikzpicture}
```

### The same idea drawn as layers of neurons

Some papers draw the autoencoder as a small network whose middle layer is the narrowest. The layer sizes are one pgfmath array, `{5,3,2,3,5}`, every layer is centred vertically, `\ifcase\l` picks a colour per layer, and a nested loop connects each layer to the next.

![A network of five layers with 5, 3, 2, 3 and 5 neurons: grey input, blue encoder, two orange code neurons, teal decoder and grey output, every neuron connected by grey lines to every neuron of the next layer, labelled input x, encoder, code z, decoder, output x hat.](https://www.labcanvas.com/tikz-snippets/fig-encoder-decoder-template/neurons.webp)

*an autoencoder as a 5–3–2–3–5 network, the two-neuron code layer in orange*

Preamble: `\usepackage{tikz}`

```latex
\begin{tikzpicture}[
    x=1.6cm, y=0.8cm, font=\sffamily\small,
    neuron/.style={circle, draw, thick, fill=#1, minimum size=5.5mm, inner sep=0pt},
  ]
  \def\sizes{{5,3,2,3,5}}  % the bottleneck is the narrow layer in the middle
  \foreach \l in {0,...,4} {
    \pgfmathtruncatemacro\n{\sizes[\l]}
    \ifcase\l \def\col{gray!15}\or\def\col{blue!15}\or\def\col{orange!35}\or\def\col{teal!15}\or\def\col{gray!15}\fi
    \foreach \i in {1,...,\n}
      \node[neuron=\col] (n\l-\i) at (\l, {(\n+1)/2 - \i}) {};
  }
  \foreach \l in {0,...,3} {
    \pgfmathtruncatemacro\nxt{\l+1}
    \pgfmathtruncatemacro\na{\sizes[\l]}
    \pgfmathtruncatemacro\nb{\sizes[\nxt]}
    \foreach \i in {1,...,\na}
      \foreach \j in {1,...,\nb}
        \draw[gray] (n\l-\i) -- (n\nxt-\j);
  }
  \foreach \t [count=\l from 0] in {input $x$, encoder, code $z$, decoder, output $\hat{x}$}
    \node at (\l, -3.2) {\t};
\end{tikzpicture}
```

## Frequently asked questions

### How do I draw an autoencoder in TikZ?

Draw the encoder and decoder as trapezoids with \filldraw and four corners, for example (0,1.5) -- (0,-1.5) -- (2.6,-0.55) -- (2.6,0.55) -- cycle, put a small node for the code z between them and join the parts with arrows along the centre line. The template on this page does exactly that, with every size as a parameter.

### Can I use the trapezium shape instead of a path?

Yes: \usetikzlibrary{shapes.geometric} gives a trapezium node shape, and shape border rotate=90 or 270 turns it sideways. A path through computed corners is easier when the narrow end must match another block’s height exactly.

### Do I need to credit OpenTikZ?

No. The template is dedicated to the public domain under CC0 1.0, so you can use and change it without conditions; a credit is a courtesy.

## References

- [opentikz/opentikz at commit 359befb: templates/encoder-decoder/template.tex (CC0 1.0)](https://github.com/opentikz/opentikz/blob/359befbf8e8af7ce08e7e387b2c2a198e0ca735d/templates/encoder-decoder/template.tex)
- [PGF/TikZ manual, §14.2 The Line-To Operation (-- cycle)](https://tikz.dev/tikz-paths#sec-14.2)
- [PGF/TikZ manual, §14.5 Rounding Corners](https://tikz.dev/tikz-paths#sec-14.5)
- [PGF/TikZ manual, §15.5 Filling a Path (fill, filldraw)](https://tikz.dev/tikz-actions#sec-15.5)
- [PGF/TikZ manual, §16.5 Reference: Arrow Tips (Stealth)](https://tikz.dev/tikz-arrows#sec-16.5)
- [PGF/TikZ manual, §17.2.3 Common Options (minimum width, minimum height)](https://tikz.dev/tikz-shapes#sec-17.2.3)
- [PGF/TikZ manual, §71.3 Geometric Shapes (trapezium)](https://tikz.dev/library-shapes#sec-71.3)
- [PGF/TikZ manual, §94.1.1 Commands (\pgfmathsetmacro)](https://tikz.dev/math-parsing#sec-94.1.1)
- [xcolor package on CTAN (\definecolor with the HTML model, colour mixing)](https://ctan.org/pkg/xcolor)

## TikZ guides for these techniques

- [TikZ neural network diagrams: perceptron, MLP, CNN, LSTM and transformer](https://www.labcanvas.com/tikz/neural-networks): Neural network diagrams in LaTeX with TikZ: perceptron, MLP from \foreach loops, labelled weights, CNN feature maps, RNN, LSTM, autoencoder, transformer.
- [TikZ shapes: triangles, stars, clouds, cylinders, crosses and braces](https://www.labcanvas.com/tikz/shapes): Every TikZ node shape (shapes.geometric, symbols, misc, arrows) with options: triangle, star, cloud, cylinder, cross, curly braces, and custom styles.
- [TikZ colors: names, mixing, fill, shading and patterns](https://www.labcanvas.com/tikz/colors): TikZ colours with xcolor: every named colour (base and dvipsnames charts), red!30 mixing, custom colours, fill and filldraw, opacity, shading, patterns.
- [TikZ coordinates, paths, \foreach, scopes and styles](https://www.labcanvas.com/tikz/coordinates): TikZ coordinates (polar, relative ++, named, calc, intersections), paths and controls, \foreach loops, scopes, \tikzset styles, decorations and grids.
- [TikZ diagrams: block, cycle, flowchart, tree and more](https://www.labcanvas.com/tikz/diagrams): How to draw diagrams in TikZ: block, cycle, flowchart, tree, graph, timeline, matrix, commutative and circuit diagrams, each with compiled code.
