常量:
在運行程序中值不會改變的單元,在TensorFlow中無須進行初始化操作創建陳述句:constant_name = tf.constant(value)
變數:
在運行程序中值會改變的單元,在TensorFlow中須進行初始化操作創建陳述句:name_variable = tf.Variable(value, name)
個別變數初始化:init_op = name_variable.initializer()
所有變數初始化:init_op = tf.global_variables_initializer()
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior() # 解決方案:注釋tf的參考,換為兼容模式,
node1 = tf.Variable(3.0, tf.float32, name='node1')
node2 = tf.Variable(4.0, tf.float32, name='node2')
result = tf.add(node1, node2)
sess = tf.Session()
# 變數初始化/所有變數初始化
init = tf.global_variables_initializer()
sess.run(init) # 必須執行一遍,才算初始化
print(sess.run(result))
變數賦值:
與傳統編程語言不同,TensorFlow中的變數定義后,一般無需人工賦值,系統會根據演算法模型,訓練優化程序中自動調整變數對應的數值,
后面再機器學習模型訓練時會更能體會,比如權重Weight變數w,經過多次迭代,會自動調整,
特殊情況需要人工更新的,可用變數賦值陳述句:update_op = tf.assign(variable_to_be_updated, new_value)
# 變數賦值運算
value = tf.Variable(0, name = "value")
one = tf.constant(1)
new_value = tf.add(value, one)
update_value = tf.assign(value, new_value) # tf.assign把new_value的值賦給value
init1 = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init1)
for i in range(10):
sess.run(update_value)
print(sess.run(value))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/374536.html
標籤:AI
