Moshe Kravchik
Moshe Kravchik

Reputation: 2341

Creating tensorflow::Tensor from Eigen::Tensor

How should I create a tensorflow::Tensor from Eigen::Tensor? I could just copy the elements over one-by-one, but I hope there is a better way.

Upvotes: 3

Views: 2102

Answers (2)

Simon Lynen
Simon Lynen

Reputation: 1

Here is an example that might be useful:

Eigen::Tensor<float, 3> TensorflowToEigen(const tensorflow::Tensor& tensor) {
  const tensorflow::TensorShape dims = tensor.shape();
  Eigen::Tensor<float, 3, Eigen::RowMajor> rm_tensor =
      tensor.tensor<float, 3>();
  // Change to ColMajor. swap_layout changes the ordering of dimensions, so we
  // shuffle them back.
  Eigen::Tensor<float, 3> cm_tensor =
      rm_tensor.swap_layout().shuffle(Eigen::make_index_list(2, 1, 0));
  return cm_tensor;
}

tensorflow::Tensor EigenToTensorflow(const Eigen::Tensor<float, 3>& tensor) {
  const Eigen::DSizes<int64_t, 3> dims = tensor.dimensions();
  // Change to RowMajor. swap_layout  changes the ordering of dimensions, so we
  // shuffle them back.
  Eigen::Tensor<float, 3, Eigen::RowMajor> rm_tensor =
      tensor.swap_layout().shuffle(Eigen::make_index_list(2, 1, 0));
  tensorflow::Tensor tf_tensor(
      tensorflow::DT_FLOAT,
      tensorflow::TensorShape({dims[0], dims[1], dims[2]}));
  tf_tensor.tensor<float, 3>() = rm_tensor;
  return tf_tensor;
}

Upvotes: 0

Benoit Steiner
Benoit Steiner

Reputation: 1469

There is no public api to create a tensorflow::Tensor from an Eigen::Tensor without copying the data. However, you can create a tensorflow::Tensor and interpret it as a Eigen::TensorMap using the following apis: tensorflow::Tensor tf_tensor(tensor_constructor_args); // For the general case: Eigen::TensorMap<type_params> eigen_tensor = tf_tensor.tensor<Type, NumDims>(); // shortcuts if you know the tensor is a matrix/vector/scalar Eigen::TensorMap<type_params> eigen_matrix = tf_tensor.matrix<Type>(); Eigen::TensorMap<type_params> eigen_vector = tf_tensor.vector<Type>(); Eigen::TensorMap<type_params> eigen_scalar = tf_tensor.scalar<Type>();

This will avoid a copy. Moreover, Eigen tensors and tensormaps share the same apis, so you can use them interchangeably.

Upvotes: 2

Related Questions