tensorflow將搭建網絡與計算網絡中的數值進行了割裂,也就是說在搭建網絡階段並不計算數值。
一、計算圖
如以下代碼:
# coding:utf-8
# 0導入模塊 ,生成模擬數據集
import tensorflow as tf
# 定義神經網絡的輸入、參數和輸出,定義前向傳播過程
def get_weight(shape, regularizer):
w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)
tf.add_to_collection(
'losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
return w
def get_bias(shape):
b = tf.Variable(tf.constant(0.01, shape=shape))
return b
def forward(x, regularizer):
w1 = get_weight([2, 11], regularizer)
b1 = get_bias([11])
y1 = tf.nn.relu(tf.matmul(x, w1) + b1)
w2 = get_weight([11, 1], regularizer)
b2 = get_bias([1])
y = tf.matmul(y1, w2) + b2
return y
其中,get_weight是獲得權重的函數,get_bias是獲得偏置的函數,forward是描述神經網絡的前向傳播過程的函數,也就是tensorflow中的計算圖,在執行此代碼段時神經網絡並不計算任何中間值。
二、會話(session)
創建會話對象後,可以使用 sess.run (node) 返回節點的值,並且 Tensorflow 將執行確定該值所需的所有計算。
假設我們有一組原始數據x,使用上面的forward搭建神經網絡。
y = forward(x, REGULARIZER)
with tf.Session() as sess:
print(sess.run(y))
第一行代碼是搭建計算圖,第二行代碼是實例化tf.Session(),第三行是打印出y的值。sess.run(y)返回y的值。