搭配Docker訓練影像分類

環境建立

  • 安裝Docker
  • 可以使用套件:Fatkun Batch Download image chrome套件,使用google搜尋圖片後,進行一鍵下載當做影像來源。
  • 安裝Tensorflow 映像檔
docker run -it gcr.io/tensorflow:latest-devel
docker run --rm -it -v $1:/tf_files  xblaster/tensor-guess bash
logout
mkdir tf_files
mkdir tf_files/star_wars
cd tf_files/star_wars
mv 下載影像目錄 .
// 學習
docker run -it -v $HOME/tf_files/star_wars:/star_wars/ gcr.io/tensorflow/tensorflow:latest-dev // 進入container
cd tensorflow
git pull
python tensorflow/examples/image_retraining/retrain.py --bottleneck_dir=/tf_files/bottlenecks \
--how_many_training_steps 4000 
--model_dir=/tf_files/inception \
--output_graph=/tf_files/retrained_graph.pb \
--output_labels=/tf_files/retrained_labels.txt \
--image_dir /tf_files/star_wars
  • 撰寫程式 image_label.py
import tensorflow as tf
import sys

# change this as you see fit
image_path = sys.argv[1]

# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()

# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line 
                   in tf.gfile.GFile("/tf_files/retrained_labels.txt")]

# Unpersists graph from file
with tf.gfile.FastGFile("/tf_files/retrained_graph.pb", 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')

with tf.Session() as sess:
    # Feed the image_data as input to the graph and get first prediction
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

    predictions = sess.run(softmax_tensor, \
             {'DecodeJpeg/contents:0': image_data})

    # Sort to show labels of first prediction in order of confidence
    top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

    for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]
        print('%s (score = %.5f)' % (human_string, score))
  • 測試
cp label_image.py /tf_files
cd /tf_files
python label_image.py /img/guess.jpg
  • 建立目錄環境,資料需要放在data目錄下
[any_path]/my_own_classifier/
 [any_path]/my_own_classifier/data
 [any_path]/my_own_classifier/data/car
 [any_path]/my_own_classifier/data/moto
 [any_path]/my_own_classifier/data/bus
  • Dockerfile
FROM tensorflow/tensorflow:0.9.0-devel
MAINTAINER Jerome WAX "xblaster@lo2k.net"
WORKDIR /tensorflow
ADD src .
RUN git pull
CMD cd /tensorflow && ./train.sh

訓練模型

  • tran.sh
docker run -v $1:/tf_files  xblaster/tensor-guess
  • 執行
./train.sh [any_path]/my_own_classifier

判斷影像類別

  • guess.sh
docker run -v $1:/tf_files -v $2:/img/guess.jpg  xblaster/tensor-guess sh -c "./guess.sh" 2> /dev/null
  • 執行
// 單張照片
./guess.sh [any_path]/my_own_classifier /yourfile.jpg
  • guessDir.sh
docker run --rm -v $1:/tf_files -v $2:/toScan -v $3:/scanned xblaster/tensor-guess sh -c "python py/label_dir.py"
#docker run --rm -it  -v $1:/tf_files -v $2:/toScan -v $3:/scanned tf bash
  • 目錄
./guessDir.sh [any_path]/classifier [any_path]/srcDir [any_path]/destDir

參考資料