1. 程式人生 > >Tensorflow學習之旅(7)

Tensorflow學習之旅(7)

暑假就在接觸Tensorflow了,但是一直斷斷續續的,所以現在又開始撿起來繼續學。

PS 我用的程式碼源於https://github.com/zhaozhengcoder/Machine-Learning  大佬寫的很好,我也是跟著他的 程式碼,在他的程式碼上,寫上 自己的理解。https://github.com/flowerflow/Machine-Learning  

import tensorflow as tf

#add_layer 函式裡面所有的with都是為了tensorboard新增上去的
def add_layer(inputs, in_size, out_size, activation_function=None):
    # add one more layer and return the output of this layer
    #查閱了https://blog.csdn.net/uestc_c2_403/article/details/72328815
    #大概意思可以理解為(舉例子,人本來都是人,但是我現在給所有人加上國籍,所以 ABCDF,變成 中國 AB,美國DF,英國C
    #參考上述網址,這樣子方便用過Tnwsorflow的名稱空間進行變數查詢

    with tf.name_scope('layer'):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
            print(Weights.name)
            #結果是 layer/weights/W:0
            #理解為 中國 / 山東 應該沒毛病233
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')

        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b, )
        return outputs
    #這個意思,就是將每一層裡的所有變數,加入了tensorflow的名稱空間
    #PS,上面我加了註釋的那個print,實際輸出 是
    #layer/weights/W:0
    #layer_1/weights/W:0
    #因為我加了兩層,一層是隱藏層,一層是輸出層

# 這個就是在tensorboard上視覺化的時候的區別:
# 使用with tf.name_scope('inputs')可以將xs和ys包含進來
# 形成一個大的圖層,圖層的名字就是with tf.name_scope()方法裡的引數。
with tf.name_scope('inputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name='x_input')  # 這個name的屬性,也是為了使用tensorboard,新增上來的
    ys = tf.placeholder(tf.float32, [None, 1], name='y_input')  # 同上
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
#tf.nn.relu()啟用函式是將大於0的數保持不變,小於0的數置為0
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)
#同上,這裡的with也是一樣的
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
# 上面的wtih或者是name都是可選的,可以選擇新增,也可以選擇不新增,but下面的這一行是一定要寫的。
# 這個表明了 在當前的目錄下面建立以logs的檔案家,然後把圖的資訊儲存進去
# 這樣執行完這段程式碼之後,就會有一個logs的資料夾被建立
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:  # tensorflow version < 0.12
    writer = tf.train.SummaryWriter('logs/', sess.graph)
else: # tensorflow version >= 0.12
    writer = tf.summary.FileWriter("logs/", sess.graph)

###
#這個地方,原作者講的不太明白,實際上就是儲存工作狀態,第一個引數是資料夾名,預設當前檔案目錄,第二個是儲存的內容,
#sess.graph是當前會話的圖
#but,我沒找到如何載入
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()
sess.run(init)


# 這樣執行完這段程式碼之後,就會有一個logs的資料夾被建立,然後在logs的資料夾的目錄下面 執行tensorboard 就可以可視化了
# 執行完這段程式碼之後,在終端執行,下面這句:
# $ tensorboard --logdir=logs
print(tf.get_variable("layer_1/weights/W", [0]) )
#layer/weights/W:0
#layer_1/weights/W:0
#<tf.Variable 'layer_1/weights/W_1:0' shape=(0,) dtype=float32_ref>