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

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

本文关键字:一列 方法 有效 立方体 添加      更新时间:2023-10-16

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

不幸的是,join_slices仅支持连接具有相同行数和列数的多维数据集。因此,您需要遍历每个切片并使用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
相关文章: