TensorFlow之變數和常量的運用

2021-08-21 15:06:18 字數 1195 閱讀 9516

原出處:變數和常量

在 tensorflow 中,定義了某字串是變數,它才是變數,這一點是與 python 所不同的。

定義語法:state = tf.variable(),如下:其中,0指變數初值為0,counter為變數名。定義常量中1值該常量為1。assign把後面new_value中的值賦給了state。

import tensorflow as tf

state = tf.variable(0, name='counter')

# 定義常量 one

one = tf.constant(1)

# 定義加法步驟 (注: 此步並沒有直接計算)

new_value = tf.add(state, one)

# 將 state 更新成 new_value

update = tf.assign(state, new_value)

如果在 tensorflow 中設定了變數,那麼初始化變數是最重要的!!所以定義了變數以後, 一定要定義

init = tf.initialize_all_variables()用來初始化.

到這裡變數還是沒有被啟用,需要再在sess裡,sess.run(init), 啟用init這一步.(sess指向init模組並執行該模組),其中range(3)指執行三次for語句。

# 如果定義 variable, 就一定要 initialize

# init = tf.initialize_all_variables() # tf 馬上就要廢棄這種寫法

init = tf.global_variables_initializer() # 替換成這樣就好

# 使用 session

with tf.session() as sess:

sess.run(init)

for _ in range(3):

sess.run(update)

print(sess.run(state)

注意:直接print(state)不起作用!!

一定要把sess的指標指向state再進行print才能得到想要的結果!

tensorflow 學習筆記之 變數的一些操作

部分內容參考了其他資源,謝謝。使用tf.variable 時,如果系統檢測到重名,會做自動處理,不會報錯。w 1 tf.variable 3,name w w 2 tf.variable 1,name w print w 1.name print w 2.name 執行結果 使用tf.get var...

C 之變數和常量

c 中每個變數都有指定的型別,型別決定了變數儲存的大小和布局,該範圍內的值都可以儲存在記憶體中,運算子可應用於變數上。變數的名稱可以由字母 數字和下劃線字元組成。它必須以字母或下劃線開頭。大寫字母和小寫字母是不同的,因為 c 是大小寫敏感的。型別描述 bool 儲存值 true 或 false。ch...

Python之變數和列印

coding utf 8 name zed a.shaw age 8.123 not a lie height 74 inches weight 180 lbs eyes blue teeth white hair brown print his name is s name 這裡可以將常量也以這種...