【ディープラーニング】実験08 TensorBoardの場合

TensorBoard視覚化

import tensorflow as tf

# 定义命名空间
with tf.name_scope('input'):
  # fetch:就是同时运行多个op的意思
  # 定义名称,会在tensorboard中代替显示
  
    input1 = tf.constant(3.0,name='A')
    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.Session() as ss:
    #默认在当前py目录下的logs文件夹,没有会自己创建
    result = ss.run([mul,add])
    wirter = tf.summary.FileWriter('logs/demo/',ss.graph)
    print(result)
[27.0, 9.0]

このコードは主に、TensorFlow と TensorBoard を使用して計算グラフを作成および視覚化する方法を示します。

TensorFlow は、データフローグラフに基づく数値計算を行うオープンソースのソフトウェアライブラリであり、高速な計算速度と柔軟な構築手法を備えており、機械学習や深層学習などの分野で広く利用されています。TensorBoard は TensorFlow によって提供される視覚化ツールで、開発者が TensorFlow の計算グラフをより深く理解し、デバッグし、最適化するのに役立ちます。

このコードでは、最初に 3 つの定数およびがtf.constantメソッドによって作成され、それぞれ値 3.0、4.0、および 5.0 が割り当てられ、これらの定数には「A」、「B」、および「C」という別名が与えられます。その後の TensorBoard でそれらの間の関係を明確に見ることができます。input1input2input3

次に、tf.addandtf.multiplyメソッドを使用して加算と乗算の演算をそれぞれ定義します。加算では合計が使用され、乗算input2では加算の結果がinput3使用されます。input12 つの名前空間inputともここで定義されておりop、それぞれ入力プロセスと操作プロセスを表します。

次に、メソッドwith tf.Session() as ss:を使用してセッションを作成し、ss.runグラフを実行し、結果を保存しますresult

最後に、tf.summary.FileWriter計算グラフをlogs/demo/TensorBoard で表示するためのディレクトリに書き込むメソッドを使用します。を実行した後python 文件名.py、コマンド ラインに を入力してtensorboard --logdir=logs/demoTensorBoard サービスを開始し、ブラウザを開いて を入力してhttp://localhost:6006/TensorBoard ビジュアル インターフェイスにアクセスします。

TensorBoard インターフェイスでは、計算グラフの視覚的な構造、定数の値、操作プロセス、その他の情報を表示でき、開発者が TensorFlow の計算グラフをよりよく理解、デバッグ、最適化するのに役立ちます。

TensorBoard のケース

#!/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
import warnings
warnings.filterwarnings("ignore")

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.InteractiveSession()

with tf.name_scope('input'):
    x = tf.placeholder(tf.float32, [None, 784], name='x-input')
    y_ = tf.placeholder(tf.float32, [None, 10], name='y-input')

#使用tf.summary.image保存图像信息,在tensorboard上还原出输入的特征数据对应的图片
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.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)

"""
构建神经网络层
创建第一层隐藏层
创建一个构建隐藏层的方法,输入的参数有:
input_tensor:特征数据
input_dim:输入数据的维度大小
output_dim:输出数据的维度大小(=隐层神经元个数)
layer_name:命名空间
act=tf.nn.relu:激活函数(默认是relu)
"""
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')

"""
创建一个dropout层,,随机关闭掉hidden1的一些神经元,并记录keep_prob
"""
with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    tf.summary.scalar('dropout_keep_probability', keep_prob)
    dropped = tf.nn.dropout(hidden1, keep_prob)
"""
创建一个输出层,输入的维度是上一层的输出:500,输出的维度是分类的类别种类:10,
激活函数设置为全等映射identity.(暂且先别使用softmax,会放在之后的损失函数中一起计算)
"""
y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)

"""
创建损失函数
使用tf.nn.softmax_cross_entropy_with_logits来计算softmax并计算交叉熵损失,并且求均值作为最终的损失值。
"""

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)

