tensorflowを用いてmnist上でLeNetモデルを訓練しテストする

25036 ワード

1.MNISTデータセットのダウンロードとその紹介


MNISTデータセットは、60000行のトレーニングデータセット(mnist.train)と10000行のテストデータセット(mnist.test)の2つの部分に分かれています.各MNISTデータユニットには、手書きの数字を含む画像と対応するラベルの2つの部分があります.訓練データセットの画像はmnistです.train.images、トレーニングデータセットのラベルはmnistです.train.labels.各ピクチャには28×28ピクセルポイントが含まれています.この配列をベクトルに展開し,長さは28 x 28=784であった.そこで、MNISTトレーニングデータセットでは、mnist.train.imagesは[60000,784]の形状のテンソルであり、第1の次元数字はピクチャをインデックスし、第2の次元数字は各ピクチャの画素点をインデックスするために使用される.このテンソルの各要素は、あるピクチャのある画素の強度値を表し、値は0と1の間にある.対応するMNISTデータセットのラベルは、所与のピクチャで表される数字を記述するために0〜9の数字である.ここで使用するラベルデータは「one-hot vectors」です.1つのone-hotベクトルは、あるビットの数字が1である以外の各次元の数字は0である.したがって、数字nは、n次元(0から)の数字が1の10次元ベクトルのみを表す.たとえば、ラベル0は([1,0,0,0,0,0,0,0,0,0,0])と表示されます.だから、mnist.train.Labelsは[60000,10]の数値行列である.

2.実現プロセス


2.1 tensorflow環境


