c++ - 优化稀疏矩阵中的对数熵计算

标签 c++ c math

我有一个 3007 x 1644 维度的术语和文档矩阵。我正在尝试为每个文档中的术语频率分配权重,所以我正在使用这个对数熵公式 http://en.wikipedia.org/wiki/Latent_semantic_indexing#Term_Document_Matrix (见最后一行的熵公式)。

我成功地做到了这一点,但我的代码运行了 >7 分钟。 这是代码:

int N = mat.cols();
for(int i=1;i<=mat.rows();i++){
    double gfi = sum(mat(i,colon()))(1,1); //sum of occurrence of terms
    double g =0;
    if(gfi != 0){// to avoid divide by zero error

        for(int j = 1;j<=N;j++){
            double tfij = mat(i,j);
            double pij = gfi==0?0.0:tfij/gfi;
            pij = pij + 1; //avoid log0
            double G = (pij * log(pij))/log(N);
            g = g + G;
        }
    }

    double gi = 1 - g;
    for(int j=1;j<=N;j++){
        double tfij = mat(i,j) + 1;//avoid log0
        double aij = gi * log(tfij);
        mat(i,j) = aij;
    }
}

有人知道如何优化它以使其更快吗?哦,mat 是来自 amlpp 矩阵库的 RealSparseMatrix。

更新 代码在具有 4GB RAM 和 AMD Athlon II 双核的 Linux mint 上运行

更改前的运行时间:> 7 分钟

@Kereks 回答后:4.1 秒

最佳答案

这是一个非常天真的重写,删除了一些冗余:

int const N = mat.cols();
double const logN = log(N);

for (int i = 1; i <= mat.rows(); ++i)
{
    double const gfi = sum(mat(i, colon()))(1, 1);  // sum of occurrence of terms
    double g = 0;

    if (gfi != 0)
    {
        for (int j = 1; j <= N; ++j)
         {
            double const pij = mat(i, j) / gfi + 1;
            g += pij * log(pij);
        }
        g /= logN;
    }

    for (int j = 1; j <= N; ++j)
    {
        mat(i,j) = (1 - g) * log(mat(i, j) + 1);
    }
}

还要确保矩阵数据结构是合理的(例如,大步访问平面数组;不是一堆动态分配的行)。

此外,我认为第一个 + 1 有点傻。你知道 x -> x * log(x) 在零处连续且极限为零,所以你应该写:

double const pij = mat(i, j) / gfi;
if (pij != 0) { g += pij + log(pij); }

事实上,您甚至可以像这样编写第一个内部 for 循环,避免在不需要时进行除法:

        for (int j = 1; j <= N; ++j)
        {
            if (double pij = mat(i, j))
            {
                pij /= gfi;
                g += pij * log(pij);
            }
        }

关于c++ - 优化稀疏矩阵中的对数熵计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857835/

相关文章:

c++ - 将结构传递给函数并在其中输入数据

css - CSS 过滤器背后的数学原理是什么?

javascript - 需要数学方面的帮助才能用 CoffeeScript 或 Javascript 编写振荡迭代器

为不同的 x 值找到 ax + b 的最大值的算法

c++ - C++ 中的字符串和整数连接

c++ - 从 DLL 导出前向声明的类

c++ - 为什么这个 C++ 成员初始值设定项列表不起作用?

c - 我在在线程序挑战编译器中遇到演示错误

c++ - if else 语句的预期表达式错误

c - linux 中对 pthread_create 的 undefined reference (c 编程)