简体   繁体   中英

Dynamic Eigen Matrix Random Initialization

I have a vector<MatrixXf*> called weights. In the loop, a new MatrixXf is allocated, pointer pushed to the vector, and meant to be initialized to random values. However, I want to avoid setRandom() in favor of my He distribution.

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).

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() .

Of course, this can also be written as a one-liner:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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