TensorFlow of obtaining and executing Operation object

Code:

import tensorflow as tf

# 定义变量Tensor对象
A_tf = tf.Variable([[1, 1], [1, 1]], dtype=tf.float32)
# 为A_tf做赋值操作
A_tf.assign(A_tf+1)
# 获取当前图
graph = tf.get_default_graph()
# 获取当前图中所有的Operation并打印
ops = graph.get_operations()
print(ops)
# 找到初始化Operation
init_op = graph.get_operation_by_name('Variable/Assign')
with tf.Session() as sess:
    # 执行初始化操作
    sess.run(init_op)
    # 取出变量值
    print(sess.run(A_tf))

In the above code, line 10 to obtain all the current Operation object, line 13, to identify the initializing operation according to the found objects Operation Operation object list, initializing operation is performed in the line 16. Code is executed, the output results are as follows:

[<tf.Operation 'Variable/initial_value' type=Const>, <tf.Operation 'Variable' type=VariableV2>, <tf.Operation 'Variable/Assign' type=Assign>, <tf.Operation 'Variable/read' type=Identity>, <tf.Operation 'add/y' type=Const>, <tf.Operation 'add' type=AddV2>, <tf.Operation 'Assign' type=Assign>]

[[1. 1.]
 [1. 1.]]

We found that, although the value A_tf out, but seemingly not running Assign assignment above code on line 6. Before we explained, line 6 Operation code is just an operation, the operation is not in the path of execution, it is necessary to manually perform this assignment Operation object, modify the above code is as follows:

import tensorflow as tf

# 定义变量Tensor对象
A_tf = tf.Variable([[1, 1], [1, 1]], dtype=tf.float32)
# 为A_tf做赋值操作
A_tf.assign(A_tf+1)
# 获取当前图
graph = tf.get_default_graph()
# 获取当前图中所有的Operation并打印
ops = graph.get_operations()
print(ops)
# 找到初始化Operation
init_op = graph.get_operation_by_name('Variable/Assign')
add_op = graph.get_operation_by_name("Assign")
with tf.Session() as sess:
    # 执行初始化操作
    sess.run(init_op)
    # 取出变量值
    print(sess.run(A_tf))
    # 执行赋值操作
    sess.run(add_op)
    # 取出变量赋值后的值
    print(sess.run(A_tf))

Output:

[<tf.Operation 'Variable/initial_value' type=Const>, <tf.Operation 'Variable' type=VariableV2>, <tf.Operation 'Variable/Assign' type=Assign>, <tf.Operation 'Variable/read' type=Identity>, <tf.Operation 'add/y' type=Const>, <tf.Operation 'add' type=AddV2>, <tf.Operation 'Assign' type=Assign>]

[[1. 1.]
 [1. 1.]]
[[2. 2.]
 [2. 2.]]

 

Published 105 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/104124698