【问题标题】:Convert Sparse Matrix from Eigen::SparseMatrix to Cusp::hyb_matrix将稀疏矩阵从 Eigen::SparseMatrix 转换为 Cusp::hyb_matrix
【发布时间】:2018-05-03 19:53:04
【问题描述】:

我正在寻找一种转换方式

Eigen::SparseMatrix cusp::hyb_matrix

来回。

特征矩阵是先前计算的结果,我需要一个 cusp::hyb_matrix 以便稍后使用 GPU 进行共轭梯度计算。

谢谢。

【问题讨论】:

  • 很好。您有实际问题要问吗?
  • “我正在寻找一种方法”相当肯定意味着如何......
  • 嗯,我正在寻找一种方法来预测中奖彩票号码。这并不意味着我们中的任何一个人都有一个实际有效的Stack Overflow 问题,您在尝试编写执行这种格式转换的代码时具体不了解什么?

标签: cuda sparse-matrix eigen data-conversion cusp-library


【解决方案1】:

嗯,我找到了一种解决方法,可以满足需要,但仍然缺少更直接的方法。

基于这个example,我只需要从 Eigen::SparseMatrix 中提取行/列/系数向量来构造一个 cusp::hyb_matrix。这可以按如下方式完成:

void SparseMatrix2Coo(Eigen::SparseMatrix<float> Matrix, std::vector<int>& rows, std::vector<int>& cols, std::vector<float>& coeffs)
{
rows.clear();
cols.clear();
coeffs.clear();
for (int k=0; k < Matrix.outerSize(); ++k)
{
    for (Eigen::SparseMatrix<float>::InnerIterator it(Matrix,k); it; ++it)
    {
        rows.push_back(it.row());
        cols.push_back(it.col());
        coeffs.push_back(Matrix.coeff(it.row(), it.col()));
    }
}
assert(cols.size() == coeffs.size());
assert(rows.size() == cols.size());
}

现在,一旦我们有了行/列/系数,我们只需要使用上面示例中的那些作为输入:

void computeConjugateGradientGPU(std::vector<int>& rows, std::vector<int>& cols, std::vector<float>& coeffs, std::vector<float>& b, Eigen::VectorXf& x)
{
int arrays_size = rows.size();
/// allocate device memory for CSR format
int   * device_I;
cudaMalloc(&device_I, arrays_size * sizeof(int));
int   * device_J;
cudaMalloc(&device_J, arrays_size * sizeof(int));
float * device_V;
cudaMalloc(&device_V, arrays_size * sizeof(float));

float * device_b;
cudaMalloc(&device_b, b.size() * sizeof(float));

/// copy raw data from host to device
cudaMemcpy(device_I, &cols[0], arrays_size * sizeof(int),   cudaMemcpyHostToDevice);
cudaMemcpy(device_J, &rows[0], arrays_size * sizeof(int),   cudaMemcpyHostToDevice);
cudaMemcpy(device_V, &coeffs[0], arrays_size * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(device_b, &b[0],  b.size() * sizeof(float), cudaMemcpyHostToDevice);

/// and the rest is the same...
}

反之亦然,逻辑相同。

希望这对某人有所帮助。

干杯。

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2023-04-10
    • 2021-11-25
    • 2017-07-02
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多