"""
训练,并计算准确率
使用AdamOptimizer优化器训练模型,最小化交叉熵损失
计算准确率,并用tf.summary.scalar记录准确率
"""

with tf.name_scope('train'):
    train_step = tf.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.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.summary.FileWriter(log_dir + '/train', sess.graph)
test_writer = tf.summary.FileWriter(log_dir + '/test')

# 运行初始化所有变量
tf.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}

"""
开始训练模型。 每隔10步,就进行一次merge, 并打印一次测试数据集的准确率,
然后将测试数据集的各种summary信息写进日志中。 每隔100步,记录原信息 
其他每一步时都记录下训练集的summary信息并写到日志中。
"""

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.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
            run_metadata = tf.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()
   WARNING:tensorflow:From <ipython-input-3-27b4be5f38e0>:25: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
   Instructions for updating:
   Please use alternatives such as official/mnist/dataset.py from tensorflow/models.
   WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.
   Instructions for updating:
   Please write your own downloading logic.
   WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
   Instructions for updating:
   Please use tf.data to implement this functionality.
   Extracting MNIST_data/train-images-idx3-ubyte.gz
   WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
   Instructions for updating:
   Please use tf.data to implement this functionality.
   Extracting MNIST_data/train-labels-idx1-ubyte.gz
   WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
   Instructions for updating:
   Please use tf.one_hot on tensors.
   Extracting MNIST_data/t10k-images-idx3-ubyte.gz
   Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
   WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.
   Instructions for updating:
   Please use alternatives such as official/mnist/dataset.py from tensorflow/models.
   WARNING:tensorflow:From <ipython-input-3-27b4be5f38e0>:109: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
   Instructions for updating:
   Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.
   WARNING:tensorflow:From <ipython-input-3-27b4be5f38e0>:123: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
   Instructions for updating:
   
   Future major versions of TensorFlow will allow gradients to flow
   into the labels input on backprop by default.
   
   See `tf.nn.softmax_cross_entropy_with_logits_v2`.
   
   Accuracy at step 0: 0.0639
   Accuracy at step 10: 0.7139
   Accuracy at step 20: 0.8271
   Accuracy at step 30: 0.8647
   Accuracy at step 40: 0.8818
   Accuracy at step 50: 0.8932
   Accuracy at step 60: 0.8984
   Accuracy at step 70: 0.8986
   Accuracy at step 80: 0.9062
   Accuracy at step 90: 0.9128
   Adding run metadata for 99
   Accuracy at step 100: 0.9134
   Accuracy at step 110: 0.9212
   Accuracy at step 120: 0.9156
   Accuracy at step 130: 0.9226
   Accuracy at step 140: 0.9251
   Accuracy at step 150: 0.9238
   Accuracy at step 160: 0.9259
   Accuracy at step 170: 0.9265
   Accuracy at step 180: 0.9291
   Accuracy at step 190: 0.932
   Adding run metadata for 199    

このコードは主に、Tensorflow と TensorBoard を使用して畳み込みニューラル ネットワーク (CNN) を作成および視覚化する方法を示しています。

CNN は、画像認識、音声認識、その他の分野に適用できる深層学習構造であり、ニューラル ネットワークの一種です。このコードでは、CNN を使用して MNIST 手書き数字認識タスクを完了します。入力は 28×28 ピクセルの手書き数字画像で、出力は 0 ~ 9 のいずれかの数字の確率です。

まず、メソッドを通じてtf.placeholder2 つのプレースホルダー変数 x と y_ が作成され、それぞれネットワークの入力と出力を表します。入力データの処理では、入力データ(28×28ピクセル)を可視化するために、入力画像のサイズが28×28×1になるようにtf.summary.image画像情報を記録し、入力特徴データを再構成します。 reshape. 、そして .tf.summary.imageで記録します。

