TensorFlow筆記-04-神經網絡的實現過程,前向傳播
阿新 • • 發佈:2018-09-08
com 描述 矩陣相乘 ons === nor 技術分享 轉載 .html
TensorFlow筆記-04-神經網絡的實現過程
- 基於TensorFlow的NN:用張量表示數據,用計算圖搭建神經網絡,用會話執行計算圖,優化線上的權重(參數),得到模型
- 張量(tensor):多維數組(列表)
- 階:張量的維數
- 計算圖(Graph):搭建神經網絡的計算過程,只搭建,不運算
- 會話(Session):執行計算圖中的結點運算
參數:即計算圖中的權重,用變量表示,隨機給初值
其中Variable有4種:zeros,ones,fill,constant
tf.zeros····全0數組··············tf.zeros([3,2],int32) 生成[[0,0],[0,0],[0,0]]
tf.fill·······全定值數組··············tf.fill([3,2],6) 生成[[6,6],[6,6],[6,6]]
tf.constant··直接給值··············tf.zeros([3,2,1]) 生成[3,2,1]
神經網絡的實現過程
- 1.準備數據,提取特征,作為輸入餵給神經網絡
- 2.搭建NN結構,從輸入到輸出(先搭建計算圖,再用會話執行)
(NN前向傳播算法===>計算輸出) - 3.大量特征數據餵給NN,叠代優化NN參數
- 4.使用訓練好的模型,預測和分類
前向傳播
- 搭建模型計算過程,讓模型具有推理能力(以全連接網絡為例)
eg.生產一批零件將體積想x1和重量x2為特征的輸入NN,通過NN後輸出一個數值
使用TensorFlow表示上例
計算結果要用到會話
- 代碼前向傳播文件:https://xpwi.github.io/py/TensorFlow/tf05forward.py
# coding:utf-8 # 前向傳播 # 兩層簡單神經網絡(全連接) import tensorflow as tf # 定義輸入和參數 x = tf.constant([[0.7, 0.5]]) w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) # 定義前向傳播的過程 a = tf.matmul(x, w1) y = tf.matmul(a, w2) # 用會話計算結果 with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) print("y in tf05前向傳播 is:\n", sess.run(y)) # 結果: # [[3.0904665]]
運行結果:
- 向神經網絡餵入1組特征
- 用placeholder實現輸入自定義(sess.run中餵1組數據)
- 代碼前向傳播2文件:https://xpwi.github.io/py/TensorFlow/tf05forward2.py
# coding:utf-8
# 前向傳播
# 兩層簡單神經網絡(全連接)
import tensorflow as tf
# 定義輸入和參數
# 用placeholder實現輸入自定義(sess.run中餵1組數據)
x = tf.placeholder(tf.float32, shape=(1, 2))
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
# 定義前向傳播的過程
# 矩陣相乘,不運算
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
# 用會話計算結果
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
# 字典,餵入一組特征
print("y in tf05forward2 is:\n", sess.run(y, feed_dict={x:[[0.7,0.5]]}))
# 結果:
# [[3.0904665]]
一次向神經網絡餵入n組特征
- 代碼前向傳播3文件:https://xpwi.github.io/py/TensorFlow/tf05forward3.py
# coding:utf-8
# 前向傳播
# 兩層簡單神經網絡(全連接)
# 向神經網絡餵入n組特征
import tensorflow as tf
# 定義輸入和參數
# 用placeholder實現輸入自定義(sess.run中餵多組數據)None表示未知
x = tf.placeholder(tf.float32, shape=(None, 2))
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
# 定義前向傳播的過程
# 矩陣相乘,不運算
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
# 用會話計算結果
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
# 字典,餵入多組特征
print("y in tf05forward2 is:\n", sess.run(y, feed_dict={x:[[0.7,0.5],[0.2,0.3],[0.3,0.4],[0.4,0.5]]}))
print("w1:", sess.run(w1))
print("w2:", sess.run(w2))
運行結果
前向傳播就到這裏了
更多文章:Tensorflow 筆記
- 本筆記不允許任何個人和組織轉載
TensorFlow筆記-04-神經網絡的實現過程,前向傳播