12

我正在对日志域中的浮点稀疏矩阵进行一些计算,因此“空”条目实际上是-Inf(使用-FLT_MAX)。我现在正在使用自定义稀疏矩阵类,但我渴望更换现成的替代品。

这是在 C++ 中。我倾向于查看 Eigen 和 Boost uBlas 中的压缩列矩阵。但是,不清楚是否支持“零”的自定义值(可能由模板参数提供)。有人有建议吗?

澄清

我想要的是:对于之前没有“设置”的任何单元格 (i,j),我希望 mat[i,j] 返回 -Inf ...所以这可能更好地描述为“默认”稀疏矩阵的“空”条目的值。

我正在使用它来执行 HMM 递归(Viterbi,sum-product),概率保存在日志域中以避免下溢。

我没有做任何矩阵运算……本质上,我只是在填写动态规划表。我想使用稀疏矩阵类,因为我只填充矩阵的一个带,并且我希望有效地使用内存。压缩带矩阵将提供良好的性能,因为我正在“按顺序”填充矩阵。

4

2 回答 2

2

这样的事情怎么样?

class compressed_matrix_nonzero_default : public boost::numeric::ublas::compressed_matrix<double>
{
    double def;
public:
    compressed_matrix_nonzero_default( int s1, int s2 )
        : boost::numeric::ublas::compressed_matrix<double>(s1,s2)
        , def(0)
    {

    }
    void setDefault( double d ) { def = d; }
    double value( int i, int j )
    {
        typedef boost::numeric::ublas::compressed_matrix<double>::iterator1 it1_t;
        typedef boost::numeric::ublas::compressed_matrix<double>::iterator2 it2_t;
        for (it1_t it1 = begin1(); it1 != end1(); it1++)
        {
            if( it1.index1() <  i )
                continue;
            if( it1.index1() > i ) {
                return def;
            }
            for (it2_t it2 = it1.begin(); it2 != it1.end(); it2++)
            {
                if( it2.index2() < j )
                    continue;
                if( it2.index2() == j )
                    return *it2;
                if( it2.index2() > j )
                    return def;
            }


        }
        return def;
    }

};

用法

compressed_matrix_nonzero_default MNZ(3,3);
MNZ.setDefault(-100);
MNZ (1,1) = 45;

for( int i = 0; i < 3; i++ ) {
    for( int j = 0; j < 3; j++ ) {
        std::cout << MNZ.value(i,j) << ",";
    }
    std::cout << "\n";
}
于 2011-08-31T20:40:02.363 回答
1

我目前制定的解决方案是这样的。定义一个类lfloat

class lfloat {
  float value;
public:
  lfloat(float f=-FLT_MAX)
  {
    value = f;
  }

  lfloat& operator=(float f)
  {
    value = f;
    return *this;
  }

  operator float()   { return value; }
};

并像这样使用它:

compressed_matrix<lfloat> M1(3,3);

这样我们就不会重写 boost 矩阵类中的任何功能,但我们应该得到想要的结果。

于 2011-09-01T15:46:01.067 回答