【问题标题】:Converting a vector<tensorflow::Tensor> to tensor of tensors将 vector<tensorflow::Tensor> 转换为张量的张量
【发布时间】:2021-05-17 18:33:09
【问题描述】:
假设我有一个图像张量向量,每个图像张量的尺寸为 [frames, height, width, num_channels],我想获取该向量并将其转换为 [num_tracks(向量大小) 的更大张量),帧,高度,宽度,num_channels]。使用tensorflow::Tensor api 最简单的方法是什么?这是为图构造输入张量,而不是在图执行本身中。
谢谢!
【问题讨论】:
标签:
c++
tensorflow
tensor
【解决方案1】:
您可以创建一个具有所需形状的新张量,然后通过迭代 for 循环中的所有暗淡来填充它(要访问单个项目,请使用 Eigen 的 TensorMap 的 operator(),您可以通过 tensor<DataType,DIMS> on @ 987654324@):
tensorflow::Tensor concat(const std::vector<tensorflow::Tensor>& in){
int frames = in[0].dim_size(0);
int height = in[0].dim_size(1);
int width = in[0].dim_size(2);
int num_channels = in[0].dim_size(3);
int num_tracks = in.size();
tensorflow::Tensor res(DT_FLOAT,tensorflow::TensorShape{num_tracks,frames,height,width,num_channels});
auto& resMap = res.tensor<float,5>();
for (int nt = 0; nt < num_tracks; ++nt) {
auto& inFrame = in[nt];
auto& inMap = inFrame.tensor<float,4>(); // Eigen's TensorMap which has operator()(Indices...)
for (int f = 0; f < frames; ++f) {
for (int r = 0; r < height; ++r) {
for (int c = 0; c < width; ++c) {
for (int ch = 0; ch < num_channels; ++ch) {
resMap(nt,f,r,c,ch) = inMap(f,r,c,ch);
}
}
}
}
}
return res;
}