特征稀疏矩阵的零复制构造 [英] Zero-copy construction of an Eigen SparseMatrix

查看:111
本文介绍了特征稀疏矩阵的零复制构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

我有一个Eigen::SparseMatrix,我需要通过网络发送,并且我的网络库仅支持发送原始类型的数组.

I have an Eigen::SparseMatrix I need to send over the network, and my network library only supports sending arrays of primitive types.

我可以通过执行以下操作来检索指向SparseMatrix的后备数组的指针(这是支持对象的代码):

I can retrieve the pointers to the backing arrays of my SparseMatrix by doing something like (here's the backing object's code):

// Get pointers to the indices and values, send data over the network
int num_items = sparse_matrix.nonZeros()
auto values_ptr = sparse_matrix.data().valuePtr()
auto index_ptr = sparse_matrix.data().indexPtr()

network_lib::send(values_ptr, num_items)
network_lib::send(index_ptr, 2 * num_items) // Times two b/c we have 2 indices per value

现在在另一侧,我可以访问这两个数组.但是AFAIK无法在不将所有数据复制到新的SparseMatrix中的情况下创建SparseArray(请参见

Now on the other side I have access to these two arrays. But AFAIK there is no way to create a SparseArray without copying all the data into a new SparseMatrix (see docs for construction).

我想做类似的事情:

Eigen::SparseMatrix<float> zero_copy_matrix(num_rows, num_cols);
zero_copy_matrix.data().valuePtr() = received_values_ptr;
zero_copy_matrix.data().indexPtr() = received_index_ptr;

但这会引发编译器错误:

But this throws a compiler error:

error: lvalue required as left operand of assignment zero_copy_matrix.data().valuePtr() = received_values_ptr;

关于如何通过现有索引和数据数组零复制构造稀疏本征矩阵的任何想法吗?

Any idea on how we could zero-copy construct a sparse Eigen matrix from existing arrays of indexes and data?

我尝试过的另一种方法不起作用(这是本地方法,无法进行通信):

Another approach I tried that didn't work (this is local, no communication):

zero_copy_matrix.reserve(num_non_zeros);
zero_copy_matrix.data().swap(original_matrix.data());

当我尝试打印zero_copy_matrix时,其中没有任何值.

When I try to print out the zero_copy_matrix it has no values in it.

推荐答案

深入研究之后,我认为对我来说一个不错的选择是使用Eigen::Map<Eigen::SparseMatrix<float>>这样的

After digging around I think a good option for me would be to use an Eigen::Map<Eigen::SparseMatrix<float>> as such:

Eigen::Map<Eigen::SparseMatrix<float>> sparse_map(num_rows, num_cols, num_non_zeros,
                             original_outer_index_ptr, original_inner_index_ptr,
                             original_values_ptr);

AFAIK,这应该是零副本.从此处回答.

AFAIK, this should be zero-copy. Answer from here.

这篇关于特征稀疏矩阵的零复制构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