TensorFlow實戰第一課(session、Variable、Placeholder、Activation Function)

莫煩tensorflow教學python

1.session會話控制網絡

 Tensorflow 中的SessionSession是 Tensorflow 爲了控制,和輸出文件的執行的語句. 運行session.run() 能夠得到你要得知的運算結果, 或者是你所要運算的部分。session

咱們首先嚐試將兩個矩陣相乘並輸出結果函數

import tensorflow as tf # create two matrixes
 matrix1 = tf.constant([[3,3]]) matrix2 = tf.constant([[2], [2]]) product = tf.matmul(matrix1,matrix2)

 

由於product不是直接計算的步驟,因此咱們會使用session來激活碼product並獲得計算結果。spa

有兩種形式使用會話控制session。指針

# method 1
sess = tf.Session() result = sess.run(product) print(result) sess.close() # [[12]]

# method 2
with tf.Session() as sess: result2 = sess.run(product) print(result2) # >>[[12]]

 

2.Variable 變量code

看得莫煩的tensorflow課程 講的頗有趣,有興趣的同窗也能夠去看看blog

tensorflow中 只有定義了某字符串是變量,他纔是變量,這一點與python不一樣ip

定義語法:state = tf.Variable( )字符串

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)

 

定義完變量後,最終要的是初始化!init = tf.initialize-all_variables()

到這裏變量尚未激活,須要在sess中 sess.run(init)  激活init這一步

# 若是定義 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才能獲得想要的結果!

 

3.Placeholder 傳入值

 placeholder是tensorflow中的佔位符,暫時存儲變量

tensorflow若是想從外部傳入數據,那麼就須要tf.placehoder(),而後以這種形式傳輸數據

sess.run(***,feed_dict={input:*****})

#placeholder
import tensorflow as tf input1 = tf.placeholder(tf.float32) #大部分狀況 只能處理float32數據形式
input2 = tf.placeholder(tf.float32) output = tf.multiply(input1,input2) with tf.Session() as sess: print(sess.run(output,feed_dict={input1:[7],input2:[2]}))

傳值工做交給sess.run() ,須要穿的值放在了feed_dict={},並一一對應每一個input

 

4.激勵函數Activation Function

激勵函數運行時激活神經網絡中某一部分神經元,將激活信息向後傳入下一層神經系統。

激勵函數的實質是非線性方程。tensorflow的神經網絡裏面處理較爲複雜的問題時都會須要運用激勵函數

相關文章
相關標籤/搜索