0

我正在 Rcpp 中实现潜在狄利克雷分配 (LDA)。在 LDA 中,我们需要处理一个巨大的稀疏矩阵(例如 50 x 3000)。

我决定在 Eigen 中使用 SparseMatrix。但是,由于我需要访问每个单元格,计算成本高昂 .coeffRef会大大减慢我的功能。

有什么方法可以在保持速度的同时使用 SparseMatrix?

我想做的有四个步骤,

  1. 我知道我想访问哪个单元格 (i,j)。
  2. 我想知道单元格 (i,j) 是否为 0。
  3. 如果单元格 (i,j) 不为 0,我想知道它的值。
  4. 在对第 2 步和第 3 步中的值进行一些分析后,我想更新单元格 (i,j)。在这一步中,我可能需要更新原来为 0 的单元格 (i,j)。
#include <iostream>
#include <Eigen/dense>
#include <Eigen/Sparse>
using namespace std;
using namespace Eigen;
typedef Eigen::Triplet<double> T;

int main(){

  Eigen::SparseMatrix<double> spmat;

  // Insert in spmat
  vector<T> tripletList;
  int value;

  tripletList.push_back(T(0,1,1));
  tripletList.push_back(T(0,3,2));
  tripletList.push_back(T(1,5,3));
  tripletList.push_back(T(2,4,4));
  tripletList.push_back(T(4,1,5));
  tripletList.push_back(T(4,5,6));
  spmat.resize(5,7);  // define size
  spmat.setFromTriplets(tripletList.begin(), tripletList.end());

  for(int i=0; i<5; i++){ // I am accessing all cells just to clarify I need to access cell
    for(int j=0; j<7; j++){
      // Check if (i,j) is 0  
      if(spmat.coeffRef(i,j) != 0){
        // Some analysis
        value = spmat.coeffRef(i,j)*2;  // just an example, more complex in the model
      }
      spmat.coeffRef(i,j) += value;  // update (i,j)
    }
  }

  cout << spmat << endl;

  return 0;
}

由于行数远小于列数,我考虑访问一列,然后检查行值,但我无法处理SparseMatrix<double>::InnerIterator it(spmat, colid).

4

0 回答 0