Tensorflow搭建神經網絡及使用Tensorboard進行可視化


創建神經網絡模型

1、構建神經網絡結構,並進行模型訓練

 

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt #python的結果可視化模塊

"""定義一個添加神經層的函數
inputs:輸入數據
in_size:輸入神經元的個數
out_size:輸出神經元的個數
activation_function:激活函數
"""
def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
layer_name = 'layer%s' % n_layer
with tf.name_scope(layer_name):
with tf.name_scope("wights"):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W') #定義權重矩陣
#tf.summary.histogram用於保存變量的變化
tf.summary.histogram(layer_name+'/weights', Weights)
with tf.name_scope("biases"):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')#定義偏置
tf.summary.histogram(layer_name + '/biases', biases)
with tf.name_scope("Wx_plus_b"):
Wx_plus_b = tf.matmul(inputs, Weights) + biases #預測出的值
if activation_function is None:
outputs = Wx_plus_b #線性激活
else:
outputs = activation_function(Wx_plus_b) #非線性激活
tf.summary.histogram(layer_name + '/outputs', outputs)
return outputs

"""創建數據"""
#定義輸入,linspace產生等差數列,加上數據的維度,定義輸入數據為300個例子
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
# print(x_data.shape)
noise = np.random.normal(0, 0.05, x_data.shape) #定義噪聲點
y_data = np.square(x_data) - 0.5 + noise # y=x_data*x_data - 0.5

"""定義網絡
輸入層:1個神經元(使用輸入的一個元素)
隱藏層:定義10個神經元
輸出層:1個神經元(1個輸入對應一個輸出)
"""
#定義命名空間,使用tensorboard進行可視化
with tf.name_scope("inputs"):
xs = tf.placeholder(tf.float32, [None, 1], name="x_input") #模型的輸入x值
ys = tf.placeholder(tf.float32, [None, 1], name="y_input") #模型的輸入y值

#隱藏層
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
#輸出層
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)

#損失函數
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),
reduction_indices=[1]))
tf.summary.scalar('loss', loss) #用於觀察常量的變化
#模型訓練
with tf.name_scope("train"):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer() #初始化所有變量
with tf.Session() as sess:
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("logs/", sess.graph) #保存神經網絡的所有的信息,方便瀏覽器訪問
sess.run(init)

for i in range(1001):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:#每訓練50次,合並一下結果
result = sess.run(merged, feed_dict={xs: x_data, ys: y_data})
writer.add_summary(result, i)
"""
fig = plt.figure() #定義一個圖片框
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data) #輸出樣本值
plt.ion() #防止plt后程序暫停
plt.show() #一次輸出,將程序暫停

for i in range(1001):
sess.run(train_step, feed_dict={xs:x_data,ys:y_data})
if i % 50 == 0:
# print(i, sess.run(loss, feed_dict={xs:x_data,ys:y_data}))
try:
ax.lines.remove(lines[0]) # 去除lines的第一個線條
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs:x_data})
lines = ax.plot(x_data, prediction_value, 'r-', lw=5) #將預測的值plot上去
plt.gca()
plt.pause(0.1) #每0.1秒輸出一次
"""

 

 

2、可視化模型的參數變化等操作

  使用tensorboard進行可視化

    1、將需要可視化的操作保存在‘logs’文件夾下

    2、cmd進入logs文件夾所在的父文件路徑

    3、tensorboard --logdir=logs

    4、在瀏覽器中訪問3中命令返回的ip地址

  結果展示如下:

    

    

    

    

3、問題解決

  開始訓練完模型后無法顯示graph。解決方法:必須在lcmd中進入'logs'文件夾的父路徑中,在鍵入tensorboard命令,盡量使用Chrom瀏覽器,其他的瀏覽器可能會遇到不兼容的問題。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM