實驗8-1tensorboard視覺化+實驗8-2tensorboard案例

阿飞藏泪發表於2024-04-27

版本python3.7 tensorflow版本為tensorflow-gpu版本2.6

實驗8-1tensorboard視覺化執行結果:

程式碼:

import tensorflow as tf

# 建立預設圖
graph = tf.compat.v1.get_default_graph()

# 定義名稱空間
with graph.as_default():
    with tf.name_scope('input'):
        # fetch:就是同時執行多個op的意思
        input1 = tf.constant(3.0, name='A')  # 定義名稱,會在tensorboard中代替顯示
        input2 = tf.constant(4.0, name='B')
        input3 = tf.constant(5.0, name='C')
    with tf.name_scope('op'):
        # 加法
        add = tf.add(input2, input3)
        # 乘法
        mul = tf.multiply(input1, add)

    with tf.compat.v1.Session() as ss:
        # 預設在當前py目錄下的logs資料夾,沒有會自己建立
        result = ss.run([mul, add])
        # 使用create_file_writer建立一個檔案寫入器
        writer = tf.summary.create_file_writer('logs/demo/')
        # 在這個上下文中,所有的tensorboard操作都會被寫入logs/demo/目錄中
        with writer.as_default():
            # 將計算圖寫入日誌檔案
            tf.summary.trace_on(graph=True, profiler=True)
            # 執行計算
            tf.summary.trace_export(name="model_trace", step=0, profiler_outdir='logs/demo/')
        print(result)

實驗8-2tensorboard案例執行結果:

程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import os
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
max_steps = 200  # 最大迭代次數 預設1000
learning_rate = 0.001   # 學習率
dropout = 0.9   # dropout時隨機保留神經元的比例

data_dir = os.path.join('data', 'mnist')# 樣本資料儲存的路徑
if not os.path.exists('log'):
    os.mkdir('log')
log_dir = 'log'   # 輸出日誌儲存的路徑
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
sess = tf.compat.v1.InteractiveSession()

with tf.name_scope('input'):
    tf.compat.v1.disable_eager_execution()
    x = tf.compat.v1.placeholder(tf.float32, [None, 784], name='x-input')
    y_ = tf.compat.v1.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)
    
def weight_variable(shape):
    """Create a weight variable with appropriate initialization."""
    initial = tf.random.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    """Create a bias variable with appropriate initialization."""
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def variable_summaries(var):
    """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
    with tf.name_scope('summaries'):
      # 計算引數的均值,並使用tf.summary.scaler記錄
      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.scaler記錄記錄下標準差,最大值,最小值
      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)
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
    """Reusable code for making a simple neural net layer.
    It does a matrix multiply, bias add, and then uses relu to nonlinearize.
    It also sets up name scoping so that the resultant graph is easy to read,
    and adds a number of summary ops.
    """
    # 設定名稱空間
    with tf.name_scope(layer_name):
      # 呼叫之前的方法初始化權重w,並且呼叫引數資訊的記錄方法,記錄w的資訊
      with tf.name_scope('weights'):
        weights = weight_variable([input_dim, output_dim])
        variable_summaries(weights)
      # 呼叫之前的方法初始化權重b,並且呼叫引數資訊的記錄方法,記錄b的資訊
      with tf.name_scope('biases'):
        biases = bias_variable([output_dim])
        variable_summaries(biases)
      # 執行wx+b的線性計算,並且用直方圖記錄下來
      with tf.name_scope('linear_compute'):
        preactivate = tf.matmul(input_tensor, weights) + biases
        tf.summary.histogram('linear', preactivate)
      # 將線性輸出經過激勵函式,並將輸出也用直方圖記錄下來
      activations = act(preactivate, name='activation')
      tf.summary.histogram('activations', activations)

      # 返回激勵層的最終輸出
      return activations

hidden1 = nn_layer(x, 784, 500, 'layer1')

with tf.name_scope('dropout'):
    tf.compat.v1.disable_eager_execution()
    keep_prob = tf.compat.v1.placeholder(tf.float32)
    tf.compat.v1.summary.scalar('dropout_keep_probability', keep_prob)
    dropped = tf.nn.dropout(hidden1, keep_prob)
    
y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)
with tf.name_scope('loss'):
    # 計算交叉熵損失(每個樣本都會有一個損失)
    diff = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)
    with tf.name_scope('total'):
      # 計算所有樣本交叉熵損失的均值
      cross_entropy = tf.reduce_mean(diff)

tf.summary.scalar('loss', cross_entropy)

with tf.name_scope('train'):
    train_step = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(
        cross_entropy)
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
      # 分別將預測和真實的標籤中取出最大值的索引,弱相同則返回1(true),不同則返回0(false)
      correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    with tf.name_scope('accuracy'):
      # 求均值即為準確率
      accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        
tf.summary.scalar('accuracy', accuracy)
# summaries合併
merged = tf.compat.v1.summary.merge_all()
# 寫到指定的磁碟路徑中
#刪除src路徑下所有檔案
def delete_file_folder(src):
    '''delete files and folders'''
    if os.path.isfile(src):
        try:
            os.remove(src)
        except:
            pass
    elif os.path.isdir(src):
        for item in os.listdir(src):
            itemsrc=os.path.join(src,item)
            delete_file_folder(itemsrc) 
        try:
            os.rmdir(src)
        except:
            pass
#刪除之前生成的log
if os.path.exists(log_dir + '/train'):
    delete_file_folder(log_dir + '/train')
if os.path.exists(log_dir + '/test'):
    delete_file_folder(log_dir + '/test')
train_writer = tf.compat.v1.summary.FileWriter(log_dir + '/train', sess.graph)
test_writer = tf.compat.v1.summary.FileWriter(log_dir + '/test')

# 執行初始化所有變數
tf.compat.v1.global_variables_initializer().run()

def feed_dict(train):
    """Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
    if train:
      xs, ys = mnist.train.next_batch(100)
      k = dropout
    else:
      xs, ys = mnist.test.images, mnist.test.labels
      k = 1.0
    return {x: xs, y_: ys, keep_prob: k}

for i in range(max_steps):
    if i % 10 == 0:  # 記錄測試集的summary與accuracy
      summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
      test_writer.add_summary(summary, i)
      print('Accuracy at step %s: %s' % (i, acc))
    else:  # 記錄訓練集的summary
      if i % 100 == 99:  # Record execution stats
        run_options = tf.compat.v1.RunOptions(trace_level=tf.compat.v1.RunOptions.FULL_TRACE)
        run_metadata = tf.compat.v1.RunMetadata()
        summary, _ = sess.run([merged, train_step],
                              feed_dict=feed_dict(True),
                              options=run_options,
                              run_metadata=run_metadata)
        train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
        train_writer.add_summary(summary, i)
        print('Adding run metadata for', i)
      else:  # Record a summary
        summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
        train_writer.add_summary(summary, i)

train_writer.close()
test_writer.close()

相關文章