Izaak Neutelings 的这个页面提供了一些绘制神经网络的代码:https://tikz.net/neural_networks/运行该页面顶部的简单代码可得到以下结果:
\documentclass[border=3pt,tikz]{standalone}
\usepackage{tikz}
\tikzstyle{mynode}=[thick,draw=blue,fill=blue!20,circle,minimum size=22]
\begin{document}
\begin{tikzpicture}[x=2.2cm,y=1.4cm]
\foreach \N [count=\lay,remember={\N as \Nprev (initially 0);}]
in {4,5,5,5,3}{ % loop over layers
\foreach \i [evaluate={\y=\N/2-\i; \x=\lay; \prev=int(\lay-1);}]
in {1,...,\N}{ % loop over nodes
\node[mynode] (N\lay-\i) at (\x,\y) {};
\ifnum\Nprev>0 % connect to previous layer
\foreach \j in {1,...,\Nprev}{ % loop over nodes in previous layer
\draw[thick] (N\prev-\j) -- (N\lay-\i);
}
\fi
}
}
\end{tikzpicture}
\end{document}
这很好,并且可以在tikzpicture
环境中进行修改。但是如何通过参数(例如网络拓扑)来控制结果?
答案1
这是实现此目的的一种方法。基本思路是:
- 移动
tikz
代码到newcommand
NN
- 用合适的参数替换常量
- 包括一些样式,固定箭头形状
这是众多可能的解决方案之一,包括以下@Skillmon 的评论:
\documentclass[border=3pt,tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}% <<< for arrow shapes
\newcommand\NN[6]{% x, y, size, layers, nodeColor, lineColor
% see webpage \tikzstyle{mynode}=[thin,draw=#5,fill=white,circle,minimum size=#3]%
% see comment \tikzset{mynode/.style={thin,draw=#5,fill=white,circle,minimum size=#3}}%
\begin{tikzpicture}[x=#1cm,y=#2cm,
mynode/.style={thin,draw=#5,fill=white,circle,minimum size=#3}]%
\foreach \N [count=\lay,remember={\N as \Nprev (initially 0);}]%
in {#4}{ % loop over layers%
\foreach \i [evaluate={\y=\N/2-\i; \x=\lay; \prev=int(\lay-1);}]%
in {1,...,\N}{ % loop over nodes%
\node[mynode] (N\lay-\i) at (\x,\y) {};%
\ifnum\Nprev>0 % connect to previous layer%
\foreach \j in {1,...,\Nprev}{ % loop over nodes in previous layer
\draw[thin,-{Latex[]}, draw=#6] (N\prev-\j) --(N\lay-\i);%
}%
\fi%
}%
}%
\end{tikzpicture}%
}
\begin{document}
% x, y,size, layers, nodeColor, lineColor
\NN{2}{2}{10}{4,2,5,3,2}{black}{black!50}
\NN{2}{2}{20}{5,4,3,2}{blue}{red!50}
\end{document}
由此产生了两个用于演示的网络: