[英]Dynamic Eigen Matrix Random Initialization
我有一個稱為權重的向量<MatrixXf*>。 在循環中,分配了一個新的 MatrixXf,將指針推送到向量,並打算初始化為隨機值。 但是,我想避免 setRandom() 以支持我的 He 分布。
下面未注釋的代碼按原樣工作,但創建一個可能位於堆棧(或堆,但類文檔含糊不清)中的“本地”矩陣並將其復制到我的目標矩陣中感覺非常笨拙。 注釋行是我之前嘗試過的沒有影響的東西(矩陣值保持為 0)。
更好的解決方案是什么?
/* 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);});
}
您可以使用共享指針向量:
#include <memory>
...
vector<shared_ptr<Matrix>> weights;
...
Matrix m = Eigen::MatrixXf::NullaryExpr(c, p, he);
weights.push_back(make_shared<Matrix>(m));
也許有人會批評這種方法是一種語法糖,它在原始“笨拙”版本的內部工作中沒有太大變化。 但它避免了使用new
並隨后使用*weights.back()
復制內容的需要。
當然,這也可以寫成一行:
weights.push_back(make_shared<Matrix>(Matrix::NullaryExpr(c, p, he)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.