在犰狳立方体中添加一列 1 的有效方法

Efficient way to add a column of 1s in armadillo Cube

我正在尝试使用 armadillo 线性代数库在 C++ 中实现神经网络。我正在使用 Cube 来存储网络的 inputsweights,我希望能够在 3d 矩阵中添加 bias 单元。我遇到了很多方法来做到这一点,这些方法涉及从立方体到矩阵的对话,这似乎效率低下。那么在立方体中每个矩阵的开头添加一列零的最有效方法是什么?

很遗憾,join_slices, only supports joining cubes with same number of rows and columns. Hence you need to loop through each slice and append a row-vector using insert_rows,像这样:

#include<armadillo>

using namespace arma;

uword nRows = 5;
uword nCols = 3;
uword nSlices = 3;

/*original cube*/
cube A(nRows  , nCols, nSlices, fill::randu);
/*new cube*/
cube B(nRows+1, nCols, nSlices, fill::zeros);
/*row vector to append*/
rowvec Z(nCols, fill::zeros);

/*go through each slice and change mat*/
for (uword i = 0; i < A.n_slices; i++)
{
    mat thisMat = A.slice(i);
    thisMat.insert_rows(0, Z);
    B.slice(i) = thisMat;
}

这应该给出:

A: 
[cube slice 0]
   0.0013   0.1741   0.9885
   0.1933   0.7105   0.1191
   0.5850   0.3040   0.0089
   0.3503   0.0914   0.5317
   0.8228   0.1473   0.6018

[cube slice 1]
   0.1662   0.8760   0.7797
   0.4508   0.9559   0.9968
   0.0571   0.5393   0.6115
   0.7833   0.4621   0.2662
   0.5199   0.8622   0.8401

[cube slice 2]
   0.3759   0.8376   0.5990
   0.6772   0.4849   0.7350
   0.0088   0.7437   0.5724
   0.2759   0.4580   0.1516
   0.5879   0.7444   0.4252


B: 
[cube slice 0]
        0        0        0
   0.0013   0.1741   0.9885
   0.1933   0.7105   0.1191
   0.5850   0.3040   0.0089
   0.3503   0.0914   0.5317
   0.8228   0.1473   0.6018

[cube slice 1]
        0        0        0
   0.1662   0.8760   0.7797
   0.4508   0.9559   0.9968
   0.0571   0.5393   0.6115
   0.7833   0.4621   0.2662
   0.5199   0.8622   0.8401

[cube slice 2]
        0        0        0
   0.3759   0.8376   0.5990
   0.6772   0.4849   0.7350
   0.0088   0.7437   0.5724
   0.2759   0.4580   0.1516
   0.5879   0.7444   0.4252