TensorFlow modification of variables

Code:

import tensorflow as tf
input = [[1, 2, 3], [2, 3, 4]]
tf1 = tf.compat.v1
Graph = tf.Graph()
with Graph.as_default():
    input_tf = tf1.Variable(input, dtype=tf.float32, name="input")
    # 将input每个元素加1
    add_one_tf = input_tf + 1
    # 将计算结果赋值给input_tf
    assign_op = input_tf.assign(add_one_tf)
    print("input_tf :", input_tf)
    print("assign_op :", assign_op)

with tf1.Session(graph=Graph) as sess:
    sess.run(tf1.global_variables_initializer())
    # 由于赋值计算也是图中的一个节点,需要被显式指定执行赋值操作才能生效
    input_v, _ = sess.run([assign_op, input_tf])
    print(input_v)
    print(_)

Output:

input_tf : <tf.Variable 'input:0' shape=(2, 3) dtype=float32>
assign_op : <tf.Variable 'AssignVariableOp' shape=(2, 3) dtype=float32>

input_v:
 [[2. 3. 4.]
 [3. 4. 5.]]
_:
 [[1. 2. 3.]
 [2. 3. 4.]]

 

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

Guess you like

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