How to add caption for a TikZ picture?

Just include your code in a figure environment. In that way you'll be able to add a caption to it as a normal figure:

\begin{figure}
\centering
\begin{tikzpicture}
<code>
\end{tikzpicture}
\caption{M1} \label{fig:M1}
\end{figure}

This is my solution using an extra node with text, it works pretty well.

\begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,auto]
        \node[state,initial]    (q_1)                           {$q_1$}; 
        \node[state,accepting]  (q_2)   [right=of q_1]          {$q_2$}; 
        \node[state]            (q_3)   [below right=of q_1]    {$q_3$}; 

        \path[->]
        (q_1) edge  [bend left]     node {a}            (q_2)
        (q_1) edge  [loop above]    node {b}            (q_1)
        (q_2) edge  [bend left]     node {a,b}          (q_3)
        (q_3) edge  [bend left]     node {a}            (q_2)
        (q_3) edge  [bend left]     node {b}            (q_1);

        \node [below=1cm, align=flush center,text width=8cm] at (q_3)
        {
            $M_1$
        };
\end{tikzpicture}

I've a similar solution using caption:

\usepackage{caption}  

where in a beamer slide I would add caption via:

\captionof{figure}{\textbf{Confusion Matrix}}

as in:

\begin{frame}[fragile]
\frametitle{Confusion Matrix}
\begin{tikzpicture}[
box/.style={draw,rectangle,minimum size=2cm,text width=1.5cm,align=left}]
\matrix (conmat) [row sep=.1cm,column sep=.1cm] {
\node (tpos) [box,
    label=left:\( \mathbf{p'} \),
    label=above:\( \mathbf{p} \),
    ] {True \\ positive};
&
\node (fneg) [box,
    label=above:\textbf{n},
    label=above right:\textbf{total},
    label=right:\( \mathrm{P}' \)] {False \\ negative};
\\
\node (fpos) [box,
    label=left:\( \mathbf{n'} \),
    label=below left:\textbf{total},
    label=below:P] {False \\ positive};
&
\node (tneg) [box,
    label=right:\( \mathrm{N}' \),
    label=below:N] {True \\ negative};
\\
};
\node [left=.05cm of conmat,text width=1.5cm,align=right] {\textbf{actual \\ value}};
\node [above=.05cm of conmat] {\textbf{prediction outcome}};
\end{tikzpicture}
\captionof{figure}{\textbf{Confusion Matrix}}
\end{frame}

Preview

slide with caption and confusion matrix


Simplified

For readability, without tikz code:

\begin{frame}[fragile]
\frametitle{Confusion Matrix}
\begin{tikzpicture}[
% ... tikz ...
\end{tikzpicture}
\captionof{figure}{\textbf{Confusion Matrix}}
\end{frame}

The confusion matrix code comes from this answer.