1 | initial version |
To retrieve the shape of all tensors in a graph using c++ in Tensorflow, you can use the following steps:
Graph::get_operations()
method.Tensor::shape()
method to retrieve its shape.Here's an example code snippet that demonstrates these steps:
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/graph/graph.h"
#include <iostream>
using namespace tensorflow;
int main() {
// Load Tensorflow graph
GraphDef graph_def;
ReadBinaryProto(Env::Default(), "path/to/your/graph.pb", &graph_def);
// Create session and load graph
SessionOptions options;
std::unique_ptr<Session> session(NewSession(options));
Status status = session->Create(graph_def);
if (!status.ok()) {
std::cerr << "Error creating Tensorflow session: " << status.ToString() << std::endl;
return 1;
}
// Get list of all operations in the graph
std::vector<tensorflow::TensorShape> shapes;
const Graph& graph = session->graph();
for (const auto& op : graph.op_nodes()) {
// Iterate over input tensors
for (const auto& input : op->inputs()) {
auto tensor = input.template tensor<T>();
TensorShape shape = tensor.shape();
shapes.push_back(shape);
std::cout << "Input tensor shape: " << shape.DebugString() << std::endl;
}
// Iterate over output tensors
for (const auto& output : op->outputs()) {
auto tensor = output.template tensor<T>();
TensorShape shape = tensor.shape();
shapes.push_back(shape);
std::cout << "Output tensor shape: " << shape.DebugString() << std::endl;
}
}
return 0;
}