Reputation: 377
I have a C++ tensorflow::Tensor
whose contents I am trying to access in Python.
I have looked through the Tensorflow C++ Documentation in search of a function that can convert a tensorflow::Tensor
to any sensible PyObject
(it does not matter for now wether this is a tf.Tensor
or a numpy.nd_array
).
After looking around though the Tensorflow Code, I have found the following clues:
There is a method TF_Tensor_to_PyObject(TF_Tensor* Tensor, PyObject** out_array)
defined in tensorflow/python/client/tf_session_helper.cc
. However, this is defined in a hidden Bazel package, moreover in an anonymous C++ namespace. It seems unintuitive to modify Tensorflow itself (I would have to modify the Bazel BUILD file, the .h and .cc files), and compile my own Tensorflow to use this Approach.
Another issue with this Approach is that TF_Tensor
!= tensorflow::Tensor
. The TF_Tensor
is defined in the C-Api for Tensorflow, and there, the conversion also not intended for public use (as in: outside of this package).
Does anybody know of a better way to do this? Is there an existing implementation for a tensorflow::Tensor
to a PyObject
which I did not find while searching?
Upvotes: 0
Views: 650
Reputation: 2308
To be more precise the following should do it:
#include "tensorflow/python/lib/core/py_func.h"
Status TensorHandler::ExportTensorAsNumpy(const Tensor *inputTensor) {
PyObject* numpyObject = Py_None;
tensorflow::ConvertTensorToNdarray(*inputTensor, &numpyObject);
//process the numpy further its now stored in numpyObject
//call this when you don't use the numpyObject anymore
Py_DECREF(numpyObject);
}
When you don't use the numpy object don't forget to call Py_DECREF or your program it will cause memory leak. Also don't forget to include py_func in you bazel build as dependency.
Upvotes: 0
Reputation: 5206
The implementation of the py_func op has code to convert Tensor to PyObject.
Upvotes: 1