1. 程式人生 > >[吃藥深度學習隨筆] 前向傳播:即如何在圖中輸入數據向前推進從而得到計算結果

[吃藥深度學習隨筆] 前向傳播:即如何在圖中輸入數據向前推進從而得到計算結果

矩陣 ted .com one 數據 UNC cat clas HA

技術分享圖片

w = tf.Variable(tf.random_normal([2,3], stddev=2,mean=0, seed=1))

其中

tf.random_normal是正太分布

  除了這個 還有tf.truncated_normal:去掉過大偏離點(大於2個標準差)的正態分布

  tf.random_uniform:平均分布

[2,3]是生成2x3的矩陣

stddev是標準差

mean是均值

seed是隨機數種子

構造其余量的方法:

#tf.zeros 全0數組
tf.zeros([3,2], int32) #生成 [[0,0], [0,0], [0,0]]
#tf.ones 全1數組
tf.ones([3,2],int32) #
生成 [[1,1], [1,1], [1,1]] #tf.fill 全定值數組 tf.fill([3,2],8) #生成 [[8,8], [8,8], [8,8]] #tf.constant 直接給值 tf.constant([3,2,1]) #生成[3,2,1]

技術分享圖片

技術分享圖片

技術分享圖片

在數組中[x,y]中 x即為有x個輸入特征 y即為有y個輸出特征

即如圖 輸入層有2個輸入特征 而在隱藏層中有3個特征

所以數組為2x3

而最後隱藏層中 輸出y 只有1個

所以隱藏層到輸出層的權w即為3x1的數組

總結 即為

技術分享圖片

輸入層X與2x3的權矩陣W1 相乘得到隱藏層a數據

隱藏層a數據與 3x1的權矩陣W2 相乘得到輸出層y數據

代碼過程:技術分享圖片

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 is: ", sess.run(y))

得到結果:y is: [[3.0904665]]

使用placeholder添加數據:

import tensorflow as tf

#定義輸入和參數
#定義了一個數據類型為32位浮點,形狀為1行2列的數組
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 is: ", sess.run(y, feed_dict={x: [[0.7, 0.5]]}))

添加多組數據:

import tensorflow as tf

#定義輸入和參數
#定義了一個數據類型為32位浮點,形狀為1行2列的數組
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 is: ", 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))

得到結果:

y is: [[3.0904665]
[1.2236414]
[1.7270732]
[2.2305048]]
w1: [[-0.8113182 1.4845988 0.06532937]
[-2.4427042 0.0992484 0.5912243 ]]
w2: [[-0.8113182 ]
[ 1.4845988 ]
[ 0.06532937]]

[吃藥深度學習隨筆] 前向傳播:即如何在圖中輸入數據向前推進從而得到計算結果