What is the C++ equivalent of python: tf.Graph.get_tensor_by_name(name) in Tensorflow? Thanks!
Here is the code I am trying to run, but I get an empty output
there is a way to get neural node from graph_def directly. if u only want the shape\type of node: "some_name":
void readPB(GraphDef & graph_def)
{
int i;
for (i = 0; i < graph_def.node_size(); i++)
{
if (graph_def.node(i).name() == "inputx")
{
graph_def.node(i).PrintDebugString();
}
}
}
results:
name: "inputx"
op: "Placeholder"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
dim {
size: -1
}
dim {
size: 5120
}
}
}
}
try member functins of the node and get the informations.
From your comment, it sounds like you are using the C++ tensorflow::Session
API, which represents graphs as GraphDef
protocol buffers. There is no equivalent to tf.Graph.get_tensor_by_name() in this API.
Instead of passing typed tf.Tensor objects to Session::Run(), you pass the string
names of tensors, which have the form <NODE NAME>:<N>
, where <NODE NAME>
matches one of the NodeDef.name
values in the GraphDef
, and <N>
is an integer corresponding to the index of the the output from that node that you want to fetch.
The code in your question looks roughly correct, but there are two things I'd advise:
The session->Run()
call returns a tensorflow::Status
value. If output
is empty after the the call returns, it is almost certain that the call returned an error status with a message that explains the problem.
You're passing "some_name"
as the name of a tensor to fetch, but it is the name of a node, not a tensor. It is possible that this API requires you to specify the output index explicitly: try replacing it with "some_name:0"
.
In case anybody is interested, here is how you extract the shape of an arbitrary sensor from graph_def using the tensorflow C++ API
vector<int64_t> get_shape_of_tensor(tensorflow::GraphDef graph_def, std::string name_tensor)
{
vector<int64_t> tensor_shape;
for (int i=0; i < graph_def.node_size(); ++i) {
if (graph_def.node(i).name() == name_tensor) {
auto node = graph_def.node(i);
auto attr_map = node.attr();
for (auto it=attr_map.begin(); it != attr_map.end(); it++) {
auto key = it->first;
auto value = it->second;
if (value.has_shape()) {
auto shape = value.shape();
for (int i=0; i<shape.dim_size(); ++i) {
auto dim = shape.dim(i);
auto dim_size = dim.size();
tensor_shape.push_back(dim_size);
}
}
}
}
}
return tensor_shape
}