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 : <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.]]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章