带有算法的伪代码。使用 varwidth 和 parbox 转义和缩进函数

带有算法的伪代码。使用 varwidth 和 parbox 转义和缩进函数

我正在使用算法包为我的文档创建伪代码。其中一个算法有几行太长,它们太长了,超出了页面的边缘,所以我想在函数和函数的第二部分之间添加一条换行符以缩进,这样它就可以从函数开始的相同缩进处开始。

我在这里找到了这个解决方案:在算法中包含换行符,同时保持缩进。并希望使用 varwidth 和 parbox 的解决方案。所以我在代码中这样做了:

\begin{algorithm}[tbp]
\caption{Bla bla}
\label{alg:traintestdeep}
\begin{algorithmic}[1]% 
\Procedure{train\_test}{$train\_features, test\_features, unlabeled\_features$} \label{imgpix}
    \Statex Returns test results of the deep classifier.

    \State $\mathit{ResNet} \gets load()$ \Comment{ResNet50 weights}
    \State $\mathit{Incep} \gets load()$ \Comment{InceptionV3 weights}
    \State $\mathit{Xcep} \gets load()$ \Comment{Xception weights}

    \State \begin{varwidth}[t]{\linewidth}

    \State {$res\_features \gets ResNet(train\_features,$\par
    \hskip\algorithmicindent $test\_features,unlabeled\_features)$}

    \State {$inc\_features \gets Incep(train\_features,$\par
    \hskip\algorithmicindent $test\_features,unlabeled\_features)$}

    \State {$xcp\_features \gets Xcep(train\_features,$\par
    \hskip\algorithmicindent $test\_features,unlabeled\_features)$}

    \end{varwidth}

    \State {$all\_features \gets concat(res\_features,inc\_features,xcp\_features)$}

    \If{$save\_features = True$} 
        \State {$savef(all\_features)$}
    \EndIf

    \State {$model \gets create\_model()$} \label{alg:model}

    \If {$training = True$}
        \State {$fitted\_model \gets model.fit(all\_features[train], labels)$} \label{alg:fitmodel1}
        \If {$pseudo = True$} 
            \State \begin{varwidth}[t]{\linewidth}

            \State {$newly\_labeled \gets $\par
            \hskip\algorithmicindent $pseudo\_labeling(fitted\_model,all\_features[unlabeled])$} \label{alg:fitmodel2}

            \end{varwidth}

            \State {$fitted\_model \gets fitted\_model.fit(newly\_labeled, labels)$} \label{alg:fitmodel3}
        \EndIf
        \State {$model \gets fitted\_model$}
    \EndIf

    \If {$testing = True$}
        \State {$results \gets fitted\_model(all\_features[test])$}
    \EndIf

    \State\Return $results$

\EndProcedure
\end{algorithmic}
\end{algorithm}

但结果很混乱,如下所示:

在此处输入图片描述

在第 6、7、8 和 18 行,我需要转义并缩进该行。有什么办法可以修复它吗?

答案1

问题出\State在 块内{varwidth}。您可以{varwidth}在不 的情况下更改块\State

\State \begin{varwidth}[t]{\linewidth}

    {$res\_features \gets ResNet(train\_features,$\par
    \hskip\algorithmicindent $test\_features,unlabeled\_features)$}

     {$inc\_features \gets Incep(train\_features,$\par
    \hskip\algorithmicindent $test\_features,unlabeled\_features)$}

     {$xcp\_features \gets Xcep(train\_features,$\par
    \hskip\algorithmicindent $test\_features,unlabeled\_features)$}

\end{varwidth}

在此处输入图片描述

相关内容