Tensorflow で Mnist

Tensorflow で Mnist をやってみます。

ドキュメント

MNIST For ML Beginners  |  TensorFlow

サンプルコード

tensorflow/mnist_softmax.py at r1.1 · tensorflow/tensorflow · GitHub

これを使えということなので、使ってみます。

mnist 用のデータを自動でダウンロードしてくれます。
Chainer 用に既にダウンロードしてありますが、まぁ、気にしません!

$ python mnist_softmax.py 
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
2017-05-09 15:08:44.979276: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:08:44.979344: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:08:45.215246: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-05-09 15:08:45.215956: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties: 
name: GeForce GTX 1060 6GB
major: 6 minor: 1 memoryClockRate (GHz) 1.7845
pciBusID 0000:06:00.0
Total memory: 5.93GiB
Free memory: 5.84GiB
2017-05-09 15:08:45.215999: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0 
2017-05-09 15:08:45.216016: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y 
2017-05-09 15:08:45.216045: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:06:00.0)
0.9186

ubuntu14.04 LTS + CUDA + cuDNN + Tensorflow インストールメモ

tensorflow の動作確認まで

tensorflow

www.tensorflow.org

インストールガイド

Installing TensorFlow on Ubuntu  |  TensorFlow

インストール方法は何種類か有るらしいですが、We recommend the virtualenv installation. とのことなので、素直に従います。

インストー

$ sudo apt-get install python-virtualenv
$ mkdir ~/tensorflow
$ virtualenv --system-site-packages ~/tensorflow
New python executable in ***/tensorflow/bin/python
Installing setuptools, pip...done.

$ source ~/tensorflow/bin/activate
(tensorflow)$ pip install --upgrade tensorflow-gpu

失敗するので・・・

(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp27-none-linux_x86_64.whl

ログがいっぱい出て・・・

Successfully installed tensorflow-gpu mock numpy protobuf wheel werkzeug funcsigs pbr setuptools
Cleaning up...

インストールのチェック validate the installation.

(tensorflow)$ deactivate

$ source ~/tensorflow/bin/activate

(tensorflow)$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
2017-05-09 15:00:35.019097: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:00:35.019149: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:00:35.339102: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-05-09 15:00:35.339812: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties: 
name: GeForce GTX 1060 6GB
major: 6 minor: 1 memoryClockRate (GHz) 1.7845
pciBusID 0000:06:00.0
Total memory: 5.93GiB
Free memory: 5.84GiB
2017-05-09 15:00:35.339858: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0 
2017-05-09 15:00:35.339875: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y 
2017-05-09 15:00:35.339902: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:06:00.0)
>>> print(sess.run(hello))
Hello, TensorFlow!
>>>

事前に鬼門である nvidia のドライバーと CUDA, cuDNN のインストールを済ませてあったので、すんなりと入ったようです。

tesseract-ocr その2 学習させてみる

まず、apt-get でインストールしても、training-tools が入っていません。

やむなく、コンパイルします。

また、依存関係の問題で、 tesseract-ocr 3.05 と leptonica-1.74.1 の組み合わせになりました。

tesseract-ocr 3.05 は Leptonica 1.74 or higher is required. なので必要でした。

Leptonica を準備する

まず、apt-get で入る Leptonica について。

$ sudo apt-cache policy libleptonica-dev
libleptonica-dev:
  インストールされているバージョン: 1.70.1-1
  候補:               1.70.1-1

です。

ソースからコンパイルですね。

http://www.leptonica.com/download.html

$ cd leptonica-1.74.1
$ ./configure
$ make
$ make install

tesseract-ocr を準備する

GitHub - tesseract-ocr/tesseract: Tesseract Open Source OCR Engine (main repository)

The latest stable version is 3.05.00, released in February 2017. とあるから、gitから 3.05 が入るんだろう。(間違い)

ソースをゲットして、展開してコンパイルする

$ git clone https://github.com/tesseract-ocr/tesseract.git
$ cd tesseract-ocr(だったかな?)
$ ./autogen.sh
$ ./configure --prefix=/usr/local/tesseract/
$ make
$ sudo make install
$ sudo ldconfig

training-toolsもコンパイルする

$ make training
$ sudo make training-install

PATH 通す

export TESSDATA_PREFIX=/usr/local/tesseract/share/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

を、.bashrc などに足しておく。

バージョン確認
$ /usr/local/tesseract/bin/tesseract -v
tesseract 4.00.00alpha
 leptonica-1.74.1
  libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 : libtiff 4.0.3 : zlib 1.2.8

 Found SSE

