我有(已初始化的)张量 input
并希望使用指针直接访问数据。我正在使用
float *input_ptr = input.flat<float>().data();
当我尝试访问数据时,例如使用:
input_ptr[0]
它会导致段错误,但我不明白为什么。
根据 C++ API:
flat()
Return the tensor data as an Eigen::Tensor of the data type and a specified shape.
These methods allow you to access the data with the dimensions and sizes of your choice. You do not need to know the number of dimensions of the Tensor to call them. However, they CHECK that the type matches and the dimensions requested creates an Eigen::Tensor with the same number of elements as the tensor.`
这让我得到了 Eigen 张量。现在,根据 Eigen 文档:
data()
Returns a pointer to the storage for the tensor. The pointer is const if the tensor was const. This allows direct access to the data. The layout of the data depends on the tensor layout: RowMajor or ColMajor.
例子:
Eigen::Tensor<float, 2> a(3, 4);
float* a_data = a.data();
>a_data[0] = 123.45f;
>cout << "a(0, 0): " << a(0, 0);
>=> a(0, 0): 123.45
因此,据我所知,我应该能够毫无问题地使用 input_ptr
。
(值得注意的是指针确实指向一个有效位置。例如,我可以使用 cudaMemcpy
成功地将其内容复制到设备数组。所以问题必须是我不被允许访问数据位置,我只是想不通为什么。)
如有任何想法,我们将不胜感激。
最佳答案
看起来您正在尝试从 CPU 访问 GPU 张量。那是行不通的。
要操作 GPU 张量,直接使用 Eigen 运算或编写一个放在 CPU 上的 op,这样张量就会被复制,然后您就可以访问它。
关于c++ - 在 tensorflow 中访问张量数据时出现段错误(在 c++ 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302338/