TensorFlow MNIST TensorBoardの例題
    • PDF

    TensorFlow MNIST TensorBoardの例題

    • PDF

    Article Summary

    Classic/VPC環境で利用できます。

    TensorFlow MNIST TensorBoard の例題

    この例題は [7. TensorFlow MNIST 回帰モデル] の例題にTensorBoardを追加した例題です。

    例題を実行すると基本で提供されるテンソルボードログディレクトリ(/home/ncp/workspace/tensorboard)にログファイルが生成されます。ウェブブラウザから[パブリックIPアドレス:18889]にアクセスするとTensorBoardからログを確認できます。アクセス環境の設定に関する詳しい方法は "アクセス環境の設定"をご参照ください。

    例題コードは TensorFlowホームページから提供されるTensorFlow初級者のためのMNIST基礎例題を使用しました。 MNISTデータセットを利用してSoftmax回帰モデルを作成し、モデルがイメージデータでどのような数字であるかを予測するようにする例題をTensorBoardで確認してみます。

    それぞれの概念や用語は例題コードを理解するにあたって必要なレベルでご説明します。正確な理解のためにはMachine Learning及びDeep Learningに関する別途の学習が必要です。

    MNIST データセットのご説明

    MNIST データセットは以下のように手書きの数字イメージをベクターで表示した imagesと、そのイメージが意味することを表すlabelsで成り立っています。下のイメージラベルはそれぞれ5, 0, 4, 1であり、ラベルは0~9まで10個の固有の値で成り立っています。

    tensorflow-1-3-101_ja.png

    MNISTデータセットはまた55,000個の学習データ(mnist.train), 10,000個のテストデータ(mnist.test), 5,000個の検証用データ(mnist.validation)で成り立っており、それぞれは上で説明したimagesとlabelsに分かれます。

    一つのイメージは28x28(=784)ピクセルであるため、これは784次元のベクターで保存されており、784次元には濃さの程度によって0~1の間の値が入っています。

    tensorflow-1-3-102_ja.png

    下のコードを通じてTensorFlowから提供されるデータをダウンロードしてdataフォルダへ保存します。
    'one_hot=True' オプション(one hot encoding)を使用してlabelを0~9間の数字値1つで定義せず10次元ベクターで定義します。one hot encoding データについては以下の例題でもう一度ご説明します。

    """ TensorFlowパッケージ import : 今後tfで使用します。 """
    import tensorflow as tf
    
    """ データダウンロード及びロード
    TensorFlowから提供するMNISTデータファイル4つをダウンロードしてdataフォルダに保存して読み取ります。
    最初に実行の際のみデータをダウンロードし、2回目からは保存されたデータを読み取るだけで済むので時間が短縮されます。"""
    from tensorflow.examples.tutorials.mnist import input_data
    %time mnist = input_data.read_data_sets("data/", one_hot=True)  # %timeを通じて全体の実行時間を残すことができます。
    
    Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
    Extracting data/train-images-idx3-ubyte.gz
    Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
    Extracting data/train-labels-idx1-ubyte.gz
    Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
    Extracting data/t10k-images-idx3-ubyte.gz
    Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
    Extracting data/t10k-labels-idx1-ubyte.gz
    CPU times: user 447 ms, sys: 454 ms, total: 901 ms
    Wall time: 36.1 s
    

    .以下のコードを通じてデータを確認してみると、 imagesは28x28ピクセルを表示する784次元ベクターになっており、labelsは 'one_hot=True' オプション(one hot encoding)を使用してデータを読み取ったため '7'というレベルを '[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]'で表していることが確認できます。(0は[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.], 1は[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.], 2は [ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]で表示).

    # images/labels データセット構造の確認
    print 'train データセット(55,000件):', mnist.train.images.shape, mnist.train.labels.shape
    print 'testデータセット(10,000件):', mnist.test.images.shape, mnist.test.labels.shape
    print 'validation データセット(5,000件):', mnist.validation.images.shape, mnist.validation.labels.shape
    
    print '\n データサンプルの確認(最初のイメージデータ 7)'
    print 'label:', mnist.train.labels[0]
    
    train データセット(55,000件): (55000, 784) (55000, 10)
    test データセット(10,000件): (10000, 784) (10000, 10)
    validation データセット(5,000件): (5000, 784) (5000, 10)
    
     データサンプルの確認(最初のイメージデータ 7)
    label: [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
    

    回帰モデル

    この例題コードはTensorFlowからTensorFlow初級者のために提供されるMNIST基礎例題を取り扱っています。
    回帰モデルを作成して訓練させてからlabelを予測してモデルの正確度を確認してみます。

    Implementing the Regression

    イメージと正解レイブルを盛り込む placeholderと学習結果である荷重値(weight)とバイアス(bias)を盛り込むVariableを定義してSoftmax Regressionモデルを定義します。

    """ placeholder定義 : データが入る所
    イメージと正解レイブル用の2次元tensorを作成する。
    Noneはどんなlengthも可能であるということを意味する。 """
    # イメージデータ用 placeholder
    with tf.name_scope("input") as scope:
        x = tf.placeholder(tf.float32, [None, 784])
    # 正解レイブル用 placeholder
    with tf.name_scope("y_") as scope:
        y_ = tf.placeholder(tf.float32, [None, 10])
    
    """ Variable 定義 : 学習結果が保存される荷重値(weight)とバイアス(bias) """
    # 0に初期化する
    with tf.name_scope("weight") as scope:
        W = tf.Variable(tf.zeros([784, 10]))
    with tf.name_scope("bias") as scope:
        b = tf.Variable(tf.zeros([10]))
    
    """ モデル定義 : Softmax Regression
    10個の値の中、最も確率の高いものを選ぶためSoftmaxを使用 """
    # モデル作成
    with tf.name_scope("layer1") as scope:
        y = tf.nn.softmax(tf.matmul(x, W) + b)
    
    w_hist = tf.summary.histogram("weight", W)
    b_hist = tf.summary.histogram("bias", b)
    y_hist = tf.summary.histogram("y", y)
    

    Training

    モデル訓練が必要なLoss 関数と学習率(Learning Rate)を定義して100個ずつサンプリングしてモデルを1000回学習させます。
    サンプリングのデータ数を増やすと正確度が高まりますが学習時間が増えます。
    ランダムにサンプリングした小さな配置で学習することをStochastic Trainingと言い、コストが安くて比較的似た結果を生み出すことができるため多く使われています。

    """ モデル訓練 """
    # Loss 関数定義
    with tf.name_scope("cost") as scope:
        cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
        #tf.summary.scalar("cost",cross_entropy)
        cost_sum = tf.summary.scalar("cost",cross_entropy)
    # learning rate을 0.5に定義
    with tf.name_scope("train") as scope:
        train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
    
    # Merge all summaries into a single op
    merged = tf.summary.merge_all()
    
    # セッション開始前に全ての変数を初期化する
    init = tf.global_variables_initializer()
    
    sess = tf.Session()
    sess.run(init)
    
    # 基本で提供されるテンソルボードログ dir : /home/ncp/workspace/tensorboard
    writer =tf.summary.FileWriter("/home/ncp/workspace/tensorboard", sess.graph)
    
    # Training : 100個ずつサンプリングして1000回学習を進める
    for i in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(100)  # 学習データセットから無作為でサンプリングした100個のデータで構成された'batch'を呼び出す
        summary, _ = sess.run([merged, train_step], feed_dict={x: batch_xs, y_: batch_ys})  # placeholder x, y_にサンプリングされた batch_xs, batch_ysを供給する
        # write summary events to disk
        writer.add_summary(summary,i)
    
    

    Evaluating Model

    tf.argmaxを通じて最も高い確率のlabelを探し
    tf.equalを通じて予測値(y)と正解(y_)が同じものを探すようにcorrect_predictionとaccuracy tensorを定義します。

    モデルを評価するためにtestデータを利用して正確度を確認します。

    以下では0.9163で約 91%の正確度が確認されましたが、モデルを再度訓練させる度に結果が少しずつ異なってきます。

    """ モデル評価 """
    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    
    # 正確度
    print sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
    
    # 実行が全て終わればSessionを閉じる
    writer.close()
    sess.close()
    
    0.9219
    

    この記事は役に立ちましたか?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.