我该如何从Eigen :: Tensor创建一个tensorflow :: Tensor?我可以逐个复制元素,但我希望有更好的方法。
tensorflow :: Tensor tf_tensor(tensor_constructor_args);
// 对于一般情况:
Eigen :: TensorMap <type_params> eigen_tensor = tf_tensor.tensor<Type,NumDims>();
// 如果您知道张量是矩阵/向量/标量,则可以使用快捷方式
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>();
这样可以避免复制。此外,Eigen张量和TensorMaps共享相同的API,因此您可以互换使用它们。这里有一个可能会有用的例子:
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;
}