Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 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 Reply

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)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...