tensorBoard可視化

先看看這個遗嗽,知道使用目的:
http://www.tensorfly.cn/tfdoc/how_tos/summaries_and_tensorboard.html
然后上代碼:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.tensorboard.plugins import projector

#載入數(shù)據(jù)集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#運行次數(shù)
max_steps = 1001
#圖片數(shù)量
image_num = 3000
#文件路徑
DIR = "/Users/yyzanll/Desktop/my_tensorflow/"

#定義會話
sess = tf.Session()

#載入圖片
embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')

#參數(shù)概要
def variable_summaries(var):
    with tf.name_scope('summaries'):
        mean = tf.reduce_mean(var)
        tf.summary.scalar('mean', mean)#平均值
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
        tf.summary.scalar('stddev', stddev)#標準差
        tf.summary.scalar('max', tf.reduce_max(var))#最大值
        tf.summary.scalar('min', tf.reduce_min(var))#最小值
        tf.summary.histogram('histogram', var)#直方圖

#命名空間
with tf.name_scope('input'):
    #這里的none表示第一個維度可以是任意的長度
    x = tf.placeholder(tf.float32,[None,784],name='x-input')
    #正確的標簽
    y = tf.placeholder(tf.float32,[None,10],name='y-input')

#顯示圖片
with tf.name_scope('input_reshape'):
    image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
    tf.summary.image('input', image_shaped_input, 10)

with tf.name_scope('layer'):
    #創(chuàng)建一個簡單神經(jīng)網(wǎng)絡(luò)
    with tf.name_scope('weights'):
        W = tf.Variable(tf.zeros([784,10]),name='W')
        variable_summaries(W)
    with tf.name_scope('biases'):
        b = tf.Variable(tf.zeros([10]),name='b')
        variable_summaries(b)
    with tf.name_scope('wx_plus_b'):
        wx_plus_b = tf.matmul(x,W) + b
    with tf.name_scope('softmax'):    
        prediction = tf.nn.softmax(wx_plus_b)

with tf.name_scope('loss'):
    #交叉熵代價函數(shù)
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
    tf.summary.scalar('loss',loss)
with tf.name_scope('train'):
    #使用梯度下降法
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化變量
sess.run(tf.global_variables_initializer())

with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        #結(jié)果存放在一個布爾型列表中
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        #求準確率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#把correct_prediction變?yōu)閒loat32類型
        tf.summary.scalar('accuracy',accuracy)

#產(chǎn)生metadata文件
if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):
    tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv')
with open(DIR + 'projector/projector/metadata.tsv', 'w') as f:
    labels = sess.run(tf.argmax(mnist.test.labels[:],1))
    for i in range(image_num):   
        f.write(str(labels[i]) + '\n')        
        
#合并所有的summary
merged = tf.summary.merge_all()   


projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph)
saver = tf.train.Saver()
config = projector.ProjectorConfig()
embed = config.embeddings.add()
embed.tensor_name = embedding.name
embed.metadata_path = DIR + 'projector/projector/metadata.tsv'
embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'
embed.sprite.single_image_dim.extend([28,28])
projector.visualize_embeddings(projector_writer,config)

for i in range(max_steps):
    #每個批次100個樣本
    batch_xs,batch_ys = mnist.train.next_batch(100)
    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
    run_metadata = tf.RunMetadata()
    summary,_ = sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata)
    projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)
    projector_writer.add_summary(summary, i)
    
    if i%100 == 0:
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print ("Iter " + str(i) + ", Testing Accuracy= " + str(acc))

saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps)
projector_writer.close()
sess.close()

我遇到報錯:

InvalidArgumentError: You must feed a value for placeholder tensor ‘inputs/x_input’ with dtype float

我就把/Users/yyzanll/Desktop/my_tensorflow/projector/projector路徑下的內(nèi)容全部刪了粘我,重新跑。
然后打開終端

yyzanlldeMacBook-Pro:~ yyzanll$ cd /Users/yyzanll/Desktop/my_tensorflow/projector/projector 
yyzanlldeMacBook-Pro:projector yyzanll$ tensorboard --logdir=/Users/yyzanll/Desktop/my_tensorflow/projector/projector
/Library/Python/2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
Starting TensorBoard 47 at http://0.0.0.0:6006

上面有Summary,想知道Summary是干嘛的痹换?

Summary

Summary被收集在名為tf.GraphKeys.SUMMARIES的colletion中征字,Summary是對網(wǎng)絡(luò)中Tensor取值進行監(jiān)測的一種Operation都弹。這些操作在圖中是“外圍”操作,不影響數(shù)據(jù)流本身匙姜。
網(wǎng)上抄個例子:

