Defining constants in TensorFlow

时间:2016-04-04 18:12:44

标签: python tensorflow

I am using Python 2.7 with the TensorFlow library. In this library, there is a data type called tf.constant(3), which means a constant float of value 3. The value needs to be assigned at initialisation and cannot be changed, similar to a const in C++.

In my code however, I do not know the value of this constant at the start. Instead, I need to call a function, which does some processing and then creates the constant. For example, if the constant is called x:

def initialise_x():
    #
    # Do some stuff
    #
    y = ...
    x = tf.constant(y)

The problem with this, is that x is now not available outside the scope of the function initialise_x().

So, I want to do something like:

x = tf.constant(0)

def initialise_x():
    #
    # Do some stuff
    #
    y = ...
    x = tf.constant(y)

But this is not possible, because the constant can only be defined once.

How can I solve this?

1 个答案:

答案 0 :(得分:1)

I'm not sure how your program looks like, but how about making a function that returns a constant?

def initialize_x():
    # Do something
    y = ...
    return tf.constant(y)

if __name__ == "__main__":
    ...
    x = initialize_x()
    ...
相关问题