スタートアップエンジニアの作ってみた日記

ものづくりが下手な横好きなエンジニアによる作ってみた的なブログです。

Google Colaboratoryとtensorflowを使って簡単に機械学習で画像判定。

機械学習素人の私がtensorflowを触ってみたといった内容です。

以前のブログでgoogle 画像検索で画像スクレイピングしました。

https://goengine.hatenablog.com/entry/2019/08/22/000112

 

こちらの画像を使って学習させた学習モデルを使って犬か猫どうかを判定させるものを作りたいと思います。

 

事前にスクレイピングで犬の画像と猫の画像を落としてください。

そしてその画像のディレクトリを同じディレクトリに入れておいてください。

こんな感じ。(dataディレクトリ内にcat、dogディレクトリを入れてあります。)

f:id:goengine:20191006232527p:plain

 

これでデータの準備は整いました。

 

retrain.pyを使い学習させていきます。こちらのファイルを以下のgithubから落としましょう。

 https://github.com/tensorflow/hub/blob/master/examples/image_retraining/retrain.py 

こちらのpyファイルを好きなディレクトリに入れます。

 

そしてColaboratory内での以下のコマンドを実行します。

!python drive/"My Drive"/190805_test/retrain.py \
  --bottleneck_dir=bottlenecks \
  --how_many_training_steps=4000 \
  --model_dir=inception \
  --summaries_dir=training_summaries/basic \
  --output_graph=drive/"My Drive"/190805_test/retrained_graph.pb \
  --output_labels=drive/"My Drive"/190805_test/retrained_labels.txt \
  --image_dir=drive/"My Drive"/190805_test/data

それぞれのパスは自分の好きなように設定してください。

僕は自分のgoogle deiveと連携させているので"My Driveが"入ってしまっていますが、google driveと連携させなくても大丈夫です。

 

こちらは学習回数にもよりますが、10分ほど時間がかかります。

f:id:goengine:20191007002435p:plain

 

これがうまくいくと、実際に判定に必要なretrained_graph.pbファイルとretrained_labels.txtファイルができます。

 

次に判定させる処理をしていきます。

label_image.pyが必要になるので、githubから落としてきましょう。

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image/label_image.py

 

また、評価を試す画像を適当に用意します。ここでは、tes.jpgとして以下の犬の画像を用意しました。

f:id:goengine:20191007004133j:plain

 

準備ができたら以下のように入力して実行します。

!python drive/"My Drive"/190805_test/label_image.py \
--image drive/"My Drive"/190805_test/test.jpg \
--graph drive/"My Drive"/190805_test/retrained_graph.pb \
--labels drive/"My Drive"/190805_test/retrained_labels.txt \
--input_layer=Placeholder

環境によって、以下のようなこのようなエラーが出るかもしれません。

KeyError: "The name 'import/InceptionV3/Predictions/Reshape_1' refers to an Operation not in the graph."

そしたらlabel_image.pyファイル内の

input_layer = "input"

output_layer = "InceptionV3/Predictions/Reshape_1"

input_layer = "Mul"

output_layer = "final_result"

に変更してみましょう。

 

うまくいくと、このようにdogとcatどちらに近いかを0~1に間の値で返してくれます。

f:id:goengine:20191007003906p:plain

dog 0.9991762
cat 0.0008238142

今回は犬の画像を使ってテストしたので、いい結果ですね。

以上です。

 

以下のサイトを参考にさせていただきました。

ありがとうございます。

https://stackoverflow.com/questions/46325799/tensorflow-for-poets-the-name-import-input-refers-to-an-operation-not-in-the

https://qiita.com/umeee/items/ffde72ec84fa2065b1ff

https://qiita.com/quotto/items/645b01cf9c3919a52b12