How to check if a variable exists or not in Tensorflow1.X?
I have get check it out in the programming, and I have googled it for a long time but still get no answer.
How to check if a variable exists or not in Tensorflow1.X?
I have get check it out in the programming, and I have googled it for a long time but still get no answer.
 
    
    Unless you are passing an explicit value for collections in tf.Variable / tf.get_variable, you should be able to find all the variables in the GLOBAL_VARIABLES collection:
import tensorflow as tf
with tf.Graph().as_default():
    tf.Variable([1, 2, 3], name='my_var')
    print('my_var' in {v.op.name for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)})
    # True
More generally, you can look for an operation with the variable name you are looking for and check the operation type is indeed a variable:
import tensorflow as tf
def variable_exists(var_name, graph=None):
    if graph is None:
        graph = tf.get_default_graph()
    try:
        op = graph.get_operation_by_name(var_name)
    except KeyError:
        return False
    return op.type in {'Variable', 'VariableV2', 'AutoReloadVariable', 'VarHandleOp'}
with tf.Graph().as_default():
    tf.Variable([1, 2, 3], name='my_var')
    print(variable_exists('my_var'))
    # True
    print(variable_exists('my_var2'))
    # False