あれ??? 4.00.00 alpha がインストールされたぞ?最新バージョンは 4.00.00 だったらしい。

やり直し

$ wget https://github.com/tesseract-ocr/tesseract/archive/3.05.00.tar.gz -O tesseract-ocr.tar.gz
$ cd tesseract-3.05.00
$ ./autogen.sh
$ ./configure --prefix=/usr/local/tesseract/
$ make
$ sudo make install

$ sudo make install
$ sudo ldconfig

$ /usr/local/tesseract/bin/tesseract -v
tesseract 3.05.00
 leptonica-1.74.1
  libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 : libtiff 4.0.3 : zlib 1.2.8

$ /usr/local/tesseract/bin/tesseract hw.png out -l eng
Tesseract Open Source OCR Engine v3.05.00 with Leptonica
kiyo@kiyo-PowerEdge-T410:~$ cat out.txt 
HeIIow world.

学習 jTessBoxEditor

jTessBoxEditor 起動

$ java -jar jTessBoxEditor.jar

簡単な手順

・"TIFF/Box Generator" タブから、Output の場所と、言語、フォントを設定し、Generate する。 ・Generate されたBOXは、"BOX Editor" タブでOpenすると確認できる。 ・"Trainer"タブから、Tesseract のPathを指定し、Training Data を指定して、RUN すると、指定したディレクトリに tessdata/***.traineddata が作成される。 ・***.traineddata を、tesseract の tessdata ディレクトリに入れる。

テスト

f:id:pongsuke:20170412153611p:plain

0123456789

f:id:pongsuke:20170412153616p:plain

7894561230

なお、上記2つは成功した例ですが、作成した学習データと、読ませるフォントが異なると上手に判定できません。

tesseract-ocr その1 動作確認

インストール

sudo apt-get install tesseract-ocr

色々と依存が有った気がします・・。

PATH を通す

.bashrc に以下を追加

export TESSDATA_PREFIX=/usr/share/tesseract-ocr/

バージョンを確認

$ tesseract -v
tesseract 3.03
 leptonica-1.70
  libgif 4.1.6(?) : libjpeg 8d : libpng 1.2.50 : libtiff 4.0.3 : zlib 1.2.8 : webp 0.4.0

画像を準備する

f:id:pongsuke:20170412102816p:plain

動かす

$ tesseract hw.png out -l eng
Tesseract Open Source OCR Engine v3.03 with Leptonica

$ cat out.txt 
Hellow world.

日本語を試す

言語データを追加する

Version 3.04 向けのデータを使ってみる(失敗)

Version 3.04 向けのデータはココ。

GitHub - tesseract-ocr/tessdata at 3.04.00

jpn.traineddata を /usr/share/tesseract-ocr/tessdata/ に入れます。

試す

f:id:pongsuke:20170412103533p:plain

$ tesseract hw.jp.png out -l jpn
Tesseract Open Source OCR Engine v3.03 with Leptonica
read_params_file: parameter not found: allow_blob_division

どうやらこれは、apt-get でインストールされた tesseract のバージョンが 3.03 なのに対し、言語データが 3.04 向けなのが原因の様です。

Version 3.02 向けのデータを使ってみる(動く)

次に、Version 3.02 向けを使う。

tesseract-ocr alternative download - Browse Files at SourceForge.net

$ tesseract hw.jp.png out -l jpn
Tesseract Open Source OCR Engine v3.03 with Leptonica

$ cat out.txt 
こんにちは。

chainer いろは

箇条書きで

学習済みモデルの保存と利用は?

せっかく学習させたので、学習済みのデータを使いたい。

どうやる?

chainer.serialisersを使う。

注意点は、ダンプしたのと同じ環境じゃないと動かない。

model の種類、GPUの使用/不使用 など、らしい。

Model 書き出し
 ...
from chainer import serializers

 ...

# npz形式で書き出し
serializers.save_npz("model.002.npz", model)
# hdf5形式で書き出し
# serializers.save_hdf5('modelhdf5', model)
Model 読み込み
 ...
from chainer import serializers
 ...


model   = Model()
# npz形式で読み込み
serializers.load_npz("model.002.npz", model)
# hdf5形式で読み込み
# serializers.load_hdf5("modelhdf5", model)

CSLAIER で学習させると、一式をzipでダウンロードできます。

GPUでの計算にするには?

gpu の初期設定と、 nummpy を chainer.cuda.cupy に変更する。

gpu_device = 0
chainer.cuda.get_device(gpu_device).use()
model.to_gpu(gpu_device)
xp = chainer.cuda.cupy

Chainer cifar を試す

README 曰く、train_cifar.py は、デフォルトで GPU 0 を使う。

$ python train_cifar.py

Mnist のように、データセットのダウンロードから始まります。

Estimated time to finish: 3:57:33

とでました。

初回の結果

$ python train_cifar.py 
GPU: 0
# Minibatch-size: 128
# epoch: 300

Using CIFAR10 dataset.
Downloading from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz...
epoch       main/loss   validation/main/loss  main/accuracy  validation/main/accuracy  elapsed_time
1           2.40104     1.94277               0.161325       0.217168                  51.6946       
2           1.81075     1.66216               0.285826       0.347706                  100.377       
3           1.50989     1.42922               0.420052       0.475771                  149.203       
4           1.27429     1.15027               0.543938       0.594343                  198.176       
5           1.0685      1.00839               0.627757       0.655756                  247.159       
6           0.953728    0.983496              0.673437       0.667623                  296.061       
7           0.871836    0.878536              0.710038       0.707476                  345.054       
8           0.825212    0.826754              0.729547       0.733782                  393.962       
9           0.789095    0.813937              0.745165       0.739517                  442.956       
10          0.753746    0.79951               0.757433       0.742089                  491.96        
11          0.729694    0.760835              0.767007       0.762658                  540.833       

 ...

285         0.00550012  0.524492              0.998881       0.899031                  13941.3       
286         0.00420565  0.549105              0.999379       0.89646                   13990.1       
287         0.00410778  0.539779              0.999341       0.897547                  14039         
288         0.00399757  0.536811              0.999419       0.897646                  14087.7       
289         0.00549819  0.532966              0.999021       0.898042                  14136.6       
290         0.00449508  0.525496              0.999341       0.899229                  14185.5       
291         0.00408126  0.528732              0.999459       0.898438                  14234.3       
292         0.00433158  0.529872              0.999361       0.897152                  14283.2       
293         0.00442761  0.534484              0.999321       0.897745                  14332.1       
294         0.00480573  0.52566               0.999179       0.898734                  14380.9       
295         0.0047175   0.535832              0.999321       0.899525                  14429.8       
296         0.00457282  0.548527              0.999299       0.89468                   14478.7       
297         0.00466009  0.538513              0.999241       0.896657                  14527.7       
298         0.00482552  0.535228              0.999201       0.898438                  14576.8       
299         0.00517972  0.528672              0.998978       0.899328                  14625.6       
300         0.00443006  0.533218              0.999261       0.899723                  14674.5

f:id:pongsuke:20170317111704p:plain

CSLAIER

GitHub - SonyCSL/CSLAIER

README から、必要なパッケージを入れる。

$ sudo apt-get install python-pip
$ sudo apt-get install python-dev
$ sudo apt-get install libhdf5-dev
$ sudo apt-get install python-opencv
$ sudo apt-get install sqlite3
$ sudo apt-get install python-matplotlib
$ sudo apt-get install nkf

どこまで必要か不明だが、メモ。

$ sudo apt-get install liblapack-dev
$ sudo pip install scipy
$ sudo apt-get install gfortran
$ git clone https://github.com/SonyCSL/CSLAIER
$ cd CSLAIER
$ ./setup.sh
$ sudo pip install -r requirements.txt

LAN内部の別マシンからアクセスしたいので、cfgを変える。

$ cat cslaier.cfg 
#HOST='localhost'
HOST='192.168.100.50'
PORT=8080
DATABASE_PATH='cslaier.db'
DEBUG=True
UPLOADED_RAW_FILE='uploaded_raw_files'
UPLOADED_FILE='uploaded_files'
PREPARED_DATA='prepared_data'
TRAINED_DATA='trained_data'
INSPECTION_TEMP='inspection_temp'
LOG_DIR='logs'

PORT を 80 にしたくなるのだけど、80にするは Permission denied がでて、思わず suro ./run.sh しちゃうんですが、そうすると、データも root 権限で作られちゃって、色々怖い。

データとモデルを登録してスタートする、、、。

動き始める?のが遅くて不安になるが、TOP で見ると Python が 100% CPU 使っていたりするから、何かしているんだろうなーと思える。

f:id:pongsuke:20170315181235p:plain

f:id:pongsuke:20170315181236p:plain

10エポック終了

f:id:pongsuke:20170316094637p:plain

inspect させる

f:id:pongsuke:20170322175752j:plain

nin で classify であれば、画像をアップロード出来ます。