TensorFlow之变量修改

代码:

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(_)

输出:

input_tf : 
assign_op : 

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

 

你可能感兴趣的:(TensorFlow)