代码之家  ›  专栏  ›  技术社区  ›  avocado

特征稀疏矩阵的性能调整

  •  0
  • avocado  · 技术社区  · 7 年前

    我已经用 Eigen SparseMatrix 基本上是这样的,

    SparseMatrix W;
    ...
    W.row(i) += X.row(j);  // X is another SparseMatrix, both W and X are row major.
    ...
    

    我通过 google-pprof ,我认为上面的代码有问题,请参见下图,

    图1

    enter image description here

    然后 图2

    enter image description here

    最后 图3

    enter image description here

    看起来像 operator+=

    我不太了解 稀疏矩阵 操作,但有没有推荐的方法来优化上述代码?

    1 回复  |  直到 7 年前
        1
  •  1
  •   ggael    7 年前

    如果X的稀疏性是W的稀疏性的子集,那么您可以编写自己的函数进行就地加法:

    namespace Eigen {
    template<typename Dst, typename Src>
    void inplace_sparse_add(Dst &dst, const Src &src)
    {
      EIGEN_STATIC_ASSERT( ((internal::evaluator<Dst>::Flags&RowMajorBit) == (internal::evaluator<Src>::Flags&RowMajorBit)),
                          THE_STORAGE_ORDER_OF_BOTH_SIDES_MUST_MATCH);
    
      using internal::evaluator;
      evaluator<Dst> dst_eval(dst);
      evaluator<Src> src_eval(src);
    
      assert(dst.rows()==src.rows() && dst.cols()==src.cols());
      for (Index j=0; j<src.outerSize(); ++j)
      {
        typename evaluator<Dst>::InnerIterator dst_it(dst_eval, j);
        typename evaluator<Src>::InnerIterator src_it(src_eval, j);
        while(src_it)
        {
          while(dst_it && dst_it.index()!=src_it.index())
            ++dst_it;
          assert(dst_it);
          dst_it.valueRef() += src_it.value();
          ++src_it;
        }
      }
    }
    }
    

    下面是一个使用示例:

    int main()
    {
      int n = 10;
      MatrixXd R = MatrixXd::Random(n,n);
      SparseMatrix<double, RowMajor> A = R.sparseView(0.25,1), B = 0.5*R.sparseView(0.65,1);
    
      cout << A.toDense() << "\n\n" << B.toDense() << "\n\n";
    
      inplace_sparse_add(A, B);
    
      cout << A.toDense() << "\n\n";
    
      auto Ai = A.row(2);
      inplace_sparse_add(Ai, B.row(2));
    
      cout << A.toDense() << "\n\n";
    }