Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - How to get reference by name of variable/placeholder?

By names I'm referring to:

tf.placeholder(tf.float32, name='NAME')
tf.get_variable("W", [n_in, n_out],initializer=w_init())

I have several placeholders which I want to access from outside functions without passing the reference, with the assumption that placeholders holding the given names exist how can you get a reference to them? (this is all during graph construction, not runtime)

And my second question is how can I get all variables that hold a given name no matter the scope?

Example: All my weights have the name "W" under many scopes, I want to get them all into a list. I do not want to add each one manually. The same can be done with the biases, lets say I want to do a histogram.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, you can get the placeholder using tf.Graph.get_tensor_by_name(). For example, assuming that you are working with the default graph:

placeholder1 = tf.placeholder(tf.float32, name='NAME')
placeholder2 = tf.get_default_graph().get_tensor_by_name('NAME:0')
assert placeholder1 == placeholder2

Secondly, I would use the following function to get all variables with a given name (no matter their scope):

def get_all_variables_with_name(var_name):
    name = var_name + ':0'
    return [var for var in tf.all_variables() if var.name.endswith(name)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...