Google AutoML Visionのedgeモデルをローカルのcpuで動かす
AutoML Visionで学習させたあと、そのモデルを試してみる際にはサーバへのデプロイが必要になる。 そしてリクエスト数ではなく、デプロイされている時間に応じて課金される。
で、案の定という感じではあるが、テストのためにデプロイした後、デプロイ解除をし忘れて課金されてしまった、、
以前使ったときはまだベータ版という扱いだったため時間ではなくリクエスト数で課金されていた(以下のページの旧予測)が、正式版になって変わった模様。
料金 | Cloud AutoML Vision | Google Cloud
ということで、そのようなことを避けるためにedgeモデル(これも正式版になって使えるようになった?)を使ってみた。 こちらであればモデルをダウンロードして自前のなんらかの端末で動かせるので課金されることもない。
トレーニング時のモデル選択でedgeモデルを選ぶと以下のような画面となりモデルのサイズを選ぶことができる
今回はPCで動かしたいので特に小さいモデルにする必要はないため、highを選んでおく
学習後、ローカルのdockerでモデルを動かすための手順はこちらにある
Edge containers tutorial | Cloud AutoML Vision | Google Cloud
上記のページに書いてあるとおりだが、”テストと使用”の項目からcontainerを選んでモデルをgcsへexportした後の手順をまとめて書いておく docker自体のinstallは適当にググればいろいろ出てくるはずなので割愛
$ YOUR_MODEL_PATH=/tmp $ gsutil cp gs://<project id>-vcm/<path/to/saved_model.pb> ${YOUR_MODEL_PATH}/saved_model.pb $ export CPU_DOCKER_GCS_PATH=gcr.io/automl-vision-ondevice/gcloud-container-1.12.0:latest $ docker pull ${CPU_DOCKER_GCS_PATH} $ CONTAINER_NAME=automl_high_accuracy_model_cpu $ docker run --rm --name ${CONTAINER_NAME} -p 8501:8501 -v ${YOUR_MODEL_PATH}:/tmp/mounted_model/0001 -t ${CPU_DOCKER_GCS_PATH}
リクエストを投げるスクリプトも貼っておく (上記ページのpythonスクリプトのコメント部分を消してimageファイルを引数で渡すようにしただけ)
import base64 import io import json import requests import argparse def container_predict(image_file_path, image_key, port_number=8501): with io.open(image_file_path, 'rb') as image_file: encoded_image = base64.b64encode(image_file.read()).decode('utf-8') instances = { 'instances': [ {'image_bytes': {'b64': str(encoded_image)}, 'key': image_key} ] } url = 'http://localhost:{}/v1/models/default:predict'.format(port_number) response = requests.post(url, data=json.dumps(instances)) print(response.json()) if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('image_path', help='path to image file') args = parser.parse_args() container_predict(args.image_path, 'testkey')
このスクリプトをpredict.pyとすれば以下のコマンドで推論結果が返ってくる
$ python predict.py <path/to/image>