# 迭代的計數(shù)器
global_step = tf.Variable(0, trainable=False)
# 迭代的+1操作
increment_op = tf.assign_add(global_step, tf.constant(1))
# 實例應(yīng)用中畅厢,+1操作往往在`tf.train.Optimizer.apply_gradients`內(nèi)部完成。

# 創(chuàng)建一個根據(jù)計數(shù)器衰減的Tensor
lr = tf.train.exponential_decay(0.1, global_step, decay_steps=1, decay_rate=0.9, staircase=False)

# 把Tensor添加到觀測中
tf.scalar_summary('learning_rate', lr)

# 并獲取所有監(jiān)測的操作`sum_opts`
sum_ops = tf.merge_all_summaries()

# 初始化sess
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)  # 在這里global_step被賦初值

# 指定監(jiān)測結(jié)果輸出目錄
summary_writer = tf.train.SummaryWriter('/tmp/log/', sess.graph)

# 啟動迭代
for step in range(0, 10):
    s_val = sess.run(sum_ops)    # 獲取serialized監(jiān)測結(jié)果:bytes類型的字符串
    summary_writer.add_summary(s_val, global_step=step)   # 寫入文件
    sess.run(increment_op)     # 計數(shù)器+1

調(diào)用tf.scalar_summary系列函數(shù)時氮昧,就會向默認的collection中添加一個Operation框杜。
再次回顧“零存整取”原則:創(chuàng)建網(wǎng)絡(luò)的各個層次都可以添加監(jiān)測;在添加完所有監(jiān)測郭计,初始化sess之前霸琴,統(tǒng)一用tf.merge_all_summaries獲取椒振。
SummaryWriter文件中存儲的是序列化的結(jié)果昭伸,需要借助TensorBoard才能查看。
在命令行中運行tensorboard澎迎,傳入存儲SummaryWriter文件的目錄:

tensorboard --logdir /tmp/log

自定義collection

除了默認的集合庐杨,我們也可以自己創(chuàng)造collection組織對象。網(wǎng)絡(luò)損失就是一類適宜對象夹供。
tensorflow中的Loss提供了許多創(chuàng)建損失Tensor的方式灵份。

x1 = tf.constant(1.0)
l1 = tf.nn.l2_loss(x1)

x2 = tf.constant([2.5, -0.3])
l2 = tf.nn.l2_loss(x2)

創(chuàng)建損失不會自動添加到集合中,需要手工指定一個collection:

tf.add_to_collection("losses", l1)
tf.add_to_collection("losses", l2)

創(chuàng)建完成后哮洽,可以統(tǒng)一獲取所有損失填渠,losses是個Tensor類型的list:

losses = tf.get_collection('losses')

另一種常見操作把所有損失累加起來得到一個Tensor:

loss_total = tf.add_n(losses)

執(zhí)行操作可以得到損失取值:

sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
losses_val = sess.run(losses)
loss_total_val = sess.run(loss_total)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市鸟辅,隨后出現(xiàn)的幾起案子氛什,更是在濱河造成了極大的恐慌,老刑警劉巖匪凉,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件枪眉,死亡現(xiàn)場離奇詭異,居然都是意外死亡再层,警方通過查閱死者的電腦和手機贸铜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來聂受,“玉大人蒿秦,你說我怎么就攤上這事〉凹茫” “怎么了棍鳖?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長瘫俊。 經(jīng)常有香客問我鹊杖,道長悴灵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任骂蓖,我火速辦了婚禮积瞒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘登下。我一直安慰自己茫孔,他們只是感情好,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布被芳。 她就那樣靜靜地躺著缰贝,像睡著了一般。 火紅的嫁衣襯著肌膚如雪畔濒。 梳的紋絲不亂的頭發(fā)上剩晴,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天,我揣著相機與錄音侵状,去河邊找鬼赞弥。 笑死,一個胖子當著我的面吹牛趣兄,可吹牛的內(nèi)容都是我干的绽左。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼艇潭,長吁一口氣:“原來是場噩夢啊……” “哼拼窥!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起蹋凝,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鲁纠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后仙粱,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體房交,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年伐割,在試婚紗的時候發(fā)現(xiàn)自己被綠了候味。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡隔心,死狀恐怖白群,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情硬霍,我是刑警寧澤帜慢,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響粱玲,放射性物質(zhì)發(fā)生泄漏躬柬。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一抽减、第九天 我趴在偏房一處隱蔽的房頂上張望允青。 院中可真熱鬧,春花似錦卵沉、人聲如沸颠锉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽琼掠。三九已至,卻和暖如春停撞,著一層夾襖步出監(jiān)牢的瞬間瓷蛙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工怜森, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留速挑,地道東北人谤牡。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓副硅,卻偏偏與公主長得像,于是被迫代替她去往敵國和親翅萤。 傳聞我的和親對象是個殘疾皇子恐疲,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容