How can I create an initialization block in an pseudo algorithm block in Latex?

by Dimitris Poulopoulos   Last Updated December 06, 2018 15:23 PM

How can I create the following algorithm block in Latex? I have everything except the init block. How can I create this?

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{algorithm2e}    

\begin{document}

\begin{algorithm}[H]
\DontPrintSemicolon
\SetAlgoLined
\KwData{$D$ = $<u,i,r>$}
\SetKwInOut{Input}{input}\SetKwInOut{Output}{output}
\Input{feat, iters, $\lambda$, $\eta$}
\Output{$A$, $B$}
\For{count $\leftarrow 1$ \KwTo iters}{
    $D \leftarrow$ Shuffle($D$) \;
    \For{$<u,i,r> \in D$}{
        $err_{ui} \leftarrow r - A_uB_i^T$ \;
        $A_u \leftarrow A_u + \eta(err_{ui}B_i - \lambda A_u)$ \;
        $B_i \leftarrow B_i + \eta(err_{ui}A_u - \lambda B_i)$ \;
    }
}
\caption{Stochastic Gradient Descent}
\end{algorithm}

\end{document}

Algorithm example

Is there an online editor/generator for algorithm blocks in Latex?



Answers 1


You can use \SetKwProg to create your own block:

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{algorithm2e}    
\SetKwProg{Init}{init}{}{}
\begin{document}

\begin{algorithm}[H]
\DontPrintSemicolon
\SetAlgoLined
\KwData{$D$ = $<u,i,r>$}
\SetKwInOut{Input}{input}\SetKwInOut{Output}{output}
\Input{feat, iters, $\lambda$, $\eta$}
\Output{$A$, $B$}
\init{
\For{$u \in Users(D)$}{
    $A_u \leftarrow$ Vector(size: $feat)
}
\For{count $\leftarrow 1$ \KwTo iters}{
    $D \leftarrow$ Shuffle($D$) \;
    \For{$<u,i,r> \in D$}{
        $err_{ui} \leftarrow r - A_uB_i^T$ \;
        $A_u \leftarrow A_u + \eta(err_{ui}B_i - \lambda A_u)$ \;
        $B_i \leftarrow B_i + \eta(err_{ui}A_u - \lambda B_i)$ \;
    }
}
\caption{Stochastic Gradient Descent}
\end{algorithm}

\end{document}
Romain Picot
Romain Picot
December 06, 2018 14:47 PM

Related Questions




Continued Algorithm over 2 pages

Updated June 07, 2017 00:23 AM

Writing this algorithm in Latex

Updated October 10, 2017 14:23 PM

Undefined control sequence \WHILE

Updated April 20, 2018 15:23 PM