A7med
A7med

Reputation: 451

tensorflow: convert scalar tensor to python scalar object in graph

I would like to convert scalar tensor (tf.constant([4]) for example) to python scalar (4) inside a computational graph so without use tf.eval().

Upvotes: 1

Views: 2323

Answers (2)

Yaroslav Bulatov
Yaroslav Bulatov

Reputation: 57893

Constant values are hardwired into the graph, so you can see it by inspecting graph definition.

IE

tf.reset_default_graph()
tf.constant(42)
print tf.get_default_graph().as_graph_def()

This gives you

node {
  name: "Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 42
      }
    }
  }
}
versions {
  producer: 9
}

This means you can get the constant value out as

tf.get_default_graph().as_graph_def().node[0].attr["value"].tensor.int_val[0]

Upvotes: 1

satojkovic
satojkovic

Reputation: 699

You can also use the Session.run() method.

In [1]: import tensorflow as tf

In [2]: sess = tf.InteractiveSession()

In [3]: x = tf.constant(4)

In [4]: sess.run(x)
Out[4]: 4

Upvotes: 0

Related Questions