[Tex/LaTex] algorithm2e missing $ inserted. $ \caption

algorithm2ealgorithms

I have trouble using package algorithm2e. The following is my latex code:

\begin{algorithm}[H]
\SetAlgoLined
\Comment{Input: Training data S, regularization parameters λ, learning rate η, initialization σ }

\Comment{Output: $\Theta = (w_{0},\textbf{w},\textbf{V})$}
initialization\; 
\While{stopping criterion is not met}{
    \For{\ (x,y) \in S}
    {
        w_{0}\leftarrow w_{0}-$η$(\frac{\partial}{\partialw_{0}}l(y(x|\Theta),y)                                +2\lambda^{0}w_{0});
    }
    \For{\ i \in \{1,...p\}  \wedge x_{i} \neq 0 }
    {
    w_{i}\leftarrow w_{i} - $η$(\frac{\partial}{\partialw_{i}}l(y(x|\Theta),y)+2\lambda_{\pi}^{w}w_{i});
    }
    For{ f \in \{1,...k\} }     
    {
    v_{i,f}\leftarrow v_{i,f}-$η$(\frac{\partial}{\partialv_{i,f}l(y(x|\Theta),y)+2\lambda_{f,\pi(i)}^{v}v_{i,f});
    }
    }
}
 \caption{Stochastic gradient descent}
\end{algorithm}

I met such an error as title, the result should be this, thank you.

enter image description here

Best Answer

The following replicates the expected output:

enter image description here

\documentclass{article}

\usepackage{amsmath}

\usepackage[noline,ruled]{algorithm2e}
\setlength{\algomargin}{7.5pt}

\begin{document}

\begin{algorithm}[H]
 \caption{Stochastic Gradient Descent (SGD)}
  \KwIn{Training data $S$, regularization parameters $\lambda$, learning rate $\eta$, initialization $\sigma$}
  \KwOut{Model parameters $\Theta = (w_0,\mathbf{w},\mathbf{V})$}
  $w_0 \leftarrow 0$; $\mathbf{w} \leftarrow (0,\dots,0)$; $\mathbf{V} \sim \mathcal{N}(0,\sigma)$\; 
  \Repeat{stopping criterion is not met}{
    \For{$(x,y) \in S$}
    {
      $w_0 \leftarrow w_0 - \eta(\frac{\partial}{\partial w_0} l( y(\mathbf{x} \mid \Theta), y) + 2\lambda^0 w_0)$\;
      \For{$i \in \{1,\dots,p\} \wedge x_i \neq 0$}
      {
        $w_i \leftarrow w_i - \eta(\frac{\partial}{\partial w_i} l( y(x \mid \Theta), y) + 2\lambda_{\pi}^w w_i)$\;
        \For{$f \in \{1,\dots,k\}$}     
        {
          $v_{i,f} \leftarrow v_{i,f} - \eta(\frac{\partial}{\partial v_{i,f}} l( y(x \mid \Theta), y) + 2\lambda_{f,\pi(i)}^v v_{i,f})$\;
        }
      }
    }
  }
\end{algorithm}

\end{document}

Some considerations:

  1. Input and output can be specified using \KwIn and \KwOut, respectively.

  2. Math object that should be bold (like vectors) are typically set using \mathbf (or \bm, needs \usepackage{bm} after \usepackage{amsmath}).

  3. Use \repeat rather than \while in order for the loop condition to be specified at the end.

  4. Math mode is required for math-related content. This often goes for unicode input like λ, η and σ.

  5. Use \mid instead of | to provide conditional functionality.

  6. Nest \Fors to have their structure tier in the output.

  7. Use \dots rather than ellipses ... inside math.

Related Question