将向量<tensorflow::Tensor> 转换为张量的张量

Converting a vector<tensorflow::Tensor> to tensor of tensors

假设我有一个图像张量向量,每个图像张量的尺寸为 [frames, height, width, num_channels] 我想获取该向量并将其转换为一个更大的张量[num_tracks(矢量大小),帧,高度,宽度,num_channels]。使用 tensorflow::Tensor api 最简单的方法是什么?这是为了构建图形的输入张量,而不是图形执行本身。

谢谢!

您可以创建一个具有所需形状的新张量,并通过迭代 for 循环中的所有暗淡来填充它(要访问单个项目,请使用 Eigen 的 TensorMapoperator(),您可以获得通过 tensor<DataType,DIMS>Tensor 上):

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;
}