简体   繁体   English

动态特征矩阵随机初始化

[英]Dynamic Eigen Matrix Random Initialization

I have a vector<MatrixXf*> called weights.我有一个称为权重的向量<MatrixXf*>。 In the loop, a new MatrixXf is allocated, pointer pushed to the vector, and meant to be initialized to random values.在循环中,分配了一个新的 MatrixXf,将指针推送到向量,并打算初始化为随机值。 However, I want to avoid setRandom() in favor of my He distribution.但是,我想避免 setRandom() 以支持我的 He 分布。

The uncommented code below works as-is, but it feels very clunky to create a 'local' matrix that may be in the stack (or heap, but the class doc is vague) and copy it into my destination matrix.下面未注释的代码按原样工作,但创建一个可能位于堆栈(或堆,但类文档含糊不清)中的“本地”矩阵并将其复制到我的目标矩阵中感觉非常笨拙。 The commented lines are things I've tried before that had no effect (matrix values remained 0).注释行是我之前尝试过的没有影响的东西(矩阵值保持为 0)。

What would be the better solution?更好的解决方案是什么?

    /* context */
    typedef Eigen::MatrixXf Matrix;
    vector<Matrix*> weights;
    random_device rd;
    mt19937 rgen(rd());

    ...

    // Initialize weights (using He)
    if (i > 0) {
        uint p = neurons[i-1]->size();
        uint c = neurons[i]->size();

        normal_distribution<float> dist(0.0, sqrt(2.0/p));
        auto he = [&](){return dist(rgen);};

        // This is what feels clunky
        Matrix m = Eigen::MatrixXf::NullaryExpr(c, p, he);
        weights.push_back(new Matrix(c, p));
        (*weights.back()) = m;

        // This is what I tried before
        //weights.back()->NullaryExpr(weights.back()->rows(), weights.back()->cols(), he);
        //weights.back()->NullaryExpr([&](){return dist(rgen);});
    }

You could use a vector of shared pointers:您可以使用共享指针向量:

#include <memory>
...
vector<shared_ptr<Matrix>> weights;
...
Matrix m = Eigen::MatrixXf::NullaryExpr(c, p, he);
weights.push_back(make_shared<Matrix>(m));

Perhaps one could criticize that this approach is syntactic sugar that doesn't change much in the inner workings of the original "clunky" version.也许有人会批评这种方法是一种语法糖,它在原始“笨拙”版本的内部工作中没有太大变化。 But it obviates the need to use new and to copy afterward the content with *weights.back() .但它避免了使用new并随后使用*weights.back()复制内容的需要。

Of course, this can also be written as a one-liner:当然,这也可以写成一行:

weights.push_back(make_shared<Matrix>(Matrix::NullaryExpr(c, p, he)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM