# Fully connected neural network in TikZ, step by step

> How a fully connected neural network is drawn in TikZ: neurons from \foreach, \vdots on an invisible path, dense arrows, fit boxes, plus two variations.

URL: https://www.labcanvas.com/tikz/examples/machine-learning/fully-connected-network

Updated 2026-11-22. Original figure: Fully connected network, © Fraser Love, MIT licence (licence text: https://www.labcanvas.com/tikz-library/credits.html#nntikz), from https://github.com/fraserlove/nntikz/blob/3dc29cfda3bd18db2d1e73830f95b4d0985e050f/tikz/neural_network.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 figure draws a multilayer perceptron with an input layer x, two hidden layers h (1) and h (2) and an output layer ŷ, every neuron joined to every neuron of the next layer, each layer in a dashed box. The neurons are placed by `\foreach` loops at computed coordinates, the vertical dots sit on an invisible `\path` between two neurons, and the dashed boxes are `fit` nodes. Because the last neuron of each layer has a letter in its name (`first_n`, `second_m`), connecting two layers takes four loops instead of one, which the second variation avoids.

## The figure and its code

![Fully connected neural network: an input layer x 1, x 2, dots, x n; two hidden layers h(1) and h(2) of empty grey circles with dots; an output layer y hat 1, y hat 2, dots, y hat m; arrows from every neuron to every neuron of the next layer, and a dashed rounded box around each layer.](https://www.labcanvas.com/tikz-snippets/fig-fully-connected-network/original.webp)

Copyright (c) 2024 Fraser Love, MIT licence (https://www.labcanvas.com/tikz-library/credits.html#nntikz). The code below is exactly the library's file (pdfLaTeX); its first lines name the source and the licence, and the MIT licence asks that they stay with the code. Open it in the TikZ editor from the page: https://www.labcanvas.com/tikz/examples/machine-learning/fully-connected-network

```latex
% Fully connected network
% Source: https://github.com/fraserlove/nntikz/blob/3dc29cfda3bd18db2d1e73830f95b4d0985e050f/tikz/neural_network.tex
% Copyright (c) 2024 Fraser Love. MIT licence: https://github.com/fraserlove/nntikz/blob/main/LICENSE
% The licence’s copyright and permission notice: https://www.labcanvas.com/tikz-library/credits.html
\documentclass{standalone}

\usepackage{tikz}

\usetikzlibrary{positioning,chains,shapes.geometric,fit,shapes,arrows.meta,calc,backgrounds}

\begin{document}

\begin{tikzpicture}[
    >=LaTeX, % Use default LaTeX arrows
    % Styles
    node/.style={ % Input or output node
        circle,
        minimum width=2.25em,
        draw,
        fill=gray!10,
        thick
    },
    cell/.style={
        rectangle,
        rounded corners=2mm,
        minimum height=2.5em,
        minimum width=2.5em,
        draw,
        thick
    },
    arrow/.style={
        -latex,
        thick
    },
    backprop/.style={ % Backpropagation arrows
        arrow,
        dashed,
        gray
    }
]

    % Input
    \foreach \x in {1,...,2}
        \draw node at (0, -\x*1.25 - 0.625) [node] (first_\x) {$x_\x$};
    \draw node at (0, -5*1.25 + 0.625) [node] (first_n) {$x_n$};
    \path (first_2) -- (first_n) node[pos=0.38, scale=2] {\vdots};

    % Hidden 1
    \foreach \x in {1,...,3}
        \node at (2.5, -\x*1.25) [node] (second_\x){};
    \draw node at (2.5, -5*1.25) [node] (second_m) {};
    \path (second_3) -- (second_m) node[pos=0.38, scale=2] {\vdots};

    % Hidden 2
    \foreach \x in {1,...,3}
        \node at (5, -\x*1.25) [node] (third_\x){};
    \draw node at (5, -5*1.25) [node] (third_m) {};
    \path (third_3) -- (third_m) node[pos=0.38, scale=2] {\vdots};

    % Output
    \foreach \x in {1,...,2}
        \node at (7.5, -\x*1.25 - 0.625) [node] (fourth_\x){$\hat{y}_\x$};
    \draw node at (7.5, -5*1.25 + 0.625) [node] (fourth_k) {$\hat{y}_m$};
    \path (fourth_2) -- (fourth_k) node[pos=0.38, scale=2] {\vdots};

    % Input -> Hidden
    \foreach \i in {1,...,2}
        \foreach \j in {1,...,3}
            \draw [arrow] (first_\i) to (second_\j);
    \foreach \i in {1,...,2}
        \draw [arrow] (first_\i) to (second_m);
    \foreach \i in {1,...,3}
        \draw [arrow] (first_n) to (second_\i);
    \draw [arrow] (first_n) to (second_m);

    % Hidden -> Hidden
    \foreach \i in {1,...,3}
        \foreach \j in {1,...,3}
            \draw [arrow] (second_\i) to (third_\j);
    \foreach \i in {1,...,3}
        \draw [arrow] (second_\i) to (third_m);
    \foreach \i in {1,...,3}
        \draw [arrow] (second_m) to (third_\i);
    \draw [arrow] (second_m) to (third_m);

    % Hidden -> Output
    \foreach \i in {1,...,3}
        \foreach \j in {1,...,2}
            \draw [arrow] (third_\i) to (fourth_\j);
    \foreach \i in {1,...,3}
        \draw [arrow] (third_\i) to (fourth_k);
    \foreach \i in {1,...,2}
        \draw [arrow] (third_m) to (fourth_\i);
    \draw [arrow] (third_m) to (fourth_k);

    % Layer Labels
    \node[above=0.25cm of first_1] (xlabel) {$\mathbf{x}$};
    \node[above=0.25cm of second_1] (h1label) {$\mathbf{h}^{(1)}$};
    \node[above=0.25cm of third_1] (h2label) {$\mathbf{h}^{(2)}$};
    \node[above=0.25cm of fourth_1] (ylabel) {$\hat{\mathbf{y}}$};

    \node[cell, dashed, fit=(first_1) (first_n)] (xbox) {};
    \node[cell, dashed, fit=(second_1) (second_m)] (xbox) {};
    \node[cell, dashed, fit=(third_1) (third_m)] (xbox) {};
    \node[cell, dashed, fit=(fourth_1) (fourth_k)] (xbox) {};
\end{tikzpicture}

\end{document}
```

## Styles for neurons, boxes and arrows

*Lines 13–40 of the code.*

The picture options define `node`, a grey circle at least `minimum width=2.25em` wide, so that every neuron has the same size whether it holds x 1 or nothing; `cell`, a rounded rectangle used later for the dashed layer boxes; and `arrow`, the old `-latex` tip with `thick` lines. `backprop` (dashed grey arrows) is defined but not used; it belongs to the styles this collection shares between figures. Naming a style `node` works because style names and the `\node` command live in different places, but a name such as `neuron` would read better.

## The input layer: a loop, a separate last neuron and the dots

*Lines 42–46 of the code.*

`\foreach \x in {1,...,2}` places x 1 and x 2 at `(0, -\x*1.25 - 0.625)`, that is at y = −1.875 and −3.125: the coordinate is computed from the loop variable, and the 0.625 offset centres this two-plus-one layer against the hidden layers, whose neurons sit at multiples of 1.25. `\draw node at …` draws nothing itself (there is no path to stroke); the circle comes from the `node` style. The last neuron, x n, is placed by hand at y = −5.625.

The dots use an invisible path: `\path (first_2) -- (first_n) node[pos=0.38, scale=2] {\vdots};`. `\path` without `draw` builds the line from x 2 to x n but does not stroke it, and the node is placed 38% of the way along, enlarged with `scale=2`. Why 0.38 and not 0.5? LaTeX’s `\vdots` keeps some empty space above its three dots, so the centre of its box is higher than the dots; placing the box a little nearer x 2 makes the dots themselves look centred. The value was found by eye.

## Hidden and output layers

*Lines 48–64 of the code.*

The two hidden layers repeat the pattern at x = 2.5 and x = 5: three neurons at y = −1.25, −2.5 and −3.75 from `\node at (2.5, -\x*1.25)`, then `second_m` (and `third_m`) at y = −6.25 and the dots between. Their neurons are empty, `{}`, so the circles keep their size only thanks to the minimum width. The output layer mirrors the input layer at x = 7.5 with labels ŷ 1, ŷ 2 and ŷ m; its last node is named `fourth_k` although its label says m, a mismatch that only matters to someone editing the code.

## Forty arrows from twelve loops

*Lines 66–94 of the code.*

Between two layers every neuron is connected to every neuron, which is what a nested loop is for: `\draw [arrow] (first_\i) to (second_\j);` inside loops over `\i` and `\j`. The catch is the last neuron of each layer. Its name ends in a letter, so the loop variables cannot reach it, and each pair of layers needs four blocks: numbered to numbered, numbered to the last neuron, the last neuron to the numbered ones, and the last to the last. That is 12 + 16 + 12 = 40 arrows written as twelve loops and three single lines. Giving the last neuron a number (`first_3`) and only its *label* the letter n reduces the whole section to one nested loop per pair of layers, as in the second variation.

`to` here behaves like `--`: a straight line, ending on both node borders. Its advantage is that options such as `bend left` could be added later without changing the syntax.

## Layer labels and the dashed boxes

*Lines 96–105 of the code.*

The labels go `above=0.25cm of first_1` and so on, 0.25 cm above the top neuron’s border. The dashed boxes are `\node[cell, dashed, fit=(first_1) (first_n)]`: the `fit` library makes each node just large enough to enclose the first and last neuron of its layer, and `cell` rounds its corners. The boxes have no fill, so drawing them last does not hide the arrows. All four are named `xbox`; each one replaces the name of the one before, which is harmless only because nothing refers to them.

## Techniques used

- [Loops with \foreach](https://www.labcanvas.com/tikz/neural-networks): neurons placed at coordinates computed from the loop variable, connections from nested loops.
- [Nodes on an invisible path](https://www.labcanvas.com/tikz/nodes): `\path (a) -- (b) node[pos=0.38]` positions the dots without drawing a line.
- [Fitted frames](https://www.labcanvas.com/tikz/diagrams): `fit=(first_1) (first_n)` draws a box around a whole layer.
- [Arrows between nodes](https://www.labcanvas.com/tikz/arrows): `to` and `--` between named nodes stop at the borders.

## Variations

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

### Any layer sizes from one list

A general network in a dozen lines. The layer sizes are a pgfmath array, `\def\sizes{{3,5,5,2}}`, read with `\sizes[\l]`; each layer is centred vertically with the coordinate `{(\n+1)/2 - \i}`, and the connections are one nested loop per pair of layers. The input and output layers get their own colours through a style with an argument, `neuron=\col`.

![A neural network with 3 green input neurons, two hidden layers of 5 blue neurons and 2 red output neurons, each layer centred vertically, with grey lines from every neuron to every neuron of the next layer and the labels Input, Hidden 1, Hidden 2 and Output on top.](https://www.labcanvas.com/tikz-snippets/fig-fully-connected-network/layer-sizes.webp)

*a 3–5–5–2 network drawn from one array of layer sizes, every layer centred*

Preamble: `\usepackage{tikz}`

```latex
\begin{tikzpicture}[
    x=2.2cm, y=1cm,
    neuron/.style={circle, draw, thick, fill=#1, minimum size=7mm, inner sep=0pt},
  ]
  \def\sizes{{3,5,5,2}}  % neurons per layer (a pgfmath array, indices 0 to 3)
  \foreach \l in {0,...,3} {
    \pgfmathtruncatemacro\n{\sizes[\l]}
    \ifnum\l=0 \def\col{green!20}\else\ifnum\l=3 \def\col{red!20}\else\def\col{blue!12}\fi\fi
    \foreach \i in {1,...,\n}
      \node[neuron=\col] (n\l-\i) at (\l, {(\n+1)/2 - \i}) {};
  }
  % every neuron to every neuron of the next layer
  \foreach \l in {0,...,2} {
    \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, Hidden 1, Hidden 2, Output}
    \node[font=\small] at (\l, 3) {\t};
\end{tikzpicture}
```

### Numeric names, so the loops need no special cases

The look of the original with a different naming scheme: the third neuron of every layer is drawn lower and labelled with a letter, but it is *named* with a number (`n13`, `n23`, `n33`). The connections between the three layers become a single nested loop, and the dots are placed exactly halfway between two neurons with `($(n\l2)!0.5!(n\l3)$)`.

![A three-layer network: input neurons x 1, x 2 and x n, hidden neurons h 1, h 2 and h m, output neurons y hat 1, y hat 2 and y hat k, dots between the second and third neuron of each layer, dashed boxes around the layers labelled x, h and y hat, and arrows from every neuron to every neuron of the next layer.](https://www.labcanvas.com/tikz-snippets/fig-fully-connected-network/numeric-names.webp)

*the same kind of network with numbered node names: one nested loop draws every connection*

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

```latex
\begin{tikzpicture}[
    >={Latex[length=1.6mm]},
    neuron/.style={circle, draw, thick, fill=gray!10, minimum size=2.25em, inner sep=0pt},
    group/.style={draw, dashed, rounded corners=2mm, inner sep=1.5mm},
  ]
  % three neurons per layer; the third is drawn lower and stands for the last one
  \foreach \l/\sym/\nlast in {1/x/n, 2/h/m, 3/\hat{y}/k} {
    \foreach \i/\y in {1/0, 2/-1.25, 3/-3.5} {
      \ifnum\i=3 \def\sub{\nlast}\else\def\sub{\i}\fi
      \node[neuron] (n\l\i) at (2.6*\l, \y) {$\sym_{\sub}$};
    }
    \node at ($(n\l2)!0.5!(n\l3)$) {$\vdots$};
    \node[group, fit=(n\l1) (n\l3)] (box\l) {};
  }
  % with numeric names, all connections are one set of nested loops
  \foreach \l [evaluate=\l as \m using int(\l+1)] in {1,2}
    \foreach \i in {1,2,3}
      \foreach \j in {1,2,3}
        \draw[->] (n\l\i) -- (n\m\j);
  \foreach \l/\t in {1/\mathbf{x}, 2/\mathbf{h}, 3/\hat{\mathbf{y}}}
    \node[above=1mm] at (box\l.north) {$\t$};
\end{tikzpicture}
```

## Frequently asked questions

### How do I draw a neural network in TikZ?

Place the neurons of each layer in a \foreach loop at computed coordinates, give them names that include the layer and the index, and connect two layers with a nested loop over both indices. The layer-sizes variation on this page is a complete, editable example.

### How do I add the vertical dots between neurons?

Put a \vdots node on an invisible path between two neurons: \path (a) -- (b) node[midway] {$\vdots$}; or place it at the calc midpoint ($(a)!0.5!(b)$). Use scale=2 or a larger font if the dots look small.

### How do I draw a box around a layer?

Load the fit library and add \node[draw, dashed, rounded corners, fit=(first) (last)] {}; after the neurons. Without a fill the box can be drawn last; with a fill, put it in a scope with on background layer (backgrounds library).

## References

- [fraserlove/nntikz at commit 3dc29cf: tikz/neural_network.tex (MIT licence)](https://github.com/fraserlove/nntikz/blob/3dc29cfda3bd18db2d1e73830f95b4d0985e050f/tikz/neural_network.tex)
- [PGF/TikZ manual, §13.5.3 The Syntax of Partway Modifiers](https://tikz.dev/tikz-coordinates#sec-13.5.3)
- [PGF/TikZ manual, §14.13 The To Path Operation](https://tikz.dev/tikz-paths#sec-14.13)
- [PGF/TikZ manual, §17.5.3 Advanced Placement Options (positioning)](https://tikz.dev/tikz-shapes#sec-17.5.3)
- [PGF/TikZ manual, §17.8 Placing Nodes on a Line or Curve Explicitly (pos)](https://tikz.dev/tikz-shapes#sec-17.8)
- [PGF/TikZ manual, §17.11 Connecting Nodes: Using Nodes as Coordinates](https://tikz.dev/tikz-shapes#sec-17.11)
- [PGF/TikZ manual, §54 Fitting Library](https://tikz.dev/library-fit)
- [PGF/TikZ manual, §88 Repeating Things: The Foreach Statement (count, evaluate)](https://tikz.dev/pgffor)
- [PGF/TikZ manual, §94.3.8 Miscellaneous Functions (array)](https://tikz.dev/math-parsing#sec-94.3.8)

## 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 nodes: shapes, anchors, positioning and labels](https://www.labcanvas.com/tikz/nodes): How TikZ nodes work: shapes, size (inner sep, minimum size), all anchors, the positioning library (right=of, node distance), labels, pins and scaling.
- [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.
- [TikZ arrows: arrow tips, sizes, curves and labels](https://www.labcanvas.com/tikz/arrows): All TikZ arrow tips in one rendered table, arrows.meta sizing (length, width, scale, open, round), and curved, labelled, thick, block and squiggly arrows.
- [TikZ graphs: drawing networks of vertices and edges](https://www.labcanvas.com/tikz/graphs): Graph theory drawings in TikZ: vertices and edges by hand, directed and weighted graphs, loops, the \graph syntax, K_n and C_n, and automatic layouts.