クラスタにtensorflowモジュールが事前にインストールされていない場合は、cacheArchiveパラメータの特性を使用して構成できます.方法は次のとおりです.-TensorFlowのライブラリをパッケージ化し、依存するライブラリは環境でインストールしたり、依存するすべてのライブラリをパッケージ化したりすることができます.例えばtar-zcvf tensorflow.tgz ./* - この圧縮パケットをhdfsの/tmp/tensorflowなどのhdfsにアップロードする.tgz-xlearningコミットスクリプトでは、-cacheArchive/tmp/tensorflowなどのcacheArchiveパラメータを追加します.tgz#tensorflow-launch-cmdで実行されるスクリプトに、環境変数設定を追加します:export PYTHONPATH=./:$PYTHONPATH
tensorflow依存ライブラリのインストール
yum install numpy python-devel python-wheel

2.2トレーニングモデル


ディレクトリへのアクセス
cd /var/lib/ambari-server/resources/stacks/CRH/5.1/services/XLEARNING/xlearning-1.2/examples/tfmnist
export XLEARNING_HOME=/var/lib/ambari-server/resources/stacks/CRH/5.1/services/XLEARNING/xlearning-1.2

スクリプトを実行します.sh
#!/bin/sh
$XLEARNING_HOME/bin/xl-submit \
   --app-type "tensorflow" \
   --app-name "tf-mnist" \
   --input /tmp/data/tfmnist/MNIST_data#data \
   --output /tmp/tfmnist_model#model \
   --files demo.py,input_data.py,demo.sh \
   --cacheArchive /tmp/tensorflow.tgz#tensorflow \
   --launch-cmd "sh demo.sh" \
   --worker-memory 2G \
   --worker-num 2 \
   --worker-cores 3 \
   --ps-memory 2G \
   --ps-num 1 \
   --ps-cores 2 \
   --queue default \

demo.shスクリプト
export PYTHONPATH=./:$PYTHONPATH
python demo.py --data_path=./data --save_path=./model --log_dir=./eventLog

demo.pyコード
import argparse
import sys
import os
import json
import numpy as np
import time

sys.path.append(os.getcwd())
import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)


import tensorflow as tf

FLAGS = None


def main(_):
    # cluster specification
    FLAGS.task_index = int(os.environ["TF_INDEX"])
    FLAGS.job_name = os.environ["TF_ROLE"]
    cluster_def = json.loads(os.environ["TF_CLUSTER_DEF"])
    cluster = tf.train.ClusterSpec(cluster_def)
    #sess = tf.InteractiveSession()

    print("ClusterSpec:", cluster_def)
    print("current task id:", FLAGS.task_index, " role:", FLAGS.job_name)

    gpu_options = tf.GPUOptions(allow_growth=True)
    server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index,
                             config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True))

    if FLAGS.job_name == "ps":
        server.join()
    elif FLAGS.job_name == "worker":
        # set the train parameters
        with tf.device(tf.train.replica_device_setter(worker_device=("/job:worker/task:%d" % (FLAGS.task_index)),
                                                      cluster=cluster)):
            global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)
            x = tf.placeholder(tf.float32, shape=[None, 784])
            y_ = tf.placeholder(tf.float32, shape=[None, 10])
            W = tf.Variable(tf.zeros([784, 10]))
            b = tf.Variable(tf.zeros([10]))

            #sess.run(tf.global_variables_initializer())

            y = tf.matmul(x, W) + b  
            cross_entropy = tf.reduce_mean(
                tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))

            train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
            correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

            def weight_variable(shape):
                initial = tf.truncated_normal(shape, stddev=0.1)
                return tf.Variable(initial)

            def bias_variable(shape):
                initial = tf.constant(0.1, shape=shape)
                return tf.Variable(initial)

            def conv2d(x, W):
                return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

            def max_pool_2x2(x):
                return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                                      strides=[1, 2, 2, 1], padding='SAME')

            W_conv1 = weight_variable([5, 5, 1, 32])
            b_conv1 = bias_variable([32])
            x_image = tf.reshape(x, [-1, 28, 28, 1])
            h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
            h_pool1 = max_pool_2x2(h_conv1)

            W_conv2 = weight_variable([5, 5, 32, 64])
            b_conv2 = bias_variable([64])
            h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
            h_pool2 = max_pool_2x2(h_conv2)

            W_fc1 = weight_variable([7 * 7 * 64, 1024])
            b_fc1 = bias_variable([1024])

            h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
            h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
            keep_prob = tf.placeholder(tf.float32)
            h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
            W_fc2 = weight_variable([1024, 10])
            b_fc2 = bias_variable([10])

            y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
            cross_entropy = tf.reduce_mean(
                tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
            train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
            correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
            init_op = tf.global_variables_initializer()
            saver = tf.train.Saver()  # defaults to saving all variables

        sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0), global_step=global_step, init_op=init_op)
        with sv.prepare_or_wait_for_session(server.target,
                                            config=tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True,
                                                                  log_device_placement=True)) as sess:
            # perform training cycles
            start_time = time.time()
            if (FLAGS.task_index == 0):
                train_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)

            sess.run(init_op)
            for i in range(20000):
                batch = mnist.train.next_batch(50)
                elapsed_time = time.time() - start_time
                start_time = time.time()
                if i % 100 == 0:
                    train_accuracy = accuracy.eval(feed_dict={
                        x: batch[0], y_: batch[1], keep_prob: 1.0})
                    print("step %d, training accuracy %g, Time: %3.2fms" % (i, train_accuracy, float(elapsed_time*1000)))
                train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
                sys.stderr.write("reporter progress:%0.4f
"
%(float(i/20000))) print("test accuracy %g" % accuracy.eval(feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) print("Train Completed.") if (FLAGS.task_index == 0): train_writer.close() print("saving model...") saver.save(sess, FLAGS.save_path+"/model.ckpt") print("done") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.register("type", "bool", lambda v: v.lower() == "true") # Flags for defining the tf.train.ClusterSpec parser.add_argument( "--job_name", type=str, default="", help="One of 'ps', 'worker'" ) # Flags for defining the tf.train.Server parser.add_argument( "--task_index", type=int, default=0, help="Index of task within the job" ) # Flags for defining the parameter of data path parser.add_argument( "--data_path", type=str, default="", help="The path for train file" ) parser.add_argument( "--save_path", type=str, default="", help="The save path for model" ) parser.add_argument( "--log_dir", type=str, default="", help="The log path for model" ) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main)

注:saver部分はトレーニングの重みとバイアスを保存し、評価プログラムで再使用できます.

2.3テスト画像の準備、Opencvによる前処理


ネットワークを訓練したら、次はそれをテストします.画像を1枚用意し、Opencvで前処理して評価プログラムに入れ、正確に認識できるかどうかを確認します.Opencvを用いて画像を前処理し,その大きさを28*28画素に縮小し,階調図に変換して二値化処理を行った.(1) stdafx.hファイルopencv関連ヘッダファイルの追加
#include 
#include  
#include 
#include 
#include 
#include 
#include 

(2)TF_ImgPreProcess.cppファイル
#include "stdafx.h"

#include 
#include 
#include 
#include 
#include 
using namespace std;
using namespace cv;

int _tmain(int argc, _TCHAR* argv[])
{
   IplImage* img = cvLoadImage("E:\\png\\5.png",1);
   IplImage* copyImg=cvCreateImage(cvGetSize(img),IPL_DEPTH_8U,3);
   cvCopyImage(img,copyImg);
   IplImage* ResImg=cvCreateImage(cvSize(28,28),IPL_DEPTH_8U,1);
   IplImage* TmpImg=cvCreateImage(cvGetSize(ResImg),IPL_DEPTH_8U,3);

   cvResize(copyImg,TmpImg,CV_INTER_LINEAR); 
   cvCvtColor(TmpImg,ResImg,CV_RGB2GRAY);
   cvThreshold(ResImg,ResImg,100,255,CV_THRESH_BINARY_INV);

   cvSaveImage("E:\\png\\result\\1.png",ResImg);
   cvWaitKey(0);

    return 0;
}

2.4画像入力ネットワークを認識する


環境にopencvパッケージをインストールする
 yum install opencv-python -y

ここでは,最後のsoftmax層分類の結果が最後の識別結果である順方向伝播プログラムを記述した.プログラムは次のとおりです:'`python from PIL import Image,ImageFilter import tensorflow as tf import cv 2
def imageprepare(): “”” This function returns the pixel values. The imput is a png file location. “”” file_name=’/data/sxl/MNIST_recognize/p_num2.png’#自分の画像アドレス#in terminal'mogrify-format png*.jpg’ convert jpg to png im = Image.open(file_name).convert(‘L’)
im.save("/data/sxl/MNIST_recognize/sample.png")
tv = list(im.getdata()) #get pixel values

#normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [ (255-x)*1.0/255.0 for x in tv] 
#print(tva)
return tva



"""
This function returns the predicted integer.
The imput is the pixel values from the imageprepare() function.
"""

# Define the model (same as when creating the model file)

result=imageprepare() x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10]))
def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=’SAME’)
def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=’SAME’)
W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

init_op = tf.initialize_all_variables()


init_op = tf.global_variables_initializer()
“”” Load the model2.ckpt file file is stored in the same directory as this python script is started Use the model to predict the integer. Integer is returend as list.
Based on the documentatoin at https://www.tensorflow.org/versions/master/how_tos/variables/index.html “”” saver = tf.train.Saver() with tf.Session() as sess: sess.run(init_op) saver.restore(sess,"/data/sxl/MNIST_recognize/form/model 2.ckpt")#ここでは、以前に保存したモデルパラメータ#print("Model restored.")を使用します.
prediction=tf.argmax(y_conv,1)
predint=prediction.
print(h_conv2)

print('recognize result:')

print(predint[0])
 :
![](/upload/images/20180309//f8c775df-a50b-4278-a2aa-ef51653938a1.png)
 :
![](/upload/images/20180309//be8605a5-d009-4156-b1d7-d423d35797de.png)
 :
tensorflow :
```python
saver = tf.train.Saver()
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
saver.save(sess,"checkpoint/model.ckpt",global_step=1)




"se-preview-section-delimiter">

実行後、モデルを保存する保存し、それぞれ3つのファイルを得る.data,.meta,.index, model.ckpt.data-00000-of-00001 model.ckpt.index model.ckpt.meta meta fileはgraph構造を保存する、GraphDef、SaverDefなどを含む.index fileはstring-string table、tableのkey値はtensor名、valueはBundleEntryProto、BundleEntryProto.Data fileはモデルのすべての変数の値を保存する.モデルは次のようにロードされます.
with tf.Session() as sess:
  saver.restore(sess, "/checkpoint/model.ckpt")
 , , , .data,.meta,.index,
model.ckpt.data-00000-of-00001
model.ckpt.index
model.ckpt.meta
meta file graph ,  GraphDef, SaverDef .
index file  string-string table,table key tensor ,value BundleEntryProto, BundleEntryProto.
data file .
 :
```python
with tf.Session() as sess:
  saver.restore(sess, "/checkpoint/model.ckpt")

もっとすばらしいオリジナルの文章、詳しくは紅象雲騰コミュニティを参照してください