Tensorflow實踐基礎 張量、會話、前向傳播、反向傳播

北京大學 Tensorflow實踐

 

Table of Contents

定義

一、張量

二、計算圖

三、會話Session

前向傳播

一、參數

二、神經網絡實現過程

反向傳播

一、loss函數

二、均方誤差MSE

三、反向傳播訓練方法:以減小loss值爲優化目標

四、學習率learning_rate

代碼舉例


定義

一、張量

張量表示數據 可以表示從0到n階數組(列表)

數據類型:tf.float32   tf.int32 .....

import tensorflow as tf #導入tensorflow

a= tf.constant([1.0,2.0])
b=tf.constant([3.0,4.0])
result = a+b
print(result)

#Tensor("add_5:0", shape=(2,), dtype=float32)

Tensor中分別爲

  • 節點名:第0個輸出
  • 維度:一維數組長度爲2
  • dtype數據類型 :float32

二、計算圖

搭建神經網絡的計算過程,不運算

x1-w1->|

             |->y->        y=XW=x1*w1+x2*w2

x2-w2->|

x= tf.constant([[1.0,2.0]])
w=tf.constant([[3.0],[4.0]])
y = tf.matmul(x,w)
print(y)

#Tensor("MatMul_1:0", shape=(1, 1), dtype=float32)

三、會話Session

執行計算圖中的節點運算,使用with結構實現

x= tf.constant([[1.0,2.0]])
w=tf.constant([[3.0],[4.0]])
y = tf.matmul(x,w)
print(y)

with tf.Session() as sess:
    print(sess.run(y))


#Tensor("MatMul_1:0", shape=(1, 1), dtype=float32)
#[[11.]]

[[11.]] 即爲最終運算結果

前向傳播

一、參數

即線上權重w,用變量表示隨機給初始值

#正態分佈 2*3 標準差 均值 隨機種子
w=tf.Variable(tf.random_normal([2,3],stddev=2,mean=0,seed=1))                         
#去掉過大偏離點的正態分佈
tf.truncated_normal(shape=[10,10], mean=0, stddev=1) 
#平均分佈
tf.random_uniform((6,6), minval=-0.5,maxval=0.5, dtype=tf.float32)

建立全爲某數的數組

#0
tf.zeros([3,2],tf.int32)
#1
tf.ones([3,2],tf.int32)
#任意數
tf.fill([3,2],6)

二、神經網絡實現過程

  1. 準備數據集,提取特徵,作爲輸入餵給神經網絡(NN)
  2. 搭建NN結構,從輸入到輸出(先搭建計算圖,再用會話執行)
  3. 大量特徵數據餵給NN,迭代優化NN參數
  4. 使用訓練好的模型預測和分類

全連接網絡

  1. X的輸入爲1*2矩陣;W爲待優化的參數
  2. W(1) 爲2*3的矩陣
  3. a(1) 爲1*3的矩陣=XW(1)
  4. W(2) 爲3*1的矩陣 y=a(1)W(2)
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結構)實現

  1. 變量初始化
  2. 計算圖節點運算sess.run()
  3. placeholder佔位,再sess.run中feed_dict喂數據
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 tf 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))

# y in tf 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]]

反向傳播

訓練模型參數,在所有參數上用梯度下降使NN模型在訓練數據上loss函數最小

一、loss函數

預測值loss:預測值(y)與已知答案(y_)的差值

二、均方誤差MSE

MSE(y',y)=\frac{ \sum(y-y')^{2} }{n}

#均方誤差
loss = tf.reduce_mean(tf.square(y-y_))

三、反向傳播訓練方法:以減小loss值爲優化目標

train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
train_step=tf.train.MomentumOptimizer(learning_rate,momentum).minimize(loss)
train_step=tf.train.AdamOptimizer(learning_rate).minimize(loss)

四、學習率learning_rate

決定參數每次更新的幅度

代碼舉例

import tensorflow as tf
import numpy as np
BATCH_SIZE = 8
seed=23455
#基於seed值產生隨機數
rng= np.random.RandomState(seed)
#隨機數返回32行2列的矩陣 表示32組 體積和重量作爲輸入數據集
X=rng.rand(32,2)
#從X這32行2列中取一行,判斷如果加和 小於1 y=1 若不小於1 y=0,作爲數據集標籤
Y=[[int(x0+x1<1)] for (x0,x1) in X ]
print(X)
print(Y)

定義輸入輸出前向傳播過程

x = tf.placeholder(tf.float32,shape=(None,2))
y_= tf.placeholder(tf.float32,shape=(None,1))

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)

定義損失函數及反向傳播方法

loss = tf.reduce_mean(tf.square(y-y_))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

生成會話,訓練STEPS輪

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print(sess.run(w1))
    print(sess.run(w2))
    STEPS = 5000
    for i in range(STEPS):
        
        start = (i*BATCH_SIZE)%32
        end = start+BATCH_SIZE
        sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
        
        if (i %500) ==0:
            total_loss = sess.run(loss,feed_dict={x: X,y_:Y})
            print("after",i,"loss is",total_loss)
            print("\n")
            print(sess.run(w1))
            print(sess.run(w2))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章