Reshaping tensors in C++

倾然丶 夕夏残阳落幕 提交于 2019-12-10 10:05:04

问题


The C++ interface to TensorFlow doesn't seem to have a reshape method. Does anyone have an idea how to convert e.g. [A,B,C,D] into [A*B,C,D]? It looks like the only way to do this is to use Eigen? However, the documentation there is very slim and the code is template hell and not easy to parse.


回答1:


Solution with checking whether reshaped tensor has the same number of elements of the source tensor:

// Extracted image features from MobileNet_224
tensorflow::Tensor image_features(tensorflow::DT_FLOAT,
                                  tensorflow::TensorShape({1, 14, 14, 512}));

tensorflow::Tensor image_features_reshaped(tensorflow::DT_FLOAT,
                                           tensorflow::TensorShape({1, 196, 512}));

// Reshape tensor from [1, 14, 14, 512] to [1, 196, 512]
if(!image_features_reshaped.CopyFrom(image_features, tensorflow::TensorShape({1, 196, 512})))
{
  LOG(ERROR) << "Unsuccessfully reshaped image features tensor [" << image_features.DebugString() << "] to [1, 196, 512]";
  return false;
}

LOG(INFO) << "Reshaped features tensor: " << image_features_reshaped.DebugString();



回答2:


This should work:

Tensor my_tensor; // [A, B, C, D]
Tensor reshaped_tensor = my_tensor.shaped<float, 3>({A*B, C, D});  //[A*B, C, D]


来源:https://stackoverflow.com/questions/43476944/reshaping-tensors-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!