次に、ニューラル ネットワークの構築に関して、2 つの隠れ層と 1 つの出力層を作成しました。このうち、各隠れ層には線形計算層とReLU活性化関数層があり、tf.summary.histogram各層の関連パラメータはTensorBoard上で各層の変化を確認できるメソッドを用いて記録されている。

次に、dropout最初の隠れ層の後に層を追加し、過剰適合を避けるために特定の割合のニューロンをランダムにオフにしました。出力層では、tf.nn.softmax cross_entropy_with_logitsこの方法を使用してクロスエントロピー損失が計算され、tf.summary.scalarその方法を使用して損失情報が記録されます。tf.train.AdamOptimizerを使用してモデルをトレーニングし、 を使用tf.reduce_mean(tf.cast(correct_prediction, tf.float32))して精度を計算し、tf.summary.scalarを使用して精度情報を記録します。

最後に、変数を定義しmerged、記録する必要があるすべての情報をまとめ、tf.summary.merge_all()メソッドを通じてそれらすべてをマージし、最後にtf.summary.FileWriterメソッドを通じてすべての情報をログ ファイルに書き込みました。トレーニング プロセス中、テスト セットの精度と関連情報は 10 ステップごとに記録され、ログに記録されます。トレーニング セットの元の情報は 100 ステップごとに記録され、ログに記録されます。他のトレーニング ステップは記録されます。セットの内容がログに書き込まれます。最終的に、ログ ファイルは渡されてtrain_writer.close()閉じtest_writer.close()られます。

コード全体を通して、名前空間の使用法が標準化されており、各パラメーターの記録方法が明確であり、TensorBoard の各レイヤーのパラメーターの変化、損失の変化、精度の変化などが明確に理解できます。したがって、TensorBoard は、開発者がモデルをデバッグ、分析、最適化するのに十分役立ちます。

添付ファイル: 一連の記事

シリアルナンバー 記事ディレクトリ 直接リンク
1 ボストンの住宅価格予測 https://want595.blog.csdn.net/article/details/132181950
2 アイリスデータセット分析 https://want595.blog.csdn.net/article/details/132182057
3 特徴処理 https://want595.blog.csdn.net/article/details/132182165
4 相互検証 https://want595.blog.csdn.net/article/details/132182238
5 ニューラルネットワークの構築例 https://want595.blog.csdn.net/article/details/132182341
6 TensorFlow を使用した完全な線形回帰 https://want595.blog.csdn.net/article/details/132182417
7 TensorFlow を使用した完全なロジスティック回帰 https://want595.blog.csdn.net/article/details/132182496
8 TensorBoard のケース https://want595.blog.csdn.net/article/details/132182584
9 Keras を使用した完全な線形回帰 https://want595.blog.csdn.net/article/details/132182723
10 Keras を使用した完全なロジスティック回帰 https://want595.blog.csdn.net/article/details/132182795
11 Keras の事前トレーニング済みモデルを使用した完全な猫と犬の認識 https://want595.blog.csdn.net/article/details/132243928
12 PyTorch を使用したモデルのトレーニング https://want595.blog.csdn.net/article/details/132243989
13 ドロップアウトを使用してオーバーフィッティングを抑制する https://want595.blog.csdn.net/article/details/132244111
14 CNN を使用して MNIST 手書き認識を完了する (TensorFlow) https://want595.blog.csdn.net/article/details/132244499
15 CNN を使用して MNIST 手書き認識を完了する (Keras) https://want595.blog.csdn.net/article/details/132244552
16 CNN を使用して MNIST 手書き認識を完了する (PyTorch) https://want595.blog.csdn.net/article/details/132244641
17 GAN を使用して手書き数字サンプルを生成する https://want595.blog.csdn.net/article/details/132244764
18 自然言語処理 https://want595.blog.csdn.net/article/details/132276591

おすすめ

転載: blog.csdn.net/m0_68111267/article/details/132182584