More Related Content Similar to Deep Learningハンズオン勉強会「Caffeで画像分類を試してみようの会」 (20) More from Yasuyuki Sugai (18) Deep Learningハンズオン勉強会「Caffeで画像分類を試してみようの会」3. - 本日の流れ -
3
• 環境構築編
– AWS上にCaffeの動作環境を準備
• Caffe Tutorial編
– チュートリアルの一つである、CIFAR-10を
使ってお試し動作
• Caffe やって!Try編
– データセットを用意して、動かしてみよう
8. Why? Caffe
8
• DeepLearningの中でも画像処理に最適化
– 畳み込みニューラルネットワーク(CNN)を実装
• C++で実装されているが、Python用のライブラリも提供
• GPUだけでなく、CPUでも動作
– GPUでモデル作ってCPUで評価とか、お得
• リファレンスモデルが用意されている
(Caffe Model Zooで学習済みモデルも)
– このモデルを基に、お試しですぐに評価が可能
• ドキュメントがそれなりに用意されている
– いざとなったらコードも公開されているし。。。
9. What We’re afraid of the Caffe
9
• 環境構築でハマる
– GPUを利用するものは全般的にですが。。。
• 自前のデータ用意に若干敷居が。。
– データの格納形式が
lmdb or leveldb
(またはHDF5)なので
13. 使用する環境
13
• NVIDIA+CUDA セットアップ済
– CUDA ver6.5
(CUDA:NVIDIAのGPUを扱うためのSDK)
• Caffeセットアップ済み
– 必要なlib(多数)インストール
• Pythonセットアップ済み
– Python ver2.7
(一部ライブラリがPython3に対応していないので..)
– numpy / pycaffe
30. LeNet MNIST
30
• 手書き数字の認識精度テスト
• 28x28ピクセル、70,000枚の画像
• チュートリアル
• http://caffe.berkeleyvision.org/gathered/examples/mnist.html
– やってもあまり面白みがなさそう(遊べることが少ない)
なので、今回はパス。。。
31. ilsvrc12(ImageNet Large Scale Visual
Recognition Challenge 2012 )
31
• 物体認識の精度を競う国際コンテスト
• 画像に「何が映っているか」を検出、識別
• クラス数:1,000、画像枚数:150,000
• チュートリアル
• http://caffe.berkeleyvision.org/gathered/examples/imagenet.html
– 研究者向けに画像を提供しているため、画像の準備が
めんどい。。。配布も不可。。色々遊べるのに。。。
– 申請してから利用できるまで1日かかるので、今回はパス。。。
34. CaffeでDeep Learningの流れ
34
• ①データセットの準備
– データ取得、前処理・正規化などなど
• ②データの格納
– lmdb or leveldb、学習用データ / 評価用データ分類
• ③パラメータ設定
– NNのネットワーク定義やCaffeの動作パラメータ設定などなど
• ④学習実行
– データとパラメータを基に、機械学習
• ⑤学習モデルの利用
– 新しい画像の分類検証
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
36. 36
①データセットの準備
• 下記のコマンドを実行してください
シェルの中身
• CIFAR-10のデータをダウンロード(wget)
• データを展開(tar展開+gunzip)
$ cd /caffe/data/cifar10
$ ./get_cifar10.sh
Downloading...
:(中略)
Saving to: ‘cifar-10-binary.tar.gz’
100%[==================================================>] 170,052,171 2.66MB/s in 59s
2015-07-24 21:12:05 (2.73 MB/s) - ‘cifar-10-binary.tar.gz’ saved [170052171/170052171]
Unzipping...
Done.
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
37. 37
①データセットの準備
$ ls -ltr
total 346152
-rw-r--r-- 1 ubuntu ubuntu 30730000 Jun 4 2009 data_batch_5.bin
-rw-r--r-- 1 ubuntu ubuntu 30730000 Jun 4 2009 test_batch.bin
-rw-r--r-- 1 ubuntu ubuntu 30730000 Jun 4 2009 data_batch_1.bin
-rw-r--r-- 1 ubuntu ubuntu 30730000 Jun 4 2009 data_batch_2.bin
-rw-r--r-- 1 ubuntu ubuntu 30730000 Jun 4 2009 data_batch_4.bin
-rw-r--r-- 1 ubuntu ubuntu 30730000 Jun 4 2009 data_batch_3.bin
-rw-r--r-- 1 ubuntu ubuntu 61 Jun 4 2009 batches.meta.txt
-rw-r--r-- 1 ubuntu ubuntu 88 Jun 4 2009 readme.html
-rwxrwxr-x 1 ubuntu ubuntu 504 Apr 21 18:20 get_cifar10.sh
ダウンロード、展開したデータ(バイナリ)
• 取得したデータの確認
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
38. 38
$ cd /caffe
$ ./examples/cifar10/create_cifar10.sh
Creating lmdb...
Computing image mean...
Done.
②データの格納
• 下記のコマンドを実行してください
シェルの中身
• LMDBにデータ格納(バイナリなので中身見れず)
• 平均画像の作成(バイナリなので中身見れず)
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
39. 39
②データの格納
$ ls -ltr examples/cifar10/
total 84
-rwxrwxr-x 1 ubuntu ubuntu 325 Apr 21 18:20 train_quick.sh
-rwxrwxr-x 1 ubuntu ubuntu 508 Apr 21 18:20 train_full.sh
-rw-rw-r-- 1 ubuntu ubuntu 5262 Apr 21 18:20 readme.md
-rwxrwxr-x 1 ubuntu ubuntu 460 Apr 21 18:20 create_cifar10.sh
-rw-rw-r-- 1 ubuntu ubuntu 3760 Apr 21 18:20 convert_cifar_data.cpp
-rw-rw-r-- 1 ubuntu ubuntu 3088 Apr 21 18:20 cifar10_quick_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 859 Apr 21 18:20 cifar10_quick_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 860 Apr 21 18:20 cifar10_quick_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 1875 Apr 21 18:20 cifar10_quick.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 3122 Apr 21 18:20 cifar10_full_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 923 Apr 21 18:20 cifar10_full_solver_lr2.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 2128 Apr 21 18:20 cifar10_full.prototxt
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 20 08:47 cifar10_train_lmdb
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 20 08:47 cifar10_test_lmdb
-rw-rw-r-- 1 ubuntu ubuntu 12299 Jul 20 08:47 mean.binaryproto
• 出来上がったデータファイルの確認
学習用データ格納DB、評価用データ格納DB、平均画像
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
40. Caffe特有な話①
40
• 学習用 / 評価用データは
LMDB or LEVELDB(またはHDF5)に格納する
– LEVELDB: key/valueの軽量データストア
» http://leveldb.org/
– LMDB: LEVELDBを高性能化、
pythonにバインディング
» https://lmdb.readthedocs.org/en/release/
» LEVEL DBに対して、単一DBへの同時アクセスを
サポート(複数プロセスで動作可能)
• 参考:HDF5:数値データを保存するためのファイルフォーマット
43. 43
③パラメータ設定
$ ls -ltr examples/cifar10
total 2372
-rwxrwxr-x 1 ubuntu ubuntu 325 Apr 21 18:20 train_quick.sh
-rwxrwxr-x 1 ubuntu ubuntu 508 Apr 21 18:20 train_full.sh
-rw-rw-r-- 1 ubuntu ubuntu 5262 Apr 21 18:20 readme.md
-rwxrwxr-x 1 ubuntu ubuntu 460 Apr 21 18:20 create_cifar10.sh
-rw-rw-r-- 1 ubuntu ubuntu 3760 Apr 21 18:20 convert_cifar_data.cpp
-rw-rw-r-- 1 ubuntu ubuntu 3088 Apr 21 18:20 cifar10_quick_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 859 Apr 21 18:20 cifar10_quick_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 860 Apr 21 18:20 cifar10_quick_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 1875 Apr 21 18:20 cifar10_quick.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 3122 Apr 21 18:20 cifar10_full_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 923 Apr 21 18:20 cifar10_full_solver_lr2.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 2128 Apr 21 18:20 cifar10_full.prototxt
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 20 08:47 cifar10_train_lmdb
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 20 08:47 cifar10_test_lmdb
-rw-rw-r-- 1 ubuntu ubuntu 12299 Jul 20 08:47 mean.binaryproto
• リファレンスモデルとして用意されている
パラメータをそのまま使用 (*.prototxt)
cifar10_quick*.prototxtを使います
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
48. CIFAR-10のニューラルネットを見てみよう
48
$ cd
$ mkdir web
$ cd web
$ vi web_server.py
#!/usr/bin/env python
#coding: utf-8
import CGIHTTPServer
CGIHTTPServer.test()
$ python web_server.py &
[1] 12710
Serving HTTP on 0.0.0.0 port 8000 ...
• Pythonで簡易なHTTPサーバを立てます
(Portはデフォルトで8000)
ファイルの中に記述
55. CIFAR-10のニューラルネットを見てみよう
55
• ニューラルネットのレイヤを画像に出力します
• Webから参照可能なディレクトリに画像を出力
$ sudo apt-get -y install graphviz
:(省略)
$ sudo pip install pydot
:(省略)
$ sudo pip uninstall pyparsing
:(省略)
$ sudo pip install -Iv https://pypi.python.org/packages/source/p/pyparsing/pyparsing-1.5.7.tar.gz
:(省略)
$ cd /caffe
$ ./python/draw_net.py ./examples/cifar10/cifar10_quick.prototxt ../web/cifar10.png
Drawing net to ../web/cifar10.png
※入っているpyparsingが上手く動かないので、個別に入れ直し。。。
63. 63
$ cd /caffe
$ build/tools/caffe train --solver examples/cifar10/cifar10_quick_solver.prototxt
I0724 21:21:59.567821 4475 caffe.cpp:113] Use GPU with device ID 0
I0724 21:22:01.224532 4475 caffe.cpp:121] Starting Optimization
I0724 21:22:01.224684 4475 solver.cpp:32] Initializing solver from parameters:
test_iter: 100
test_interval: 500
base_lr: 0.001
display: 100
max_iter: 4000
lr_policy: "fixed"
momentum: 0.9
weight_decay: 0.004
snapshot: 4000
snapshot_prefix: "examples/cifar10/cifar10_quick"
solver_mode: GPU
net: "examples/cifar10/cifar10_quick_train_test.prototxt"
:(中略)
④学習実行
• ③で定義したファイルを指定し、機械学習を実行
• 下記のコマンドを実行してください
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
64. 64
④学習実行
:(中略)
I0720 09:26:33.801441 7750 solver.cpp:189] Iteration 1100, loss = 1.01867
I0720 09:26:33.801512 7750 solver.cpp:204] Train net output #0: loss = 1.01867 (* 1 = 1.01867 loss)
I0720 09:26:33.801527 7750 solver.cpp:464] Iteration 1100, lr = 0.001
I0720 09:26:42.208279 7750 solver.cpp:189] Iteration 1200, loss = 1.0143
I0720 09:26:42.208398 7750 solver.cpp:204] Train net output #0: loss = 1.0143 (* 1 = 1.0143 loss)
I0720 09:26:42.208413 7750 solver.cpp:464] Iteration 1200, lr = 0.001
I0720 09:26:50.614888 7750 solver.cpp:189] Iteration 1300, loss = 0.932997
I0720 09:26:50.614959 7750 solver.cpp:204] Train net output #0: loss = 0.932997 (* 1 = 0.932997 loss)
I0720 09:26:50.614974 7750 solver.cpp:464] Iteration 1300, lr = 0.001
I0720 09:26:59.020402 7750 solver.cpp:189] Iteration 1400, loss = 0.881796
I0720 09:26:59.020475 7750 solver.cpp:204] Train net output #0: loss = 0.881796 (* 1 = 0.881796 loss)
I0720 09:26:59.020490 7750 solver.cpp:464] Iteration 1400, lr = 0.001
I0720 09:27:07.344590 7750 solver.cpp:266] Iteration 1500, Testing net (#0)
I0720 09:27:10.201467 7750 solver.cpp:315] Test net output #0: accuracy = 0.6719
I0720 09:27:10.201541 7750 solver.cpp:315] Test net output #1: loss = 0.967036 (* 1 = 0.967036 loss)
I0720 09:27:10.245405 7750 solver.cpp:189] Iteration 1500, loss = 0.920801
I0720 09:27:10.245442 7750 solver.cpp:204] Train net output #0: loss = 0.920801 (* 1 = 0.920801 loss)
:(中略)
• しばらくすると、こんな感じの標準出力が行われます
500回毎のテスト結果
accuracy = 0.6719 67.19%の正解率
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
accuracy : どれだけの精度か(正解率)
loss : 予測と正解が一致すると小さくなる
65. 65
④学習実行
:(中略)
I0724 21:27:42.383982 4475 solver.cpp:464] Iteration 3800, lr = 0.001
I0724 21:27:50.766244 4475 solver.cpp:189] Iteration 3900, loss = 0.72959
I0724 21:27:50.766304 4475 solver.cpp:204] Train net output #0: loss = 0.72959 (* 1 = 0.72959 loss)
I0724 21:27:50.766317 4475 solver.cpp:464] Iteration 3900, lr = 0.001
I0724 21:27:59.108741 4475 solver.cpp:334] Snapshotting to examples/cifar10/
cifar10_quick_iter_4000.caffemodel
I0724 21:27:59.111134 4475 solver.cpp:342] Snapshotting solver state to examples/cifar10/
cifar10_quick_iter_4000.solverstate
I0724 21:27:59.140338 4475 solver.cpp:248] Iteration 4000, loss = 0.641892
I0724 21:27:59.140404 4475 solver.cpp:266] Iteration 4000, Testing net (#0)
I0724 21:28:01.943065 4475 solver.cpp:315] Test net output #0: accuracy = 0.712
I0724 21:28:01.943125 4475 solver.cpp:315] Test net output #1: loss = 0.844847 (* 1 = 0.844847 loss)
I0724 21:28:01.943140 4475 solver.cpp:253] Optimization Done.
I0724 21:28:01.943148 4475 caffe.cpp:134] Optimization Done.
• 最終的にこんな感じの出力になります
4000回のイテレーションの結果、71.2%の正解率
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
66. 66
$ ls -ltr examples/cifar10
total 2372
-rwxrwxr-x 1 ubuntu ubuntu 325 Apr 21 18:20 train_quick.sh
-rwxrwxr-x 1 ubuntu ubuntu 508 Apr 21 18:20 train_full.sh
-rw-rw-r-- 1 ubuntu ubuntu 5262 Apr 21 18:20 readme.md
-rwxrwxr-x 1 ubuntu ubuntu 460 Apr 21 18:20 create_cifar10.sh
-rw-rw-r-- 1 ubuntu ubuntu 3760 Apr 21 18:20 convert_cifar_data.cpp
-rw-rw-r-- 1 ubuntu ubuntu 3088 Apr 21 18:20 cifar10_quick_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 859 Apr 21 18:20 cifar10_quick_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 860 Apr 21 18:20 cifar10_quick_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 1875 Apr 21 18:20 cifar10_quick.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 3122 Apr 21 18:20 cifar10_full_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 923 Apr 21 18:20 cifar10_full_solver_lr2.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 2128 Apr 21 18:20 cifar10_full.prototxt
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 20 08:47 cifar10_train_lmdb
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 20 08:47 cifar10_test_lmdb
-rw-rw-r-- 1 ubuntu ubuntu 12299 Jul 20 08:47 mean.binaryproto
-rw-rw-r-- 1 ubuntu ubuntu 583301 Jul 20 09:30 cifar10_quick_iter_4000.caffemodel
-rw-rw-r-- 1 ubuntu ubuntu 582496 Jul 20 09:30 cifar10_quick_iter_4000.solverstate
④学習実行
• 学習したモデルはファイルに出力します
prefix + 何回目の学習結果かがスナップショットのファイル名
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
67. $ ls -ltr /tmp
total 124
-rw-rw-r-- 1 ubuntu ubuntu 832 Jul 20 08:42 convert_cifar_data.bin.ip-10-123-220-57.ubuntu.log.INFO.20150720-084140.1490
-rw-rw-r-- 1 ubuntu ubuntu 1134 Jul 20 08:42 compute_image_mean.ip-10-123-220-57.ubuntu.log.INFO.20150720-084223.1491
lrwxrwxrwx 1 ubuntu ubuntu 76 Jul 20 08:47 convert_cifar_data.bin.INFO ->
convert_cifar_data.bin.ip-10-123-220-57.ubuntu.log.INFO.20150720-084700.1495
-rw-rw-r-- 1 ubuntu ubuntu 832 Jul 20 08:47 convert_cifar_data.bin.ip-10-123-220-57.ubuntu.log.INFO.20150720-084700.1495
lrwxrwxrwx 1 ubuntu ubuntu 72 Jul 20 08:47 compute_image_mean.INFO -> compute_image_mean.ip-10-123-220-57.ubuntu.log.INFO.
20150720-084741.1496
-rw-rw-r-- 1 ubuntu ubuntu 1134 Jul 20 08:47 compute_image_mean.ip-10-123-220-57.ubuntu.log.INFO.20150720-084741.1496
-rw-rw-r-- 1 ubuntu ubuntu 35406 Jul 20 09:15 caffe.ip-10-123-220-57.ubuntu.log.INFO.20150720-090857.1524
-rw-rw-r-- 1 ubuntu ubuntu 26593 Jul 20 09:16 caffe.ip-10-123-220-57.ubuntu.log.INFO.20150720-091503.6440
lrwxrwxrwx 1 ubuntu ubuntu 59 Jul 20 09:24 caffe.INFO -> caffe.ip-10-123-220-57.ubuntu.log.INFO.20150720-092452.7750
-rw-rw-r-- 1 ubuntu ubuntu 35412 Jul 20 09:30 caffe.ip-10-123-220-57.ubuntu.log.INFO.20150720-092452.7750
67
④学習実行
• ちなみに標準出力を見逃した!コンソール閉じた!
という時でも安心、/tmpに結果が出力されています
ファイルで残っているので、結果を加工しやすい
ファイル名は随時変わるけど、caffe.INFOでシンボリックリンク
張られるので便利
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
68. $ cat /tmp/caffe.INFO ¦ grep "accuracy = "
I0720 09:24:55.671538 7750 solver.cpp:315] Test net output #0: accuracy = 0.085
I0720 09:25:40.486860 7750 solver.cpp:315] Test net output #0: accuracy = 0.5406
I0720 09:26:25.351641 7750 solver.cpp:315] Test net output #0: accuracy = 0.6333
I0720 09:27:10.201467 7750 solver.cpp:315] Test net output #0: accuracy = 0.6719
I0720 09:27:55.011241 7750 solver.cpp:315] Test net output #0: accuracy = 0.6943
I0720 09:28:39.849061 7750 solver.cpp:315] Test net output #0: accuracy = 0.699
I0720 09:29:24.693994 7750 solver.cpp:315] Test net output #0: accuracy = 0.705
I0720 09:30:09.520272 7750 solver.cpp:315] Test net output #0: accuracy = 0.7102
I0720 09:30:54.410053 7750 solver.cpp:315] Test net output #0: accuracy = 0.7162
68
④学習実行
• 図のような学習曲線を描きたい場合もファイルから抽出可能
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
※図はサンプルなので、この値と一致しているわけではありません
73. 73
⑤学習モデルの利用
• 前スライドまで見ていたカエルの画像を
EC2上に取り込みます
$ cd
$ wget https://upload.wikimedia.org/wikipedia/commons/4/49/Green_treefrog.jpg
$ ls -ltr
total 2112
-rw-rw-r-- 1 ubuntu ubuntu 2143384 Oct 5 2013 Green_treefrog.jpg
-rwx--x--x 1 ubuntu ubuntu 2175 Apr 21 18:19 aws1404.sh
drwxrwxr-x 16 ubuntu ubuntu 4096 Apr 21 18:43 caffe
drwxr-xr-x 2 root root 4096 Apr 21 20:20 data
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
75. 75
import sys
import caffe
from caffe.proto import caffe_pb2
import numpy
cifar_map = {
0: "airplane",
1: "automobile",
2: "bird",
3: "cat",
4: "deer",
5: "dog",
6: "frog",
7: "hourse",
8: "ship",
9: "truck"
}
mean_blob = caffe_pb2.BlobProto()
with open('caffe/examples/cifar10/mean.binaryproto') as f:
mean_blob.ParseFromString(f.read())
mean_array = numpy.asarray(mean_blob.data, dtype=numpy.float32).reshape(
(mean_blob.channels, mean_blob.height, mean_blob.width)
)
classifier = caffe.Classifier(
'caffe/examples/cifar10/cifar10_quick.prototxt',
'caffe/examples/cifar10/cifar10_quick_iter_4000.caffemodel',
mean=mean_array,
raw_scale=255)
image = caffe.io.load_image(sys.argv[1])
predictions = classifier.predict([image], oversample=False)
answer = numpy.argmax(predictions)
print(predictions)
print(str(answer) + ":" + cifar_map[answer])
cifar10_classifier.py
77. 77
⑤学習モデルの利用
• 画像分類を試してみましょう
$ python cifar10_classifier.py Green_treefrog.jpg
:(省略)
[[ 4.74744802e-03 2.51210417e-06 7.85273733e-05 3.28274607e-03
5.87507930e-06 2.04037860e-05 9.91847277e-01 1.77818379e-07
3.59641581e-06 1.14896684e-05]]
6:frog
クラス毎に、そのクラスである確率を表示(指数表記)
6番目=frogである確率が、99.184………%1と最も高い
最も確率が高いものを出力
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
※どの環境でも、必ずしも「カエル」と評価されるわけではありません。。
イテレーション数を増やすと多少収束しますが、、それでも確実ではありません。。
78. 78
⑤学習モデルの利用
• 他のファイルでも試してみましょう
$ wget https://upload.wikimedia.org/wikipedia/commons/9/9b/Deaf_odd_eye_white_cat_sebastian.jpg
$ python cifar10_classifier.py Deaf_odd_eye_white_cat_sebastian.jpg
$ wget https://upload.wikimedia.org/wikipedia/commons/7/75/Yonaguniuma.jpg
$ python cifar10_classifier.py Yonaguniuma.jpg
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
81. 81
事前準備
• CIFAR-10は汎用的に画像分類として利用できるモデルなので、
これを真似して使います
• そのため作業用ディレクトリはCIFAR-10をコピーして用意して
おきます
$ cd /caffe/examples
$ cp -pr cifar10 handson
$ ls -ltr
total 2832
-rw-rw-r-- 1 ubuntu ubuntu 1063 Apr 21 18:20 CMakeLists.txt
-rw-rw-r-- 1 ubuntu ubuntu 240557 Apr 21 18:20 classification.ipynb
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 feature_extraction
-rw-rw-r-- 1 ubuntu ubuntu 623219 Apr 21 18:20 detection.ipynb
-rw-rw-r-- 1 ubuntu ubuntu 994307 Apr 21 18:20 filter_visualization.ipynb
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 finetune_pascal_detection
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 finetune_flickr_style
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 mnist
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 images
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 imagenet
-rw-rw-r-- 1 ubuntu ubuntu 467938 Apr 21 18:20 hdf5_classification.ipynb
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 hdf5_classification
-rw-rw-r-- 1 ubuntu ubuntu 511846 Apr 21 18:20 net_surgery.ipynb
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 net_surgery
drwxrwxr-x 3 ubuntu ubuntu 4096 Apr 21 18:20 web_demo
drwxrwxr-x 2 ubuntu ubuntu 4096 Apr 21 18:20 siamese
drwxrwxr-x 4 ubuntu ubuntu 4096 Jul 24 21:27 handson
drwxrwxr-x 4 ubuntu ubuntu 4096 Jul 24 21:27 cifar10
83. LFW
(Labeled Face in the Wild)
http://vis-www.cs.umass.edu/lfw/
• 研究用に作成された、著名人がラベル付けされた
画像集
– 1万枚以上の画像が収録
– 一人あたりの画像枚数は少なめ
• ちなみに、過去の自宅警備員でも利用したデータ
83
85. 85
• クレンジング済みデータはDropboxに置いて
あるので、ダウンロードしてください
①データセットの準備
$ cd
$ wget https://dl.dropboxusercontent.com/u/8148946/Develop/aws/lfw3.zip
: (省略)
$ sudo apt-get -y install unzip
: (省略)
$ unzip lfw3.zip
:(中略)
inflating: lfw3/woman/Zhang_Ziyi_0002.jpg
inflating: lfw3/woman/Zhang_Ziyi_0003.jpg
inflating: lfw3/woman/Zhang_Ziyi_0004.jpg
inflating: lfw3/woman/Zoe_Ball_0001.jpg
inflating: lfw3/woman/Zorica_Radovic_0001.jpg
$ cd lfw3
• 何故かunzipが無かったので入れます。。。
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
86. 86
• 画像ファイルは man / womanディレクトリにそれぞれ
分類して配置していますが、男性の方が画像が3倍以上あります
①データセットの準備
$ ls -ltr man | wc
8560 77033 585263
$ ls -ltr woman | wc
2574 23159 177992
• 分類するクラス毎に画像の枚数が著しく異なると、学習結果の精度が悪くなります
• そのため、男性の画像は1/3を利用することにします
(基画像を消すのではなく、DB格納時にサンプリング)
• 後で出てくるDB格納時のプログラムを見ると、削っている箇所がわかるので
時間があれば画像枚数が異なる状態で実施して結果がどうなるか試してください
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
90. 90
import os
import caffe
import lmdb
from caffe.proto import caffe_pb2
import numpy
import PIL.Image
import random
IMAGE_SIZE = 32
def make_datum(image, label):
return caffe_pb2.Datum(
channels=3,
width=IMAGE_SIZE,
height=IMAGE_SIZE,
label=label,
data=numpy.rollaxis(numpy.asarray(image), 2).tostring())
train_lmdb = '/home/ubuntu/caffe/examples/handson/handson_train_lmdb'
test_lmdb = '/home/ubuntu/caffe/examples/handson/handson_test_lmdb'
os.system('rm -rf '+train_lmdb)
os.system('rm -rf '+test_lmdb)
print 'filepaths'
label_file_map = {}
filepaths = []
for dirpath, _, filenames in os.walk('./man'):
for idx, filename in enumerate(filenames):
if filename.endswith(('.png', '.jpg')):
if idx % 3 == 0 :
continue
file = os.path.join(dirpath, filename)
filepaths.append(file)
label_file_map[file] = 0
print file
for dirpath, _, filenames in os.walk('./woman'):
for filename in filenames:
if filename.endswith(('.png', '.jpg')):
file = os.path.join(dirpath, filename)
filepaths.append(file)
label_file_map[file] = 1
print file
random.shuffle(filepaths)
print 'train'
in_db = lmdb.open(train_lmdb, map_size=int(1e12))
with in_db.begin(write=True) as in_txn:
for in_idx, file in enumerate(filepaths):
if in_idx % 6 == 0 :
continue
image = PIL.Image.open(file)
datum = make_datum(image, label_file_map[file])
in_txn.put('{:0>5d}'.format(in_idx), datum.SerializeToString())
print '{:0>5d}'.format(in_idx) + ':' + file
in_db.close()
print 'test'
in_db = lmdb.open(test_lmdb, map_size=int(1e12))
with in_db.begin(write=True) as in_txn:
for in_idx, file in enumerate(filepaths):
if in_idx % 6 != 0 :
continue
image = PIL.Image.open(file)
datum = make_datum(image, label_file_map[file])
in_txn.put('{:0>5d}'.format(in_idx), datum.SerializeToString())
print '{:0>5d}'.format(in_idx) + ':' + file
in_db.close()
※長いので分けましたが、
一つのファイルです
左をコピペした後、
その下に右をコピペしてください
create_lmdb.py
92. 92
• 重要そう(Caffe特有)なところを補足
• プログラムの下記部分について
②データの格納
return caffe_pb2.Datum(
channels=3,
width=IMAGE_SIZE,
height=IMAGE_SIZE,
label=label,
data=numpy.rollaxis(numpy.asarray(image), 2).tostring())
• channels : RGBの3色のカラー画像なので、3を指定
• labelで : クラスを示す値を指定
• 今回の場合: man = 0 / woman = 1
• 他の部分はCaffeに依存したコードではありません
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
93. 93
• プログラムを実行してLMDBに画像を
格納します
②データの格納
$ sudo pip install lmdb
: (省略)
$ python create_lmdb.py
filepaths
./man/Gunter_Pleuger_0002.jpg
./man/Adolfo_Aguilar_Zinser_0003.jpg
./man/Will_Young_0001.jpg
./man/Paul_Bremer_0011.jpg
:(中略)
08256:./woman/Caroline_Kennedy_0001.jpg
08262:./woman/Elizabeth_Berkeley_0001.jpg
08268:./man/Howard_Dean_0001.jpg
08274:./man/Ken_Watanabe_0002.jpg
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
• PythonのLMDBライブラリも無いので入れます
94. 94
• 出来上がったDBを確認します
②データの格納
$ ls -ltr /caffe/examples/handson
total 1236
-rwxrwxr-x 1 ubuntu ubuntu 325 Apr 21 18:20 train_quick.sh
-rwxrwxr-x 1 ubuntu ubuntu 508 Apr 21 18:20 train_full.sh
-rw-rw-r-- 1 ubuntu ubuntu 5262 Apr 21 18:20 readme.md
-rwxrwxr-x 1 ubuntu ubuntu 460 Apr 21 18:20 create_cifar10.sh
-rw-rw-r-- 1 ubuntu ubuntu 3760 Apr 21 18:20 convert_cifar_data.cpp
-rw-rw-r-- 1 ubuntu ubuntu 3088 Apr 21 18:20 cifar10_quick_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 859 Apr 21 18:20 cifar10_quick_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 860 Apr 21 18:20 cifar10_quick_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 1875 Apr 21 18:20 cifar10_quick.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 3122 Apr 21 18:20 cifar10_full_train_test.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 923 Apr 21 18:20 cifar10_full_solver_lr2.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 922 Apr 21 18:20 cifar10_full_solver_lr1.prototxt
-rw-rw-r-- 1 ubuntu ubuntu 2128 Apr 21 18:20 cifar10_full.prototxt
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 24 21:15 cifar10_train_lmdb
drwxr--r-- 2 ubuntu ubuntu 4096 Jul 24 21:16 cifar10_test_lmdb
-rw-rw-r-- 1 ubuntu ubuntu 12299 Jul 24 21:16 mean.binaryproto
-rw-rw-r-- 1 ubuntu ubuntu 582496 Jul 24 21:27 cifar10_quick_iter_4000.solverstate
-rw-rw-r-- 1 ubuntu ubuntu 583301 Jul 24 21:27 cifar10_quick_iter_4000.caffemodel
drwxr-xr-x 2 ubuntu ubuntu 4096 Jul 24 22:16 handson_train_lmdb
drwxr-xr-x 2 ubuntu ubuntu 4096 Jul 24 22:16 handson_test_lmdb
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
95. 95
• ファイルができているだけだと不安なので、
DBにちゃんとレコードが書き込まれているか
読み込んでみます
②データの格納
$ vi read_lmdb.py
import caffe
import lmdb
import numpy as np
from caffe.proto import caffe_pb2
lmdb_env = lmdb.open('/home/ubuntu/caffe/examples/handson/handson_train_lmdb')
lmdb_txn = lmdb_env.begin()
lmdb_cursor = lmdb_txn.cursor()
datum = caffe_pb2.Datum()
for key, value in lmdb_cursor:
datum.ParseFromString(value)
label = datum.label
data = caffe.io.datum_to_array(datum)
print str(key) +':'+str(label)
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
97. 97
• プログラムを実行してLMDBを読み込んで
みます
②データの格納
$ python read_lmdb.py
:(中略)
08252:0
08253:0
08254:1
08255:1
08257:0
08258:0
08259:0
08260:0
08261:1
08263:0
08264:0
08265:0
08266:0
:(中略)
keyとlabelを出力しています
レコードの件数とか、
クラスの割合を確認したり
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
100. # reduce the learning rate after 8 epochs (4000 iters) by a factor of 10
# The train/test net protocol buffer definition
net: "examples/handson/handson_quick_train_test.prototxt"
# test_iter specifies how many forward passes the test should carry out.
# In the case of MNIST, we have test batch size 100 and 100 test iterations,
# covering the full 10,000 testing images.
test_iter: 100
# Carry out testing every 500 training iterations.
test_interval: 500
# The base learning rate, momentum and the weight decay of the network.
base_lr: 0.001
momentum: 0.9
weight_decay: 0.004
# The learning rate policy
lr_policy: "fixed"
# Display every 100 iterations
display: 100
# The maximum number of iterations
max_iter: 4000
# snapshot intermediate results
snapshot: 4000
snapshot_prefix: "examples/handson/handson_quick"
# solver mode: CPU or GPU
100
• cifar10_quick_solver.prototxt
③パラメータ設定
$ cp -p cifar10_quick_solver.prototxt handson_quick_solver.prototxt
$ vi handson_quick_solver.prototxt
パスの変更
:%s/cifar10/handson/g でもいいかも
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
101. 101
• cifar10_quick.prototxt
③パラメータ設定
$ cp -p cifar10_quick.prototxt handson_quick.prototxt
$ vi handson_quick.prototxt
name: "handson_quick_test"
input: "data"
input_dim: 1
input_dim: 3
input_dim: 32
input_dim: 32
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
}
: (中略)
: (中略)
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 2
}
}
layer {
name: "prob"
type: "Softmax"
bottom: "ip2"
top: "prob"
}
Softmaxへの出力数を
分類するクラス数に変更
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
末尾
103. 103
name: "handson_quick"
layer {
name: "cifar"
type: "Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
transform_param {
mean_file: "examples/handson/mean.binaryproto"
}
data_param {
source: "examples/handson/handson_train_lmdb"
batch_size: 100
backend: LMDB
}
}
layer {
name: "cifar"
type: "Data"
top: "data"
top: "label"
include {
phase: TEST
}
transform_param {
mean_file: "examples/handson/mean.binaryproto"
}
data_param {
source: "examples/handson/handson_test_lmdb"
batch_size: 100
backend: LMDB
}
}
: (中略)
: (中略)
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 2
weight_filler {
type: "gaussian"
std: 0.1
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "accuracy"
type: "Accuracy"
bottom: "ip2"
bottom: "label"
top: "accuracy"
include {
phase: TEST
}
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
先頭
末尾
:%s/cifar10/handson/g でいいかも
パス、ファイル名の変更
2に変更
106. 106
$ cd /caffe
$ build/tools/caffe train --solver examples/handson/handson_quick_solver.prototxt
I0724 22:58:56.684227 11048 caffe.cpp:113] Use GPU with device ID 0
I0724 22:58:57.038519 11048 caffe.cpp:121] Starting Optimization
I0724 22:58:57.038648 11048 solver.cpp:32] Initializing solver from parameters:
test_iter: 100
test_interval: 500
:(中略)
I0724 23:04:54.502674 11048 solver.cpp:334] Snapshotting to examples/handson/
handson_quick_iter_4000.caffemodel
I0724 23:04:54.505038 11048 solver.cpp:342] Snapshotting solver state to examples/handson/
handson_quick_iter_4000.solverstate
I0724 23:04:54.534106 11048 solver.cpp:248] Iteration 4000, loss = 0.00121072
I0724 23:04:54.534142 11048 solver.cpp:266] Iteration 4000, Testing net (#0)
I0724 23:04:57.330543 11048 solver.cpp:315] Test net output #0: accuracy = 0.9437
I0724 23:04:57.330601 11048 solver.cpp:315] Test net output #1: loss = 0.253835 (* 1 =
0.253835 loss)
I0724 23:04:57.330615 11048 solver.cpp:253] Optimization Done.
I0724 23:04:57.330624 11048 caffe.cpp:134] Optimization Done.
④学習実行
• 下記のコマンドを実行してください
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行
108. 108
import sys
import os
import caffe
from caffe.proto import caffe_pb2
import numpy
answer_map = {
0: "man",
1: "woman"
}
os.system('convert '+sys.argv[1]+' -equalize test.jpg')
mean_blob = caffe_pb2.BlobProto()
with open('caffe/examples/handson/mean.binaryproto') as f:
mean_blob.ParseFromString(f.read())
mean_array = numpy.asarray(mean_blob.data, dtype=numpy.float32).reshape(
(mean_blob.channels, mean_blob.height, mean_blob.width)
)
classifier = caffe.Classifier(
'caffe/examples/handson/handson_quick.prototxt',
'caffe/examples/handson/handson_quick_iter_4000.caffemodel',
mean=mean_array,
raw_scale=255)
image = caffe.io.load_image('test.jpg')
predictions = classifier.predict([image], oversample=False)
answer = numpy.argmax(predictions)
print(predictions)
print(str(answer) + ":" + answer_map[answer])
ファイルの中身
110. 110
⑤学習モデルの利用
• 画像分類を試してみましょう
$ wget https://upload.wikimedia.org/wikipedia/commons/a/a9/Mona_Lisa_detail_face.jpg
$ python handson_classifier.py Mona_Lisa_detail_face.jpg
??????
モナリザは男性?女性?
データセット
準備
データの格納
パラメータ
設定
学習モデル
利用
学習実行