<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hayato Yoshikawa on Medium]]></title>
        <description><![CDATA[Stories by Hayato Yoshikawa on Medium]]></description>
        <link>https://medium.com/@hayatoy?source=rss-a6d93b5c4325------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zQiRMWNVNdY7PxkZSzJZpg.png</url>
            <title>Stories by Hayato Yoshikawa on Medium</title>
            <link>https://medium.com/@hayatoy?source=rss-a6d93b5c4325------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:39:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hayatoy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cloud Run と Firestore でリアルタイムダッシュボードを作るよ]]></title>
            <link>https://medium.com/google-cloud-jp/building-connected-car-dashboard-with-cloudrun-and-firestore-dfd5af59eaa?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfd5af59eaa</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 23:56:32 GMT</pubDate>
            <atom:updated>2022-07-14T00:21:56.563Z</atom:updated>
            <content:encoded><![CDATA[<p>みなさん可視化してますか？データが有ったら、次に可視化して分析したくなりますよね。BI ツールで BigQuery から読み込めば簡単ですが、日々刻々と変わるデータを可視化してモニタリングするにはどうすればよいでしょうか？本記事では、 Cloud Run と Firestore を使って簡単にリアルタイムでデータが更新されるダッシュボードを作る方法を紹介します。</p><p>公式サイトに最新版が掲載されたのでそちらを参照ください。<a href="https://cloud.google.com/blog/ja/topics/manufacturing/building-a-mobility-dashboard-with-cloud-run-and-firestore">https://cloud.google.com/blog/ja/topics/manufacturing/building-a-mobility-dashboard-with-cloud-run-and-firestore</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfd5af59eaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/building-connected-car-dashboard-with-cloudrun-and-firestore-dfd5af59eaa">Cloud Run と Firestore でリアルタイムダッシュボードを作るよ</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Mobility Dashboard with Cloud Run and Firestore]]></title>
            <link>https://medium.com/google-cloud/building-a-mobility-dashboard-with-cloud-run-and-firestore-dfa48d193ae1?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa48d193ae1</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 02:06:53 GMT</pubDate>
            <atom:updated>2022-06-21T23:39:17.063Z</atom:updated>
            <content:encoded><![CDATA[<p>Visualization is the key to understand massive amount of data. Today we have BigQuery and Looker to analyze petabytes scale data and to extract insights in a sophisticated way. But how about monitoring data that actively changing every second? In this post, we will walk through how to build a realtime dashboard with Cloud Run and Firestore.</p><h4>Mobility Dashboard</h4><p>Actually, it is easy to build a dashboard that changes its data every second. Rather than making a simple demo, let’s make something fun and useful.. What if we can monitor realtime locations of vehicles running on roads? That’s fun! So in this post we will make a dashboard, monitoring vehicles on a map, in realtime!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*ZLLxfBJjmRA2M2gEnTnW1g.gif" /></figure><p>More details on <a href="https://cloud.google.com/blog/topics/manufacturing/building-a-mobility-dashboard-with-cloud-run-and-firestore">Google Cloud Blog</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa48d193ae1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/building-a-mobility-dashboard-with-cloud-run-and-firestore-dfa48d193ae1">Building a Mobility Dashboard with Cloud Run and Firestore</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vertex AI で AnimeGAN やってみた]]></title>
            <link>https://medium.com/google-cloud-jp/serving-animegan-with-vertex-ai-9d210e3a66a7?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d210e3a66a7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 00:08:46 GMT</pubDate>
            <atom:updated>2021-12-08T00:08:46.283Z</atom:updated>
            <content:encoded><![CDATA[<p>この記事は <a href="https://medium.com/google-cloud-jp/google-cloud-japan-advent-calendar-2021-9f9400a0ee73">Google Cloud Japan Advent Calendar 2021</a> の 8日目の記事です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGye5PI8D6yO79RZodVWNg.png" /><figcaption>original photo from <a href="https://photos.google.com/share/AF1QipO2_gTkgT1QwgYaWCTowaN6d2Cb5rvyJU10cjAdSU9Ao8v9Ec-r1v1cKdWEx6PNqg?key=WEdYT3BMNFZGdUlwQ0l6aEdFT1UwVlg2LUZESDhn">Pixel 2 library</a></figcaption></figure><h4><strong>TL;DR,</strong></h4><p>本記事では <a href="https://cloud.google.com/vertex-ai/docs/predictions/getting-predictions">Vertex AI Prediction</a> のカスタムコンテナを使って、顔写真をアニメ顔にする PyTorch版 AnimeGANv2をサービングする方法を解説します。モデルそのものの詳細や、学習方法については取り上げません。</p><h4><strong>Vertex AI Prediction とは</strong></h4><p>Vertex AI は、機械学習に関わるワークフロー（学習、推論だけではなく、データ前処理やモデルのモニタリング、パイプラインなど）を効率的に構築する統合環境です。<a href="https://cloud.google.com/vertex-ai/docs/predictions/getting-predictions">Vertex AI Prediction</a> は、スケーラブルな推論の実行環境を自動的に構築できます。単にスケールする VM やコンテナ環境というわけではなく、以下のような ML Ops で必要になる機能を備えています。</p><ul><li>バッチ、オンライン推論</li><li>リクエストの認証</li><li>トラフィック分割</li><li>モニタリング</li></ul><p><em>Motivation — とまぁ、なんとなく面倒くさいところをやってくれる便利な機能のように見えますが、少し込み入ったこと（例：カスタムコンテナ）をやろうと思うとハマりどころがいくつかあります。本来、ML Eng. にモデルの開発に専念してもらい、面倒なことは俺らがやるぜ！なプロダクトなはずなので、そんなハマりどころに時間を取られたくないですよね。本記事ではそんな苦労どころをなるべく簡単にできるよう、工夫してみました。</em></p><h4><strong>STEP 0: AnimeGAN を Colab で使ってみる</strong></h4><p>AnimeGAN は先駆者が色々前準備をしてくれたおかげで、使うこと自体はとても簡単です。本編の Vertex AI で使う事とは全く関係ありませんが、Google Colaboratory で AnimeGAN を使ってみましょう。ここは知ってるよ、という方は STEP1 に進んでください。</p><p>Colab のノートブックは <a href="https://colab.research.google.com/github/bryandlee/animegan2-pytorch/blob/main/colab_demo.ipynb">PyTorch 版のデモ</a>があるので、それを実行してみるのが手っ取り早いです。重要なのは以下の3行です。</p><pre>model = torch.hub.load(&quot;bryandlee/animegan2-pytorch:main&quot;, &quot;generator&quot;, device=device).eval()</pre><pre>face2paint = torch.hub.load(&quot;bryandlee/animegan2-pytorch:main&quot;, &quot;face2paint&quot;, device=device)</pre><pre>...</pre><pre>im_out = face2paint(model, im_in, side_by_side=False)</pre><p>上2行がモデルのロード、最後の行が実際の推論（アニメ化）です。とても簡単ですね！これは <a href="https://pytorch.org/hub/">PyTorch Hub</a> から学習済みのモデルをロードしているので、複雑なコードを書かなくても使え便利です。一旦ロードしたモデルはキャッシュされるので、実行の度にロードされることはありません。</p><h4>STEP 1: サービング用のコードに AnimeGAN を埋め込む</h4><p>今回使う AnimeGAN は PyTorch 版なので、そのまま Vertex AI にモデルを読み込むことはできません。そこで依存ライブラリを内包したカスタムコンテナに、モデルの推論コードを埋め込む必要があります。するとモデルの I/F どうするの？となるわけですが、HTTP サーバーを立てて Vertex AI の REST API の形式に合わせた<a href="https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#image">リクエストを受け取れるようにします</a>。HTTP サーバーの実装は何でもOKなのですが、特に複雑な機構は要りませんから、Flask で簡易的に実装し、リクエストの形式だけ合わせます。例えば、画像データを入力とするモデルの場合、以下のような JSON の形式で推論時の入力を受け取ります。</p><pre>{&#39;instances&#39;: [<br>  {&#39;b64&#39;: base64.b64encode(jpeg_data).decode()}<br>]}</pre><p>ここでは JPEG の画像データを BASE64 でエンコードして、JSON に埋め込んでいます。推論時にはHTTP Request Payload からこのデータを抽出し、BASE64 をデコードして画像データをモデルに入力する部分を自分で記述しなければなりません。ただこの形式は毎回変わるわけではないので、1度書いたらコードスニペットにでも入れておくとよいでしょう。以下のような感じでリクエストから画像の読み込み、モデル実行、結果を返すことができます。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6a00b90565bef09daae0e9f9d292dfd/href">https://medium.com/media/a6a00b90565bef09daae0e9f9d292dfd/href</a></iframe><h4>STEP 2: ヘルスチェック用の関数を実装する</h4><p>Vertex AI はカスタムコンテナの HTTP サーバーが正常に起動しているかを、指定のルートにリクエストを送ることで<a href="https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#health">確認します</a>。このルートが 200 を返さない限り、Vertex AI はこのコンテナに推論のリクエストをルーティングしません。モデルの読み込みや初期化に時間がかかる場合はここに判定を入れるとよいでしょう。今回は Flask を起動する前にモデルを読み込んでいるので、単純に 200 を返すコードのみを実装します。</p><pre><a href="http://twitter.com/app">@app</a>.route(&quot;/healthcheck&quot;)<br>def healthcheck():<br>  status_code = Response(status=200)<br>  return status_code</pre><p>なお、ヘルスチェックに失敗しても Vertex AI はコンテナを再起動せず、10秒毎にチェックして成功するのを待ちます。</p><h4>STEP 3: コンテナをビルドし、コンテナリポジトリに登録する</h4><p>次のステップで Vertex AI にモデルを読み込めるようにするため、Container Registry (gcr.io) に登録します。特にユニークな機構を入れる必要はないのですが、 ENTRYPOINT or CMD でHTTP サーバーを起動するのと、どの Port を開いているかは Dockerfile に記載する必要があります。必要最低限なところだけ書くと次のようになります。</p><pre>FROM python:3.7-buster</pre><pre>COPY requirements.txt ./requirements.txt<br>RUN pip install -r requirements.txt</pre><pre>COPY app.py ./app.py</pre><pre>EXPOSE 8080</pre><pre>ENTRYPOINT [&quot;python3&quot;, &quot;app.py&quot;]</pre><p>Port 番号は STEP4 でモデルを読み込むときに指定できます。ここではデフォルトの 8080 にしておきました。</p><p>ビルドと gcr.io への登録はこんな感じです。</p><pre>$ docker build -t animegan .<br>$ docker tag animegan gcr.io/${PROJECT_ID}/animegan<br>$ docker push gcr.io/${PROJECT_ID}/animegan</pre><h4>STEP 4: Vertex AI で カスタムコンテナをモデルとして登録する</h4><p>カスタムコンテナができたので、Vertex AI にモデルとして登録しましょう。Console を開いて、サイドメニューから「Vertex AI」→「Models」を開き、左上の <strong>IMPORT</strong> をクリックします。（初めて Vertex AI を開く場合は、先に「ENABLE VERTEX AI API」をクリックし、API を有効にしてください）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*U6_0Rc3_1YwHOPeO-vEyTw.png" /></figure><p>モデルの詳細を入力する画面が出てくるので、以下の必須項目を入力します。</p><ul><li>Model name — モデル名</li><li>Container image — STEP3のgcr.ioを指定</li><li>Prediction route — /predict と記載</li><li>Health route — /healthcheck と記載</li></ul><p>その他はデフォルト値でかまいません。終わったら、IMPORT ボタンを押すとモデルのインポートが開始します。数分かかるので、お茶でも入れて待ちましょう。</p><h4>STEP 5: エンドポイントを作成する</h4><p>モデルをインポートし終わったら、Vertex AI→Models のメニューに STEP4でインポートしたモデルがリストに表示されます。それをクリックし、「DEPLOY TO ENDPOINT」ボタンをクリックします。色々細かい設定ができるのですが、今回は使い方を覚えるだけなので以下の必須項目だけ入力し、「DEPLOY」ボタンをクリックします。</p><ul><li>Endpoint name — エンドポイント名</li><li>Machine type — マシンタイプ。 n1-standard-2 でとりあえずOK</li></ul><p>エンドポイントの作成にも数分時間がかかります。これでサービング環境の出来上がりです！</p><h4>リクエストを投げてみる</h4><p>Vertex AI のエンドポイントは REST API として機能しているので、HTTP Post できるクライアントであればリクエストを投げることができます。認証も組み込まれているので、Vertex AI にアクセスできるサービスアカウントを利用するとよいでしょう。クライアントライブラリを使うと次のように簡単に認証も含めたリクエストを送れます。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6a5699753aa4a5ab13285b516d0c57f/href">https://medium.com/media/a6a5699753aa4a5ab13285b516d0c57f/href</a></iframe><p>エンドポイントでは以下のように秒間リクエスト数やレイテンシーをモニタリングできます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVBF2UWycXxMPrgSgN_Rsg.png" /><figcaption>秒間リクエスト数</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUIbn6LeGcFPhMT3wf3zjw.png" /><figcaption>モデルレイテンシー</figcaption></figure><p>おまけ：動画の場合は各フレームを変換するので時間がかかりますが、並列でリクエストを投げれば時間を短縮することもできますね。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*7hP6nK_RdBmx34MT9PbGSg.gif" /><figcaption>original photo from <a href="https://photos.google.com/share/AF1QipO2_gTkgT1QwgYaWCTowaN6d2Cb5rvyJU10cjAdSU9Ao8v9Ec-r1v1cKdWEx6PNqg?key=WEdYT3BMNFZGdUlwQ0l6aEdFT1UwVlg2LUZESDhn">Pixel 2 library</a></figcaption></figure><h4>後片付け</h4><p>作成したリソースは削除しないと課金が続いてしまうので、使わない場合は削除しましょう。特にエンドポイントはノードが立ち上がっているので、早めに消した方が無駄になりません。他に使っているプロダクトがない場合はプロジェクトごと消すと簡単です。</p><h4>まとめ</h4><p>本記事では、 PyTorch 版 AnimeGAN をカスタムコンテナを使って Vertex AI でサービングする手順を紹介しました。元々のコードから、少し追加するだけで環境が立ち上がるのが体感できたのではないかと思います。</p><h4>参照</h4><p><strong>本記事のソースコード</strong></p><p><a href="https://github.com/hayatoy/vertex-ai-prediction-animegan">GitHub - hayatoy/vertex-ai-prediction-animegan</a></p><p><strong>TorchServe をカスタムコンテナで使う手順</strong><a href="https://cloud.google.com/blog/ja/topics/developers-practitioners/pytorch-google-cloud-how-deploy-pytorch-models-vertex-ai">https://cloud.google.com/blog/ja/topics/developers-practitioners/pytorch-google-cloud-how-deploy-pytorch-models-vertex-ai</a></p><p><strong>PyTorch 版 AnimeGAN</strong></p><p><a href="https://github.com/bryandlee/animegan2-pytorch">GitHub - bryandlee/animegan2-pytorch: PyTorch implementation of AnimeGANv2</a></p><p><strong>TensorFlow 版 AnimeGAN</strong></p><p><a href="https://github.com/TachibanaYoshino/AnimeGAN">GitHub - TachibanaYoshino/AnimeGAN: A Tensorflow implementation of AnimeGAN for fast photo animation ! This is the Open source of the paper 「AnimeGAN: a novel lightweight GAN for photo animation」, which uses the GAN framwork to transform real-world photos into anime images.</a></p><blockquote>Disclaimer この記事は個人的なものです｡ここで述べられていることは私の個人的な意見に基づくものであり､私の雇用者には関係はありません｡</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d210e3a66a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/serving-animegan-with-vertex-ai-9d210e3a66a7">Vertex AI で AnimeGAN やってみた</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP と Edge TPU でつくるインテリジェント IoT 基盤]]></title>
            <link>https://medium.com/google-cloud-jp/making-an-intelligent-iot-system-with-gcp-and-edge-tpu-178275458006?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/178275458006</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[edge-tpu]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[日本語]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Tue, 17 Sep 2019 00:39:48 GMT</pubDate>
            <atom:updated>2019-09-17T01:06:56.490Z</atom:updated>
            <content:encoded><![CDATA[<p>IoT はデバイスからデータを取る存在から、様々な解析をしたりエッジ側でよりインテリジェントな処理が求められる存在へと変化してきています。この記事では、 Edge TPU で複雑でインテリジェントな処理をエッジ側で実行し、GCP でその結果をリアルタイムに可視化、解析する方法を紹介します。<br><em>TL;DR — 以下のリポジトリの手順に従うと、Edge TPU と GCP上の IoT データ分析基盤を構築できます。</em><br><a href="https://github.com/google-coral/project-cloud-monitor"><em>https://github.com/google-coral/project-cloud-monitor</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*SOx3-WhgA7NwEUBGNtsi3g.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*uRhzAeBZMKtdLWJnu5rDOw.gif" /><figcaption>エッジ側（左）とクラウド側（右）</figcaption></figure><h4>Edge TPU とは</h4><p>Edge TPU は、Google が開発した TensorFlow Lite 形式の機械学習モデルを高速に演算（推論）するための ASIC のことです。2018年に発表されるまで、 TPU (Tensor Processing Unit) というとクラウド側で利用できるものだけでしたが、 Edge TPU は小型のデバイスでも実装できるよう設計されたものです。現在では、 <a href="https://coral.withgoogle.com/">Coral</a> というブランドネームのもと、いくつかの形態で実装されたデバイスが販売されています。<br>また Edge TPU は特定のタスク（画像認識や音声認識など）専門に作られたものではなく、特有の制約はあるものの TensorFLow Lite 形式のモデルであれば実行可能です。つまり、自分で独自に作ったモデルを高速に推論することができます。</p><h4>インテリジェントな IoT の必要性</h4><p>IoT がインテリジェントだとどんな良いことがあるのでしょうか？実はほとんどの業種業界で、ビジネスの課題解決に役立ちます。例えば製造業では悩みのタネである、生産ラインにおける外観検査があります。外観検査とは、その名の通り商品や製造物の外観（見た目）の不具合を検査する工程のことです。傷が入っていたり、変色していたりするものを目や機械で判断して除きますが、最近では機械学習による画像識別で不具合を検知する場合もあります。画像識別はクラウド上でももちろん行えますが、そのためには画像をクラウド に送信し、推論結果のレスポンスを待つ必要があります。これは速くても数百msかかります。この検査にかかる時間は生産のコストに反映されるので、検査は短時間で行える方が経済的です。つまりEdge TPU などを使ってエッジ側で高速に推論するのが理にかなっています。一方、画像識別をするためのモデルの学習は、多くの計算リソースとデータが必要となるため、クラウドの潤沢なリソースを使った方が時間もコストも削減できます。学習データの収集も複数のエッジからクラウドに集約する方がよいでしょう。また、学習がし終わって実際に検査を行う段階になった場合は、その検査が正しく行われているかモニタリングしたいでしょう。これも、クラウドで集中管理する方が合理的です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*oRhfa2B6q3UQ0cr7CqjmbA.png" /><figcaption>エッジとクラウド、双方を使い分け連携する</figcaption></figure><p>このようにエッジ側が単にインテリジェントになるだけではなく、 IoT としてクラウドと連携することによって実際の運用に耐えうる価値を創出することができます。</p><h3>GCP と Edge TPU でインテリジェントな IoT 基盤をつくる</h3><p>それでは GCP と Edge TPU を組み合わせて、上記のようなインテリジェントな IoT 基盤を構築してみましょう。ここでは、次のようなアーキテクチャを考えます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*KYlDW6cidw1Jx3VTrULPUQ.png" /></figure><p>Coral Dev Board がエッジ側のデバイスです。ここで、Edge TPU を使ってカメラに映った物体を高速にオブジェクト検知します。オブジェクト検知とは、画像の中にある、特定のオブジェクト（車や人など）を検知し、その画像上の位置を矩形などで出力することです。一般的には CNN を含むモデルにより実現されますが、これを CPU のみで演算する場合は非常に重く、リッチなハードウェア構成を組めない IoT デバイスでは高速に実行するのは困難です。Edge TPU にこれを演算させることで、非常に高速に検知結果を得ることができます。<br>Coral Dev Board で検知された結果（矩形の位置やオブジェクトの種類）は、MQTT プロトコルで IoT Core に送信されます。データは Pub/Sub を経由し、BigQuery と Firestore に保存されます。この一連の ETL 処理は、Dataflow によって実行されます。<br>Firestore は、リアルタイムにデータのやりとりを行いたい場合に便利な DB です。一度 Firestore に対してデータを書き込むと、そのデータをリッスンしている複数のクライアントに自動的に同期されます。このアーキテクチャでは、Google App Engine でホストしている WebUI から、Firestore のデータを読み込んでいます。</p><h4>構築手順</h4><p><a href="https://github.com/google-coral/project-cloud-monitor">https://github.com/google-coral/project-cloud-monitor</a><br>手順は上記リポジトリに記載されているので、ここでは各要素の補足を解説することにします。</p><p><strong>エッジ側処理<br></strong>エッジ側はオブジェクト検知のモデルを実行し、カメラに映った画像中の特定のオブジェクトを検知します。このモデルは <a href="http://cocodataset.org/#home">COCO</a> というオープンなデータセットを MobileNet SSD v1 のネットワークで学習したものを利用しています。90種類のオブジェクト（車、くだもの、動物など）を検知することができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*QtnLgGvt3zDfjPsx1cLKXg.jpeg" /><figcaption>オブジェクト検知例 [CC BY 4.0] : <a href="http://cocodataset.org/#explore?id=39555">http://cocodataset.org/#explore?id=39555</a></figcaption></figure><p>Edge TPU では量子化した TensorFlow Lite のモデルを、Edge TPU 用にコンパイルして使います。Python API が用意されているので、コンパイル済みの tflite ファイルを API で読み込むだけで、推論を実行することができます。</p><p><strong>データパイプライン</strong><br>IoT Core で受け取ったデータは、 Pub/Sub でキューイングされて必要な変換処理や保存先に渡すことができます。Dataflow を使うと、この一連の処理を行うパイプラインを簡単に構築することができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*9QHWZ-YH30xvQY3-LHyUIw.png" /><figcaption>本構成の Dataflow パイプライン</figcaption></figure><p>ここでは Pub/Sub から受け取ったデータを、少し整形して Firestore と BigQuery に書き込んでいます。BigQuery は書き込むだけでその後何かに使っている訳ではありませんが、BigQuery に全てのデータを保管しておくことで、アドホックに解析したい場合に即座にそれが実行できるので便利です。また、クエリを実行しない場合はストレージコストだけしかかからないため、とりあえず保存する、といった用途でもとてもリーズナブルです。一方 Firestore は前述した通りリアルタイムに結果を表示するために使います。このパイプラインでは全てのデータを Firestore に書き込んでいますが、データを送信するデバイスが増えてくる場合は集計した結果のみを Firestore に書き込むなど、工夫するとよいでしょう。また本稿執筆時点（2019年9月）では Firestore の Data Sink は無いため、<a href="https://googleapis.dev/python/firestore/latest/index.html">Python の API</a> を使って実装しています。次のようにクライアントライブラリを使えば簡単に Firestore への書き込みを行えます。</p><pre>db = firestore.Client()<br>doc_ref = db.collection(u&#39;users&#39;).document(u&#39;alovelace&#39;)<br>doc_ref.set({<br>    u&#39;first&#39;: u&#39;Ada&#39;,<br>    u&#39;last&#39;: u&#39;Lovelace&#39;,<br>    u&#39;born&#39;: 1815<br>})</pre><p><strong>Web UI</strong><br>GAE (Google App Engine) を使って、Web UI 用のページをホスティングしています。Firestore からのデータ読み込みは、HTML 内に記述した Javascript で行なっています。Firestore は Javascript 用のライブラリも提供されているため、リアルタイムにデータが変更される Web UI を簡単に構築することができます。例えば、 COL という Collection の中にある DEV という Document に変更があった場合に何らかの処理を行いたい場合、次のような数行のコードを書くだけでそれが実装できます。</p><pre>var db = firebase.firestore();<br>db.collection(&quot;COL&quot;).doc(&quot;DEV&quot;).onSnapshot(function(doc) {<br>    // 値が更新されたときに実行するコード<br>});</pre><p>また、今回は実装していませんが、IoT Core を使ってエッジ側に対してデータを送信することも容易です。GAE 等からコントロールする場合は<a href="https://googleapis.dev/python/iot/latest/index.html">クライアントライブラリ</a> を使うとよいでしょう。</p><h4>まとめ</h4><p>今回アーキテクチャで使用したプロダクトは、全てフルマネージドなものです。実際にコードをなぞっていくことで、それぞれの要素がいかに簡単に実装できるかを体感できると思います。<br>次回は、モデルの学習とエッジへのデプロイについて解説します。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=178275458006" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/making-an-intelligent-iot-system-with-gcp-and-edge-tpu-178275458006">GCP と Edge TPU でつくるインテリジェント IoT 基盤</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a Banana Seeker Robot with Coral Edge TPU]]></title>
            <link>https://medium.com/@hayatoy/making-a-banana-seeker-robot-with-coral-edge-tpu-169c993fc370?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/169c993fc370</guid>
            <category><![CDATA[edge-tpu]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Thu, 02 May 2019 15:17:44 GMT</pubDate>
            <atom:updated>2019-05-02T15:39:43.476Z</atom:updated>
            <content:encoded><![CDATA[<p><em>TL,DR; In this article you will learn how to make a robot that moves closer to a banana, with object detection model accelerated by Edge TPU.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*crYRG1X9OZZ0WyfPNxKI8w.gif" /><figcaption>Everyone loves banana!</figcaption></figure><h3>How does it work?</h3><p>This robot is built on Raspberry Pi 3 B+ connecting L298N motor driver that drives 2 motors, and detecting object with camera accelerated by Coral USB Accelerator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkesRyBhLZLyLAyMuV3Ygw.png" /><figcaption>HW Architecture of the robot</figcaption></figure><p>Let’s walk through how it works.</p><h3>Object Detection</h3><p>Object Detection is an algorithm or a program that literally detects particular object(s) within an image. Typically it addresses locations of objects with rectangles (see attached image).<br>Today you can easily implement object detection because these technologies are mostly using deep learning, and pre-trained models are provided by several sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ZJ93T9HqgreJghCOzPWzAg.png" /><figcaption>Detecting multiple objects in a picture (using Vision API on GCP)</figcaption></figure><h3>Raspberry Pi + Coral USB Accelerator + MobileNet SSD v2</h3><p>It is a bit tough to run an object detection model on Raspberry Pi, because it requires bunch of CPU resources thus it causes slow response on detection (typically more than a second per image) even though you use a model made for mobile usage such as MobileNet SSD. <br>With <a href="https://coral.withgoogle.com/products/accelerator">Coral USB Accelerator</a>, you can make the detection time more than 10x faster.</p><p>You can find a quick &amp; easy walkthrough object detection demo with Edge TPU on <a href="https://coral.withgoogle.com/docs/edgetpu/api-intro/">Coral website</a>, but it doesn’t have real-time demo. If you want to monitor what’s detected on camera in real-time, you can make it with picamera and its overlay function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6cae2e5c9fdf50ec8371069c25f4db6/href">https://medium.com/media/b6cae2e5c9fdf50ec8371069c25f4db6/href</a></iframe><h3>Motor Driver</h3><p>Meanwhile, we need to drive motors so that Raspberry Pi works like a robot! Fortunately Raspberry Pi already has GPIO pins that can send and control signals to external devices. But do not drive motors directly by GPIO, use L298N H-Bridge DC motor driver instead. L298N motor driver can drives DC motors by Raspberry Pi GPIO’s LVTTL signals. <br>You can control this motor driver with 3 GPIO pins for each motor, feeding HIGH or PWM to EN pin and HIGH/LOW to IN1/2 pins. The code would be something like below.</p><pre>import RPi.GPIO as GPIO<br># Setup<br>GPIO.setmode(GPIO.BCM)<br>GPIO.setup(14, GPIO.out)  # connect to IN1<br>GPIO.setup(15, GPIO.out)  # connect to IN2<br>GPIO.setup(18, GPIO.out)  # connect to ENA</pre><pre># Run a motor CW or CCW (depends on how you connect)<br>GPIO.output(14, GPIO.HIGH)<br>GPIO.output(15, GPIO.LOW)<br>GPIO.output(18, GPIO.HIGH)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvQJi8N7exKqEOIdCEH7UA.jpeg" /><figcaption>L298N H-Bridge DC Motor Driver board</figcaption></figure><p>If you are interested in the mechanism of this driver, refer to <a href="https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/">this tutorial</a>.</p><h3>Simple Logic to Seek a Banana</h3><p>Now we have an object detection model with Raspberry Pi Camera, and can drive motors. Let’s combine these two functions and make it work like an intelligent robot. At this time we want the robot to seek a banana (which here means following a banana), how can we achieve this?<br>This can be very complex, but be simple at this time. If the banana is in the left side of camera frame, turn left, if right side, turn right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*H4XKtMrjDy5NJsKCCfof_w.png" /></figure><h3>Wrap up — why on edge? why need accelerator?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHJatCQilzDAjiqgYFsV4w.jpeg" /><figcaption>Too prototype? but it works!</figcaption></figure><p>You may wonder why we use object detection model on Edge TPU instead of Cloud nor CPU? It depends on what application you need. In this application the robot detects objects and drives motors for each frame, which is 10 frames per second. What if it takes more than a second per frame? The robot must wait a second to detect, drives motors, and wait a second and drives motors… You see, fast iteration is needed for this application. As it’s written earlier CPU is a way too slow for object detection, what about Cloud? It can be faster than Edge TPU because you can use powerful GPU or even Cloud TPU. However detecting objects on Cloud means you have to send images to Cloud for each frames, it requires bandwidth and doesn’t work when offline.</p><p>Check out the whole source code on my <a href="https://github.com/hayatoy/edgetpu-robo">GitHub repository</a>.<br>There will be an article for integrating with Cloud.. maybe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=169c993fc370" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GAE スタンダード環境で scikit-learn を使う]]></title>
            <link>https://medium.com/google-cloud-jp/gae-standard-with-scikit-learn-dff5ad1a0ea1?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff5ad1a0ea1</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-app-engine]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 23:57:48 GMT</pubDate>
            <atom:updated>2018-10-08T23:57:48.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*V2FUZFl55imw5GNgCsztLg.png" /></figure><p>Google Cloud Next ’18 in San Francisco にて、Google App Engine スタンダード環境の <a href="https://cloud.google.com/blog/products/gcp/bringing-the-best-of-serverless-to-you">Python 3.7 対応</a>がアナウンスされました。Pythonista の方々には朗報ですが、実はそれ以外にも大きな変更がありました。</p><h4>C で書かれたライブラリの使用が可能に</h4><p>今までの GAE スタンダード環境 Python ランタイムでは、ライブラリはホワイトリスト化された特定のビルトインのものか、Pure Python のものという制限がありました。これは従来のランタイムで使用されていたアイソレーション環境では、システムの安全性を保証できなかったからです。一方、今回Python 3.7 が動作する<a href="https://cloud.google.com/blog/products/gcp/introducing-app-engine-second-generation-runtimes-and-python-3-7">第２世代ランタイムでは、gVisor をベースとしたアイソレーション環境</a>により安全性が担保できるため、内部的にCで書かれた Pythonライブラリもロードして使用することができます。これは長年のGAEファンには待望の機能拡張ではないでしょうか？<br>このおかげで、従来は使えなかった scikit-learn¹ なども使うことができます。</p><h3>Oren Teich on Twitter</h3><p>Google uses technology based on gVisor in production for many Google services serving hundreds of billions of requests per day including App Engine standard, Cloud Functions, and CloudML.</p><h4>scikit-learn を GAE スタンダード環境で使う準備</h4><p>GAE スタンダード環境でこれらCで書かれたライブラリをロードするには、まずはapp.yaml でPython 3.7 を使う事を定義します。</p><pre>runtime: python37</pre><p>その後requirements.txt にライブラリ名を記載をするだけです。</p><pre>scikit-learn==0.20.0</pre><p>これだけです！簡単ですね。 pip install -t lib -r requirements.txt なども実行する必要はありません<em>（ローカル環境でテストしたい場合を除く）。</em></p><h4>scikit-learn のモデルを Serving する</h4><p>scikit-learn で学習したモデルは、 joblib を使ってファイルにしておくことができます。ここでは簡単に、あらかじめローカル環境にて Iris のデータを SVM で学習しておいたモデルを、GAE 環境で Serving してみましょう。<br>ローカルで学習するには、次のコードを実行します。</p><pre>from sklearn import svm<br>from sklearn import datasets</pre><pre>clf = svm.SVC(gamma=&#39;scale&#39;)<br>iris = datasets.load_iris()<br>X, y = iris.data, iris.target</pre><pre># 学習<br>clf.fit(X, y)</pre><pre># ファイルにする<br>from sklearn.externals import joblib<br>joblib.dump(clf, &#39;iris.joblib&#39;)</pre><p>実行すると、 iris.joblib というファイルが生成されます。このファイルをデプロイするファイルに含めれば、GAE環境でも学習済みモデルをロードすることができます。</p><h4>GAE にデプロイするファイルを準備</h4><p>GAE スタンダード環境で必要なファイルはごく少数です。ここでは次のようなファイル構成を用意します。</p><pre>gae-sklearn<br>  |-- app.yaml<br>  |-- requirements.txt<br>  |-- main.py<br>  |-- iris.joblib</pre><p>これだけです。 app.yamlと iris.joblib は先に記載した通りですが、 requirements.txt は Webフロントエンドフレームワークとして Flask を使いたいので、次のように書きます²。</p><pre>Flask==1.0.2<br>scikit-learn==0.20.0</pre><p>次は推論のデータリクエストに対し、学習済みモデルで推論した結果を返すハンドラを main.py に記載します。推論したい特徴ベクトルを JSON で受け取り、scikit-learn の学習済みモデルで推論し、その結果を JSON で返す簡単なコードです。</p><pre>from flask import Flask, request, jsonify<br>from sklearn.externals import joblib</pre><pre>clf = joblib.load(&#39;iris.joblib&#39;)<br>app = Flask(__name__)</pre><pre>@app.route(&#39;/predict&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def predict():<br>  dat = request.json<br>  pred = clf.predict(dat[&#39;data&#39;])<br>  return jsonify({&quot;predicted_class&quot;: pred.tolist()})</pre><pre>if __name__ == &#39;__main__&#39;:<br>  app.run(host=&#39;127.0.0.1&#39;, port=8080, debug=True)</pre><p>これでコーディングは完了です。GAE 環境にデプロイしましょう。デプロイは今まで通り、 gcloud app deploy で行えます。</p><pre>$ cd gae-sklearn<br>$ gcloud app deploy .</pre><p>デプロイが完了したら、リクエストを投げてみましょう。 今回は JSON でデータを受け付ける構成にしたので、次のように application/json ヘッダをつけてリクエストします。<strong><em>[project_id]</em></strong> の部分は自分のプロジェクトIDに書き換えてください。</p><pre>$ curl -H &quot;Content-Type: application/json&quot; \<br>    --data &#39;{&quot;data&quot;:[[0,0,0,0]]}&#39; \<br>    https://<strong><em>[project_id]</em></strong>.appspot.com/predict</pre><p>リクエストに成功すると、次のように推論結果が返ってきます。 2 のラベルのようですね。</p><pre>{&quot;predicted_class&quot;:[2]}</pre><p>このように、 Cで書かれたライブラリを簡単に使う事ができるようになりました。今まで GAE スタンダード環境に魅力を感じたものの、使いたいライブラリが実行できないため泣く泣く別の環境を選択した方も、もう一度GAE を検討してみてはいかがでしょうか？</p><p>[1] ライブラリが Python 3.7 に対応している必要があります。TensorFlowは本記事執筆時点では Python 3.7 に未対応であるため、requrements.txt に記載してもインストールできません。</p><p>[2] 今回の構成だと、デフォルトのインスタンスタイプではメモリ不足になる場合があります。その際は app.yaml に instance_class: F2 などを追記し、よりメモリの多いタイプを使うと解決します。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff5ad1a0ea1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/gae-standard-with-scikit-learn-dff5ad1a0ea1">GAE スタンダード環境で scikit-learn を使う</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DataflowとTFRecordでシームレスなMLパイプライン構築]]></title>
            <link>https://medium.com/google-cloud-jp/dataflow%E3%81%A8tfrecord%E3%81%A7%E3%82%B7%E3%83%BC%E3%83%A0%E3%83%AC%E3%82%B9%E3%81%AAml%E3%83%91%E3%82%A4%E3%83%97%E3%83%A9%E3%82%A4%E3%83%B3%E6%A7%8B%E7%AF%89-284766efa05f?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/284766efa05f</guid>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[dataflow]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 01:01:55 GMT</pubDate>
            <atom:updated>2018-06-05T02:59:14.023Z</atom:updated>
            <content:encoded><![CDATA[<p>最近では、機械学習を用いた事例が徐々に聞かれるようになってきました。しかし、MLエンジニアの方々からは「モデルを作ったはいいが、プロダクションに持っていくのは難しい」という声をよくいただきます。この要因は様々ですが、システムとして考慮しなければならない構成が多いというのが主だった要因になっています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Of2gMWTy0y2nsT2P-4SkiA.png" /><figcaption>モデルはシステム全体のごく一部（黒い四角部分）</figcaption></figure><p>中でも特にMLエンジニアを悩ませるのは、データの前処理ではないでしょうか？機械学習では学習と推論時にデータを入力する必要がありますが、プロダクション時のデータは取得してそのままモデルに入力することはできません。なぜなら、データには欠損があるかもしれないし、画像ならモデルに合わせてサイズや階調を変える必要があるからです。さらに、これらのデータが大量にある場合は、１台のマシンでは処理しきれなくなるため、分散環境を構築する必要があります。そして、将来どこかで推論結果がおかしいとなったとき、モデルだけでなく前処理の仕組みや、データになにか問題がないか調査しなければなりません。これらを全て考慮してシステム設計するのは非常に大変です。</p><p>実はこの面倒臭さは、DataflowとTFRecordを組み合わせるとほとんど解決してしまいます。Dataflowは<a href="https://medium.com/google-cloud-jp/tensorflow-hub-dataflow-70786ff1b7ae">前回の記事</a>でも紹介しましたが、TFRecordとは何でしょうか？<br><strong>TFRecordとは</strong><br>TensorFlowでのモデルの学習に最適なレコード指向のデータフォーマットです。GCS上にシャーディングして配置することで、モデルが分散環境にあっても効率的にデータをロードすることができます。Dataflowを使うと、データの前処理を簡単に分散環境で実行できるだけでなく、このTFRecord形式のファイルを簡単にGCS上に保存することができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbKohLzb9yIZxWB6t2RHdA.png" /><figcaption>DataflowとTFRecordを使ったMLパイプラインの例</figcaption></figure><p>それでは例として、GCS上に保存された大量の画像を、Dataflowで加工してTFRecordでGCSに保存する、というDataflowのコードを書いてみましょう。</p><h4>大量画像の例：衛星画像</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*HyUZR-muqhpyUCtrFioScQ.png" /></figure><p>GCSの公開データの1つに、<a href="https://cloud.google.com/storage/docs/public-datasets/landsat">ランドサット衛星の衛星画像</a>があります。米国地質調査所（USGS）と NASA から提供された衛星画像のデータセットで、GoogleがGCS上にホスティングしており、GCPユーザーは自由にアクセスすることができます。膨大な数の画像がある上、サイズも大きく、加工しないと通常のモデルには使えないので、実践的な例と言えるでしょう。<br>これらの画像のインデックスは、<a href="https://bigquery.cloud.google.com/table/bigquery-public-data:cloud_storage_geo_index.landsat_index">BigQueryのデータセット</a>として用意されています。そこで、BigQueryでインデックスを読み込み、GCSから画像をロードするというパイプラインにしてみましょう。</p><p>BigQueryからクエリ結果をパイプラインに流すのはとても簡単です。次のようにBigQuerySourceをパイプラインの先頭に設定するだけです。このクエリは画像ファイルが保存されているGCSのパスが記載されているカラム ( base_url )のみを取得します。</p><pre>p = beam.Pipeline(options=options)</pre><pre>query = &quot;SELECT&quot; \<br>&quot;  base_url &quot; \<br>&quot;FROM&quot; \<br>&quot;  `bigquery-public-data.cloud_storage_geo_index.landsat_index` &quot; \<br>&quot;LIMIT&quot; \<br>&quot;  10&quot;</pre><pre>(p | &#39;gcs_path&#39; &gt;&gt; beam.io.Read(beam.io.BigQuerySource(<br>                                  project=PROJECTID,<br>                                  use_standard_sql=True,<br>                                  query=query))<br>   | ...次のTransform...</pre><h4>TFRecordで保存</h4><p>画像を加工したら、TFRecord形式でGCSに保存しましょう。これは<a href="https://beam.apache.org/documentation/sdks/pydoc/2.2.0/apache_beam.io.tfrecordio.html">WriteToTFRecord</a>を使うだけで実現できますが、与えるデータ(PCollection)は少し工夫が必要です。</p><pre># パイプラインにWriteToTFRecordを追加<br>(p | &#39;write&#39; &gt;&gt; beam.io.tfrecordio.<strong>WriteToTFRecord</strong>(<br>                                      &#39;gs://[BUCKET]/path/img&#39;,<br>                                      file_name_suffix=&#39;.tfrecord&#39;)<br>)</pre><p>WriteToTFRecordに与えるデータは、次の例のようにtf.train.Exampleをシリアライズしたものである必要があります。ここでは画像のrawデータと、縦横の画素サイズを特徴量としてデータ化しています。モデルの学習には（分類問題の場合）ラベルも必要なので、ここで合わせてデータ化しておくとよいでしょう。</p><pre>def serialize_element(element):<br>  # 何らかの処理<br>  ...</pre><pre>  # 保存するデータ<br>  height = tf.train.Int64List(value=[256])<br>  width = tf.train.Int64List(value=[256])<br>  img_raw = tf.train.BytesList(value=[img_raw])</pre><pre>  # tf.train.Exampleを作成<br>  example = tf.train.Example(features=tf.train.Features(feature={<br>    &#39;height&#39;: tf.train.Feature(int64_list=height),<br>    &#39;width&#39;: tf.train.Feature(int64_list=width),<br>    &#39;img_raw&#39;: tf.train.Feature(bytes_list=img_raw)}))</pre><pre>  # シリアライズする<br>  return example.SerializeToString()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQIg3sKAgmdVAnOGUGmydg.png" /><figcaption>実行し終わるとこのようにTFRecordのファイル群が生成される</figcaption></figure><h4>Dataflowでパイプライン実行</h4><p>コードをローカルで実行すると、自身のコードをパッケージングしてデプロイとDataflowのjob実行まで自動で行われます。Consoleを見ると実行状況と、どれ位スケールしているかが時系列のチャートで確認する事ができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaJIATsp9eG0dJ9WZwnLCA.png" /><figcaption>Dataflow実行中の画面。徐々にスケールしていくのがグラフィカルに表示される</figcaption></figure><h4>TFRecordの読み込み</h4><p>Dataflowの実行が終わったら、生成されたTFRecordファイルをTensorFlowのコードから読み込んでみましょう。読み込みは簡単で、TFRecordDatasetでGCS上に保存されたファイルを読み込み、あとはイテレータを使って逐次データを取り出すだけです。ここではmapを使ってTFRecordファイル中の特徴量のうち一部だけを取り出すようにしています。</p><pre>import tensorflow as tf<br>import numpy as np<br>from PIL import Image</pre><pre>def _parse_feature(example_proto):<br>  features = {<br>    &quot;height&quot;: tf.FixedLenFeature((), tf.int64, default_value=0),<br>    &quot;width&quot;: tf.FixedLenFeature((), tf.int64, default_value=0),<br>    &quot;img_raw&quot;: tf.FixedLenFeature((), tf.string, default_value=&quot;&quot;)}<br>  parsed_features = tf.parse_single_example(example_proto, features)<br>  return parsed_features[&quot;img_raw&quot;], parsed_features[&quot;height&quot;]</pre><pre># 保存したTFRecordを読み込み、データセットを作成<br>gcs_path = &#39;gs://[BUCKET]/tfrecord/&#39;<br>filenames = [gcs_path + fn for fn in tf.gfile.ListDirectory(gcs_path)]<br>dataset = tf.data.TFRecordDataset(filenames)<br>dataset = dataset.map(_parse_feature)</pre><pre>batched_dataset = dataset.batch(1)</pre><pre>with tf.Session() as sess:<br>  # １回だけデータセットをイテレーションする<br>  iterator = batched_dataset.make_one_shot_iterator()<br>  raw, height = iterator.get_next()<br>  img_string = sess.run(raw)</pre><pre># 画像を可視化<br>im = np.fromstring(img_string[0], dtype=np.uint32)<br>img = Image.fromarray(im.reshape((256, 256)))<br>img.convert(&#39;RGB&#39;).save(&#39;out.png&#39;)</pre><h4>Template化してパイプラインをバージョニング</h4><p>冒頭で述べたように、MLシステムを運用していると、モデルの推論結果に異常が見られたり、または精度が低下してくる場合があります。このときはモデルやデータを見直すだけでなく、前処理のパイプラインを見直し、場合によっては過去のバージョンにロールバックする必要があります。DataflowにはTemplateという機能があり、パッケージングした処理パイプラインをGCSに保存しておくことで、APIからそのパイプラインにJob実行指示をすることできます。このTemplateを利用することで、前処理のパイプラインをバージョニングすることができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tb0NC0syxcxky01qiGU95A.png" /><figcaption>データ、前処理、モデルを全てバージョン管理し、いつでもロールバックできるようにする</figcaption></figure><p>DataflowのTemplateを作るのは非常に簡単です。オプションの設定に次の１行を追加するだけで、パッケージングからGCSへのアップロードまで自動で行ってくれます。</p><pre>options = beam.options.pipeline_options.PipelineOptions()</pre><pre>google_cloud_options = options.view_as(<br>  beam.options.pipeline_options.GoogleCloudOptions)<br>google_cloud_options.<strong>template_location</strong> = &quot;gs://[BUCKET]/path/name&quot;</pre><h4>TemplateをAPIで実行</h4><p>Template化したら、次はAPIから呼び出してみましょう。REST APIでJobの実行指示を出すだけなので、どの環境（たとえDataflowのSDKが入っていなくても）からでも実行することができます。GCPの環境から実行するなら、Discovery APIを使うと認証も自動で行ってくれるので楽です。GAEのcronで定期実行する、といった使い方もすることができます。</p><pre>from oauth2client.client import GoogleCredentials<br>from oauth2client.service_account import ServiceAccountCredentials<br>from apiclient.discovery import build</pre><pre>credentials = GoogleCredentials.get_application_default()<br>service = build(&quot;dataflow&quot;, &quot;v1b3&quot;, credentials=credentials)<br>templates = service.projects().templates()</pre><pre>BODY = {<br>         &quot;jobName&quot;: &quot;JOB名&quot;,<br>         &quot;gcsPath&quot;: &quot;gs://[BUCKET]/path/&quot;,<br>         &quot;environment&quot;: {<br>           &quot;tempLocation&quot;: &quot;gs://[BUCKET]/temp&quot;,<br>         }<br>       }</pre><pre>dfrequest = service.projects().templates().create(<br>  projectId=PROJECT, body=BODY)<br>dfresponse = dfrequest.execute()</pre><h4>最後に</h4><p>機械学習のシステムは、データに依存して結果が不安定になりがちです。そこにシステムの不安定さが加わると、不具合の真の原因を追求するのが非常に困難になります。今回のようなサーバーレス環境であれば、インフラ部分はクラウドに任せる事ができるので、機能に集中して開発と運用を行うことができます。DataflowならPythonでも書けるので、データ処理系はちょっと苦手・・・というMLエンジニアの方々にとっても簡単です。是非お試しください。</p><blockquote><em>Disclaimer この記事は個人的なものです｡ここで述べられていることは私の個人的な意見に基づくものであり､私の雇用者には関係はありません｡</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=284766efa05f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/dataflow%E3%81%A8tfrecord%E3%81%A7%E3%82%B7%E3%83%BC%E3%83%A0%E3%83%AC%E3%82%B9%E3%81%AAml%E3%83%91%E3%82%A4%E3%83%97%E3%83%A9%E3%82%A4%E3%83%B3%E6%A7%8B%E7%AF%89-284766efa05f">DataflowとTFRecordでシームレスなMLパイプライン構築</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TensorFlow Hub を Cloud Dataflowで使ってみた]]></title>
            <link>https://medium.com/google-cloud-jp/tensorflow-hub-dataflow-70786ff1b7ae?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/70786ff1b7ae</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Fri, 06 Apr 2018 06:01:27 GMT</pubDate>
            <atom:updated>2018-06-05T02:49:33.801Z</atom:updated>
            <content:encoded><![CDATA[<p>先日の<a href="https://www.tensorflow.org/dev-summit/">TF Dev Summit 2018</a>で発表されたTensorFlowの新機能に、<a href="https://www.tensorflow.org/hub/">TensorFlow Hub</a>というのがあります。これはDockerでいえばDockerHubに該当するもので、モデルを簡単に共有できるエコシステムの一部です。本記事執筆時点(2018年4月)ではまだ一般ユーザーが独自のモデルをHubへアップロードすることはできませんが、現在多くの有用な学習済みモデルがGoogleから提供されています。</p><p><strong>何の記事？</strong><br>上記のTensorFlow HubをDataflowから使い、バッチでたくさんの画像の特徴量を抽出してみよう、というお話です。</p><p><strong>Dataflowって何？</strong><br><a href="https://cloud.google.com/dataflow/">Cloud Dataflow</a>とはGoogle Cloud Platformのプロダクトの1つで、いわゆるETLに該当します。サーバーレス環境なので、ほんの数十行のコードでオートスケールする大規模なデータ処理が可能です。実はこのDataflow、TensorFlowとも非常に相性がよく、TFRecord形式で出力もできるので学習データの前処理なんかもできてしまいます！</p><h3>TensorFlow Hubの使い方</h3><p>TensorFlow Hubを使うのはとても簡単です。まずはライブラリのインストールをします。TensorFlowのバージョンは1.7以降が必須なので、すでに下位バージョンをインストール済みの環境では-U をつけてアップグレードしましょう。</p><pre>pip install “tensorflow&gt;=1.7.0”<br>pip install tensorflow-hub</pre><p>次にTF Hubで学習済みモデルをロードします。</p><pre>import tensorflow as tf<br>import tensorflow_hub as hub<br>module = hub.Module(“<a href="https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1">https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1</a>&quot;)</pre><p>以上！ 簡単ですね。これはちなみにInception-v3というモデルにImagenetの画像データを学習させたものです。通常は1000クラスを識別するモデルですが、TopのDenseレイヤーがすでに切り離されている状態で用意されており、新たなDenseレイヤーを追加して転移学習がしやすくなっています。</p><h3>DataflowでTensorFlow Hubを使うには</h3><p>DataflowにもTensorFlowはプリインストール済みですが、現時点ではv1.7が入っていないので、別途インストールしてあげる必要があります。</p><p>Dataflowにライブラリを追加する方法はいくつかありますが、今回はsetup.pyを使う方法を紹介します。まずは次のようなsetup.pyを作成します。</p><pre>import setuptools</pre><pre>setuptools.setup(<br> name=’df-tfhub’,<br> version=’0.1&#39;,<br> install_requires=[‘tensorflow&gt;=1.7.0’, ‘tensorflow-hub’],<br> packages=setuptools.find_packages(),<br>)</pre><p>次にsetup.pyをPipelineOptionsに設定します。</p><pre>options = beam.options.pipeline_options.PipelineOptions()<br>setup_options = options.view_as(beam.options.pipeline_options.SetupOptions)<br>setup_options.setup_file = &#39;./setup.py&#39;</pre><p>これで終わりです。あとは自由にTF Hubをつかえます。</p><h3>パイプラインの定義</h3><p>Dataflowは行いたい処理を数珠つなぎに繋げていって、それらをパイプラインで処理することができます。今回は上記のInception-v3モデルを使って、GCS上にある画像の特徴量を出力するパイプラインを構築してみましょう。次の図のようなパイプラインです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*IMn8NatHpJscVfi82nEkyw.png" /></figure><p>それぞれ順番に解説すると、</p><ol><li>画像ファイルがあるGCSのパスを入力（固定）</li><li>パス内のファイル一覧を取得</li><li>画像をロード（＆リサイズ）</li><li>特徴量抽出（<strong>TF Hubを使っているところ</strong>）</li><li>GCSに書き込み</li></ol><p>という感じです。Dataflowでこれらのパイプラインを定義するには、次のようになります。</p><pre>p = beam.Pipeline(options=options)<br>(p | ‘gcs_path’ &gt;&gt; beam.Create([‘gs://[BUCKET]’])<br>   | ‘get file names’ &gt;&gt; beam.FlatMap(get_file_names)<br>   | ‘load image’ &gt;&gt; beam.Map(load_image)<br>   | ‘extract features’ &gt;&gt; beam.Map(extract_features)<br>   | ‘write’ &gt;&gt; beam.io.WriteToText(‘gs://[/BUCKET]/hub.txt’,<br>                                   num_shards=1)<br>)</pre><p>Dataflow(Python)では、パイプラインの処理を繋げるにはパイプ「 | 」で繋げるということをします。通常のPythonコードとは感覚が違いますが、こういうものだと思いましょう。</p><p>beam.Map() は、1つの入力に対して1つの出力をします。beam.FlatMap()は、1つの入力に対して複数の出力をします。ここでは、GCSからファイル名を取得している処理をFlatMapにし、それ以外はMapで１画像を１処理単位としています。</p><p>beam.Map()とbeam.FlatMap()の引数は、それぞれ具体的にその中で行なっている処理の関数です。次のように定義します。</p><pre># ファイル名取得<br>def get_file_names(gcs_path):<br>  import tensorflow as tf<br> <br>  for fn in tf.gfile.ListDirectory(gcs_path):<br>    yield gcs_path + ‘/’ + fn</pre><pre># 画像をGCSからロード<br>def load_image(fn):<br>  import tensorflow as tf<br>  import numpy as np<br>  from PIL import Image<br> <br>  f = tf.gfile.Open(fn)<br>  im = Image.open(f)<br>  im = im.resize((299, 299))<br> <br>  return np.array(im).reshape((1, 299, 299, 3))</pre><pre># Hubで読み込んだInception-v3で特徴量抽出<br>def extract_features(elem):<br>  import tensorflow as tf<br>  import tensorflow_hub as hub<br> <br>  with tf.Graph().as_default():<br>    module = hub.Module(“<a href="https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1">https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1</a>&quot;)<br>    features = module(elem)<br>  with tf.Session() as sess:<br>    sess.run(tf.global_variables_initializer())<br>    return sess.run(features)</pre><p>それぞれ、数行のコードで済んでしまうのがDataflowのすごいところですね！ちなみにDataflowの処理関数（Transform）上からGCSへアクセスする方法はいくつかありますが、tf.gfileを使うと簡単です。</p><h3>Takeaways..</h3><p>Dataflowは冒頭で記載したように、ワークロードに合わせて自動でスケールしてくれます。ただし、上記のサンプルコードはちょっと非効率な部分が含まれています。</p><p><strong>ライブラリのロード</strong><br>各関数内でライブラリをインポートしているのに気が付いたかもしれません。Dataflowでは、複数のワーカーで並列処理を行うため、どの処理をどのワーカーが実行しているのかわかりません。なので、関数内で使うライブラリは、関数内でインポートしないといけないのです。でもこれって結構オーバーヘッドにならないでしょうか？</p><p>解決方法の1つは、よく使うライブラリ（とTF Hubでロードしたモデル）はSingletonで定義してしまうことです。そうすれば、少なくとも１要素の処理単位でロードされてしまうことは防げます。他にも、いろんな方法があるので、みなさんも是非Dataflowを利用し、情報をシェアしてくださいね！</p><blockquote><em>Disclaimer この記事は個人的なものです｡ここで述べられていることは私の個人的な意見に基づくものであり､私の雇用者には関係はありません｡</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70786ff1b7ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud-jp/tensorflow-hub-dataflow-70786ff1b7ae">TensorFlow Hub を Cloud Dataflowで使ってみた</a> was originally published in <a href="https://medium.com/google-cloud-jp">google-cloud-jp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Transfer Learning with Cloud ML Engine and Keras]]></title>
            <link>https://medium.com/google-cloud/serverless-transfer-learning-with-cloud-ml-engine-and-keras-335435f31e15?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/335435f31e15</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[cloud-ml-engine]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Mon, 02 Oct 2017 14:19:33 GMT</pubDate>
            <atom:updated>2017-10-02T14:19:33.397Z</atom:updated>
            <content:encoded><![CDATA[<p>Image classification using deep learning is widely known today, but you hear only small numbers of successful news for image classification. The reason why, I suppose because it needs enormous data and time consuming to achieve good results.</p><p><strong>Transfer Learning </strong>solves such a problem in a sophisticated way. <br>Transfer learning is a technique that uses pre-trained network and change little bit at the end of the network, so you re-train only the part changed. This network still have ability to extract features of images and can be fine tuned for dedicated image classification, also need less time and fewer datasets to re-train. However, there are still many troublesome aspects of training and operation, so here this article show you how to use transfer learning easily on <a href="https://cloud.google.com/ml-engine/">Cloud ML Engine</a> .</p><p><strong>TL;DR.</strong> Read my <a href="https://github.com/hayatoy/cloudml-magic/blob/master/examples/Keras_Fine_Tuning.ipynb">notebook</a> :)</p><h3>Transfer Learning using Keras</h3><p><a href="https://keras.io/">Keras</a> is the easiest way to construct transfer learning model. As mentioned above, transfer learning model uses pre-trained network, and Keras has already some great <a href="https://keras.io/applications/">pre-trained models</a>.</p><p><strong>Inception-v3 in Keras<br></strong>It is quite easy to use a pre-trained model in Keras, only two lines as follows.</p><pre><strong>from</strong> keras.applications.inception_v3 <strong>import</strong> InceptionV3<br>model <strong>=</strong> InceptionV3(weights<strong>=</strong>’imagenet’)</pre><p>This model was pre-trained with ImageNet’s datasets, which has one million images and 1000 classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCXqy5c-MwRzJlo7rYPyRQ.png" /><figcaption>Inception-v3 diagram via Google Research Blog</figcaption></figure><p>Let’s classify following two images with this model. Since Inception-v3 model accepts RGB 299x299 image as input, you must convert your image before classify it. Keras has also helpful modules to do this.</p><pre><strong>from</strong> keras.preprocessing <strong>import</strong> image<br><strong>from</strong> keras.applications.inception_v3 <strong>import</strong> preprocess_input, decode_predictions<br><strong>import</strong> numpy <strong>as</strong> np<br><br><em># Make input data from Jpeg file</em><br>img_path <strong>=</strong> &#39;seagull.jpg&#39;<br>img <strong>=</strong> image<strong>.</strong>load_img(img_path, target_size<strong>=</strong>(299, 299))<br>x <strong>=</strong> image<strong>.</strong>img_to_array(img)<br>x <strong>=</strong> np<strong>.</strong>expand_dims(x, axis<strong>=</strong>0)<br>x <strong>=</strong> preprocess_input(x)<br><br><em># Classify image</em><br>preds <strong>=</strong> model<strong>.</strong>predict(x)<br><br><em># Print predicted classes</em><br><strong>print</strong>(&#39;Predicted:&#39;)<br><strong>for</strong> p <strong>in</strong> decode_predictions(preds, top<strong>=</strong>5)[0]:<br>    <strong>print</strong>(&quot;Score {}, Label {}&quot;<strong>.</strong>format(p[2], p[1]))</pre><p>Images to classify and results;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*GnRMG7gylnjEbwmd3w-grg.jpeg" /></figure><pre>Predicted:<br><strong>Score 0.965535342693, Label Indian_elephant</strong><br>Score 0.0246694963425, Label tusker<br>Score 0.000626200810075, Label African_elephant<br>Score 0.000182053816388, Label Mexican_hairless<br>Score 0.000138055766001, Label hippopotamus</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*hJK2YZwlmu-HbEDSJuWVmw.jpeg" /></figure><pre>Predicted:<br><strong>Score 0.278156191111, Label albatross</strong><br>Score 0.0422638729215, Label drake<br>Score 0.0255650430918, Label goose<br>Score 0.0211290325969, Label red-breasted_merganser<br>Score 0.019902639091, Label lakeside</pre><p>The model classified elephants correctly, but failed to classify a seagull. The reason is simply because <a href="http://image-net.org/challenges/LSVRC/2012/browse-synsets">datasets</a> for training the model doesn’t include “gull”, so that it classified similar candidates instead. You never get results out of the list, and that’s why transfer learning is needed.</p><p><strong>Visualize intermediate layer outputs</strong><br>Before going to transfer learning, let’s visualize intermediate layer outputs. To show list of layers, run the code below.</p><pre><strong>import</strong> pandas <strong>as</strong> pd<br>pd<strong>.</strong>DataFrame(model<strong>.</strong>layers)<strong>.</strong>tail()</pre><p>The output is as follows.</p><pre>308  &lt;keras.layers.merge.Concatenate object at 0x7f...<br>309  &lt;keras.layers.core.Activation object at 0x7fb7...<br>310  &lt;keras.layers.merge.Concatenate object at 0x7f...<br>311  &lt;keras.layers.pooling.GlobalAveragePooling2D o...<br>312  &lt;keras.layers.core.Dense object at 0x7fb7a1a5b...</pre><p>We want to visualize outputs of layer 311, GlobalAveragePooling2D, so let’s construct a model to output the intermediate layer outputs.</p><pre><strong>from</strong> keras.models <strong>import</strong> Model<br><br><em># The model which outputs intermediate layer features</em><br>intermediate_layer_model <strong>=</strong> Model(inputs<strong>=</strong>model<strong>.</strong>input, <br>                                 outputs<strong>=</strong>model<strong>.</strong>layers[311]<strong>.</strong>output)</pre><p>To extract features and visualize, run the following code.</p><pre>features <strong>=</strong> intermediate_layer_model<strong>.</strong>predict(x)<br>pd<strong>.</strong>DataFrame(features<strong>.</strong>reshape(<strong>-</strong>1,1))<strong>.</strong>plot(figsize<strong>=</strong>(12, 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*X9KVZRl8wT5iAcXtEuDLuw.png" /></figure><p>The outputs of GlobalAveragePooling2D are 2048 dimensions features. Inception-v3 model classifies 1000 classes by using Dense layer at the end of the network, which uses these features as input. But now, we would like to classify “other” classes. So let’s remove this layer and put another one.</p><p><strong>Add Dense layers for fine tuning</strong><br>Let’s add dense layers, if we want to classify two-classes, the code would be something like this.</p><pre><strong>from</strong> keras.layers <strong>import</strong> Dense<br><br><em># Connect Dense layers at the end</em><br>x <strong>=</strong> intermediate_layer_model<strong>.</strong>output<br>x <strong>=</strong> Dense(1024, activation<strong>=</strong>&#39;relu&#39;)(x)<br>predictions <strong>=</strong> Dense(2, activation<strong>=</strong>&#39;softmax&#39;)(x)<br><br><em># Transfer Learning model</em><br>transfer_model <strong>=</strong> Model(inputs<strong>=</strong>intermediate_layer_model<strong>.</strong>input, outputs<strong>=</strong>predictions)</pre><p>At this moment, the model trains all its variables. But we want to train only the dense layers we added, so let’s freeze untrained layers.</p><pre><em># Freeze all layers</em><br><strong>for</strong> layer <strong>in</strong> transfer_model<strong>.</strong>layers:<br>    layer<strong>.</strong>trainable <strong>=</strong> False<br><br><em># Unfreeze last dense layers</em><br>transfer_model<strong>.</strong>layers[312]<strong>.</strong>trainable <strong>=</strong> True<br>transfer_model<strong>.</strong>layers[313]<strong>.</strong>trainable <strong>=</strong> True<br><br>transfer_model<strong>.</strong>compile(loss<strong>=</strong>&#39;categorical_crossentropy&#39;,<br>                       optimizer<strong>=</strong>&#39;adam&#39;,<br>                       metrics<strong>=</strong>[&#39;accuracy&#39;])</pre><p>Done! Now we can fine-tune this model for dedicated two-classes classification.</p><p>Fine tuning for two-classes classification<br>Let’s classify the images below. the datasets is named <strong>Opera-Capitol</strong> datasets that I made, which includes Opera house and Capitol 100 images for each. You can download the code to make this datasets.<br><a href="https://github.com/hayatoy/deep-learning-datasets">https://github.com/hayatoy/deep-learning-datasets</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*iHxe57geQ_CkXsdYnu-ZWw.png" /></figure><p><strong>Load dataset</strong><br>The dataset is compressed as NumPy format and stored in GitHub, you can use it as follows.</p><pre><strong>import</strong> requests<br><br>url <strong>=</strong> &#39;https://github.com/hayatoy/deep-learning-datasets/releases/download/v0.1/tl_opera_capitol.npz&#39;<br>response <strong>=</strong> requests<strong>.</strong>get(url)<br>dataset <strong>=</strong> np<strong>.</strong>load(BytesIO(response<strong>.</strong>content))<br><br>X_dataset <strong>=</strong> dataset[&#39;features&#39;]<br>y_dataset <strong>=</strong> dataset[&#39;labels&#39;]</pre><p>Let’s split the dataset into for train and for test, here I split it 80% for train and 20% for test.</p><pre><strong>from</strong> keras.utils <strong>import</strong> np_utils<br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br><br>X_dataset <strong>=</strong> preprocess_input(X_dataset)<br>y_dataset <strong>=</strong> np_utils<strong>.</strong>to_categorical(y_dataset)<br>X_train, X_test, y_train, y_test <strong>=</strong> train_test_split(<br>    X_dataset, y_dataset, test_size<strong>=</strong>0.2, random_state<strong>=</strong>42)</pre><p>By the way, what would be the result if normal Inception-v3 model classifies the dataset? Let’s see how it goes.</p><pre>x <strong>=</strong> X_dataset[0]<br>x <strong>=</strong> np<strong>.</strong>expand_dims(x, axis<strong>=</strong>0)<br><br>preds <strong>=</strong> model<strong>.</strong>predict(x)<br><strong>print</strong>(&#39;Predicted:&#39;)<br><strong>for</strong> p <strong>in</strong> decode_predictions(preds, top<strong>=</strong>5)[0]:<br>    <strong>print</strong>(&quot;Score {}, Label {}&quot;<strong>.</strong>format(p[2], p[1]))</pre><p>The first image of the dataset is Opera house. and here is the result.. wreck. Again, because original ImageNet dataset doesn’t include Opera house.</p><pre>Predicted:<br><strong>Score 0.110657587647, Label wreck</strong><br>Score 0.0671983659267, Label lakeside<br>Score 0.0309968702495, Label seashore<br>Score 0.0249739717692, Label breakwater<br>Score 0.0229569561779, Label fountain</pre><p><strong>Fine tuning the model for Opera-Capitol</strong><br>To train the transfer learning model, just call fit<strong> </strong>function. After that, let’s evaluate the model how it predict correctly.</p><pre>transfer_model<strong>.</strong>fit(X_train, y_train, epochs<strong>=</strong>20,<br>                   validation_data<strong>=</strong>(X_test, y_test))<br>loss, acc <strong>=</strong> transfer_model<strong>.</strong>evaluate(X_test, y_test)<br><strong>print</strong>(&#39;Loss {}, Accuracy {}&#39;<strong>.</strong>format(loss, acc))</pre><p>The evaluation result for test data is..</p><pre>Loss 0.112133163214, Accuracy 0.975</pre><p>Accuracy reached 97.5%!</p><h3>Training the model on Cloud ML Engine</h3><p>The transfer learning model takes approx. ten to twenty minutes for training on local machine without GPU, if you run on Cloud ML Engine.. only a minute. (plus a few minutes for staging)</p><p><strong>Making package</strong><br>To train your model on Cloud ML Engine, you must make a package of your code first. In this example we use <strong>keras</strong>, <strong>h5py</strong>, and <strong>Pillow</strong> as external libraries, so you must include these libraries in your setup.py.</p><pre><strong>from</strong> setuptools <strong>import</strong> setup<br><strong>if</strong> __name__ <strong>==</strong> &#39;__main__&#39;:<br>    setup(name<strong>=</strong>&#39;trainer&#39;,<br>          packages<strong>=</strong>[&#39;trainer&#39;],<br>          install_requires<strong>=</strong>[&#39;keras&#39;,&#39;h5py&#39;,&#39;Pillow&#39;])</pre><p><strong>Cloud ML Engine from Jupyter Notebook</strong><br>Packaging, uploading to Google Cloud Storage, running ML Engine job are really tiring. Don’t you want to just run your Jupyter Notebook code on ML Engine? I made an extension to do that!<br><a href="https://github.com/hayatoy/cloudml-magic">https://github.com/hayatoy/cloudml-magic</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Gnjo5yH0xRRLSOcley3B3g.png" /></figure><h3>Online Prediction on Cloud ML Engine</h3><p>Now you want to serve your trained model, how to do that? Implement HTTP server, setup TensorFlow or Keras on the server, and Load balancing etc etc.. That’s touch work. On Cloud ML Engine, only things you need to do is to upload your model to GCS (Google Cloud Storage). It serves your model, accept prediction requests by REST API, and of course auto scaling.</p><p><strong>Build a graph that converts image</strong><br>Since Keras model accepts only raw image array as input, we should convert Jpeg or Png format to raw image array, otherwise the REST API requests’ payload would be too big.</p><pre><strong>with</strong> tf<strong>.</strong>Graph()<strong>.</strong>as_default() <strong>as</strong> g_input:<br>    input_b64 <strong>=</strong> tf<strong>.</strong>placeholder(shape<strong>=</strong>(1,),<br>                               dtype<strong>=</strong>tf<strong>.</strong>string,<br>                               name<strong>=</strong>&#39;input&#39;)<br>    input_bytes <strong>=</strong> tf<strong>.</strong>decode_base64(input_b64[0])<br>    image <strong>=</strong> tf<strong>.</strong>image<strong>.</strong>decode_image(input_bytes)<br>    image_f <strong>=</strong> tf<strong>.</strong>image<strong>.</strong>convert_image_dtype(image, dtype<strong>=</strong>tf<strong>.</strong>float32)<br>    input_image <strong>=</strong> tf<strong>.</strong>expand_dims(image_f, 0)<br>    output <strong>=</strong> tf<strong>.</strong>identity(input_image, name<strong>=</strong>&#39;input_image&#39;)<br><br><em># Convert to GraphDef</em><br>g_input_def <strong>=</strong> g_input<strong>.</strong>as_graph_def()</pre><p>Next we convert the Keras model to tf.GraphDef, so that we can connect the above graph.</p><pre>sess <strong>=</strong> K<strong>.</strong>get_session()<br><br><strong>from</strong> tensorflow.python.framework <strong>import</strong> graph_util<br><br><em># Make GraphDef of Transfer Model</em><br>g_trans <strong>=</strong> sess<strong>.</strong>graph<br>g_trans_def <strong>=</strong> graph_util<strong>.</strong>convert_variables_to_constants(sess, <br>                      g_trans<strong>.</strong>as_graph_def(),<br>                      [transfer_model<strong>.</strong>output<strong>.</strong>name<strong>.</strong>replace(&#39;:0&#39;,&#39;&#39;)])</pre><p>Here is the combined graph, it accepts base64 encoded Jpeg or Png file, then outputs classified result from transfer learning model.</p><pre><strong>with</strong> tf<strong>.</strong>Graph()<strong>.</strong>as_default() <strong>as</strong> g_combined:<br>    x <strong>=</strong> tf<strong>.</strong>placeholder(tf<strong>.</strong>string, name<strong>=</strong>&quot;input_b64&quot;)<br><br>    im, <strong>=</strong> tf<strong>.</strong>import_graph_def(g_input_def,<br>                              input_map<strong>=</strong>{&#39;input:0&#39;: x},<br>                              return_elements<strong>=</strong>[&quot;input_image:0&quot;])<br><br>    pred, <strong>=</strong> tf<strong>.</strong>import_graph_def(g_trans_def,<br>             input_map<strong>=</strong>{transfer_model<strong>.</strong>input<strong>.</strong>name: im,<br>             &#39;batch_normalization_1/keras_learning_phase:0&#39;: False},<br>             return_elements<strong>=</strong>[transfer_model<strong>.</strong>output<strong>.</strong>name])</pre><p>Before uploading the model to GCS, we must convert the model to SavedModel format. The following code converts the graph to SavedModel format, and save it to GCS directly.</p><pre><strong>with</strong> tf<strong>.</strong>Session() <strong>as</strong> sess2:<br>  inputs <strong>=</strong> {&quot;inputs&quot;: tf<strong>.</strong>saved_model<strong>.</strong>utils<strong>.</strong>build_tensor_info(x)}<br>  outputs <strong>=</strong> {&quot;outputs&quot;:tf<strong>.</strong>saved_model<strong>.</strong>utils<strong>.</strong>build_tensor_info(pred)}<br>  signature <strong>=</strong>tf<strong>.</strong>saved_model<strong>.</strong>signature_def_utils<strong>.</strong>build_signature_def(<br>            inputs<strong>=</strong>inputs,<br>            outputs<strong>=</strong>outputs,<br>  method_name<strong>=</strong>tf<strong>.</strong>saved_model<strong>.</strong>signature_constants<strong>.</strong>PREDICT_METHOD_NAME<br>        )<br><br>  <em># save as SavedModel</em><br>  b <strong>=</strong> tf<strong>.</strong>saved_model<strong>.</strong>builder<strong>.</strong>SavedModelBuilder(&#39;gs://{BUCKET}/mdl&#39;)<br>  b<strong>.</strong>add_meta_graph_and_variables(sess2,<br>                  [tf<strong>.</strong>saved_model<strong>.</strong>tag_constants<strong>.</strong>SERVING],<br>                  signature_def_map<strong>=</strong>{&#39;serving_default&#39;: signature})<br>  b<strong>.</strong>save()</pre><p>Let’s register the model to ML Engine. Just type the following two commands. It may take a few minutes.. so have a cuppa and it will be done.</p><pre>gcloud ml-engine models create OperaCapitol<br>gcloud ml-engine versions create v1 \<br>          --model OperaCapitol \<br>          --runtime-version 1.2 \<br>          --origin gs://<strong>{</strong>BUCKET<strong>}</strong>/mdl</pre><h3>Classify an image by Online Prediction</h3><p>To classify an image by Online Prediction, just call its REST API. If you are requesting in Python environment, using discovery api library is much easier. Here is how to initialize discovery api for Online Prediction.</p><pre><strong>from</strong> oauth2client.client <strong>import</strong> GoogleCredentials<br><strong>from</strong> googleapiclient <strong>import</strong> discovery<br><strong>from</strong> googleapiclient <strong>import</strong> errors<br><br>PROJECTID <strong>=</strong> &#39;PROJECTID&#39;<br>projectID <strong>=</strong> &#39;projects/{}&#39;<strong>.</strong>format(PROJECTID)<br>modelName <strong>=</strong> &#39;OperaCapitol&#39;<br>modelID <strong>=</strong> &#39;{}/models/{}&#39;<strong>.</strong>format(projectID, modelName)<br><br>credentials <strong>=</strong> GoogleCredentials<strong>.</strong>get_application_default()<br>ml <strong>=</strong> discovery<strong>.</strong>build(&#39;ml&#39;, &#39;v1&#39;, credentials<strong>=</strong>credentials)</pre><p>Let’s classify an image. The converter graph doesn’t have any resizing function, you must resize the image to 299x299 by yourselves. Also don’t forget to encode the image to base64.</p><pre><strong>with</strong> open(&#39;opera.jpg&#39;, &#39;rb&#39;) <strong>as</strong> f:<br>    b64_x <strong>=</strong> f<strong>.</strong>read()<br><strong>import</strong> base64<br><strong>import</strong> json<br><br>b64_x <strong>=</strong> base64<strong>.</strong>urlsafe_b64encode(b64_x)<br>input_instance <strong>=</strong> dict(inputs<strong>=</strong>b64_x)<br>input_instance <strong>=</strong> json<strong>.</strong>loads(json<strong>.</strong>dumps(input_instance))<br>request_body <strong>=</strong> {&quot;instances&quot;: [input_instance]}<br><br>request <strong>=</strong> ml<strong>.</strong>projects()<strong>.</strong>predict(name<strong>=</strong>modelID, body<strong>=</strong>request_body)<br><strong>try</strong>:<br>    response <strong>=</strong> request<strong>.</strong>execute()<br><strong>except</strong> errors<strong>.</strong>HttpError <strong>as</strong> err:<br>    <strong>print</strong>(err<strong>.</strong>_get_reason())<br>response</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*OvN0EAWdOtmAZXMWjntTzw.jpeg" /></figure><p>Here is the response from Online Prediction. The list of “outputs” represents confidence of Opera House and Capitol respectively.<br>99.7% for Opera House, that’s correct!</p><pre>{u&#39;predictions&#39;: [<br>    {u&#39;outputs&#39;: [0.9974665641784668, 0.00253341649658978]}<br>]}</pre><p>You can find the code of this article here;<br><a href="https://github.com/hayatoy/cloudml-magic">https://github.com/hayatoy/cloudml-magic</a></p><p>Enjoy Cloud ML Engine!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=335435f31e15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/serverless-transfer-learning-with-cloud-ml-engine-and-keras-335435f31e15">Serverless Transfer Learning with Cloud ML Engine and Keras</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training Multiple Models of TensorFlow using Dataflow]]></title>
            <link>https://medium.com/@hayatoy/training-multiple-models-of-tensorflow-using-dataflow-7a5a9efafe53?source=rss-a6d93b5c4325------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a5a9efafe53</guid>
            <category><![CDATA[google-cloud-dataflow]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hayato Yoshikawa]]></dc:creator>
            <pubDate>Tue, 07 Mar 2017 14:17:17 GMT</pubDate>
            <atom:updated>2017-03-07T14:17:17.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WPfL2Gf9kGQWafm1qcq5w.jpeg" /><figcaption><a href="https://unsplash.com/collections/582860/devices?photo=6g0KJWnBhxg">https://unsplash.com/collections/582860/devices?photo=6g0KJWnBhxg</a></figcaption></figure><p>Deep learning is one of the most trending words these days, and thanks to great machine learning libraries like <strong>TensorFlow</strong>, we can access this scientific world without deep knowledge.</p><p>Once you choose a basic model to train your dataset, you would want to change its parameters, or want to try other models don’t you? Then you would notice how much coffee you need while waiting for the training finishes.</p><p>Meanwhile <strong>Google Cloud Dataflow </strong>can compute many things in parallel, and yet <strong>fully</strong> <strong>managed</strong>. Which means, don’t need to struggle with parallel coding and resource management. Why not to use it for reducing training time?</p><h4>Option Settings</h4><p>It’s easy to manipulate <strong>Dataflow</strong> from <strong>Jupyter Notebook</strong> running on your local machine. Here’s the settings that should be written in the first cell. Replace <em>PROJECTID</em> and <em>BUCKET_NAME</em> as you desire.</p><pre><strong>import</strong> apache_beam <strong>as</strong> beam<br><strong>import</strong> apache_beam.transforms.window <strong>as</strong> window<br><br>options <strong>=</strong> beam<strong>.</strong>utils<strong>.</strong>pipeline_options<strong>.</strong>PipelineOptions()<br><br>google_cloud_options <strong>=</strong> options<strong>.</strong>view_as(beam<strong>.</strong>utils<strong>.</strong>pipeline_options<strong>.</strong>GoogleCloudOptions)<br>google_cloud_options<strong>.</strong>project <strong>=</strong> &#39;{PROJECTID}&#39;<br>google_cloud_options<strong>.</strong>job_name <strong>=</strong> &#39;tensorflow-gs&#39;<br>google_cloud_options<strong>.</strong>staging_location <strong>=</strong> &#39;gs://{BUCKET_NAME}/binaries&#39;<br>google_cloud_options<strong>.</strong>temp_location <strong>=</strong> &#39;gs://{BUCKET_NAME}/temp&#39;<br><br>worker_options <strong>=</strong> options<strong>.</strong>view_as(beam<strong>.</strong>utils<strong>.</strong>pipeline_options<strong>.</strong>WorkerOptions)<br>worker_options<strong>.</strong>max_num_workers <strong>=</strong> 6<br>worker_options<strong>.</strong>num_workers <strong>=</strong> 6<br>worker_options<strong>.</strong>disk_size_gb <strong>=</strong> 20<br><em># worker_options.machine_type = &#39;n1-standard-16&#39;</em><br><br><em># options.view_as(beam.utils.pipeline_options.StandardOptions).runner = &#39;DirectRunner&#39;</em><br>options<strong>.</strong>view_as(beam<strong>.</strong>utils<strong>.</strong>pipeline_options<strong>.</strong>StandardOptions)<strong>.</strong>runner <strong>=</strong> &#39;DataflowRunner&#39;<br><br>p <strong>=</strong> beam<strong>.</strong>Pipeline(options<strong>=</strong>options)</pre><h4>Making grid parameters</h4><p>Having trouble writing enormous parameter combinations? Here is a code to reduce your time. We only need to define ranges for each parameters, then this code generates all distinct combinations.</p><pre><strong>import</strong> itertools<br><br>param_grid <strong>=</strong> {&#39;hidden_units&#39;: [[10, 20, 10],<br>                               [20, 40, 20],<br>                               [100, 200, 100]],<br>              &#39;dropout&#39;: [0.1, 0.2, 0.5, 0.8],<br>              &#39;steps&#39;: [20000, 50000, 100000]}<br><br><strong>def</strong> <strong>dict_product</strong>(param):<br>    <strong>return</strong> (dict(itertools<strong>.</strong>izip(param, x)) <strong>for</strong> x <strong>in</strong> itertools<strong>.</strong>product(<strong>*</strong>param<strong>.</strong>itervalues()))<br><br>params <strong>=</strong> list(dict_product(param_grid))</pre><p>As a result of above code, we get following combination parameters.</p><pre>[{&#39;dropout&#39;: 0.1, &#39;hidden_units&#39;: [10, 20, 10], &#39;steps&#39;: 20000},<br> {&#39;dropout&#39;: 0.1, &#39;hidden_units&#39;: [20, 40, 20], &#39;steps&#39;: 20000},<br> {&#39;dropout&#39;: 0.1, &#39;hidden_units&#39;: [100, 200, 100], &#39;steps&#39;: 20000},<br> {&#39;dropout&#39;: 0.2, &#39;hidden_units&#39;: [10, 20, 10], &#39;steps&#39;: 20000},<br> {&#39;dropout&#39;: 0.2, &#39;hidden_units&#39;: [20, 40, 20], &#39;steps&#39;: 20000},<br><em># ... </em><br> {&#39;dropout&#39;: 0.5, &#39;hidden_units&#39;: [20, 40, 20], &#39;steps&#39;: 100000},<br> {&#39;dropout&#39;: 0.5, &#39;hidden_units&#39;: [100, 200, 100], &#39;steps&#39;: 100000},<br> {&#39;dropout&#39;: 0.8, &#39;hidden_units&#39;: [10, 20, 10], &#39;steps&#39;: 100000},<br> {&#39;dropout&#39;: 0.8, &#39;hidden_units&#39;: [20, 40, 20], &#39;steps&#39;: 100000},<br> {&#39;dropout&#39;: 0.8, &#39;hidden_units&#39;: [100, 200, 100], &#39;steps&#39;: 100000}]</pre><p>Note: this combination includes useless patterns. for ex., dropout should only be set in high step number.</p><h4>Training each models</h4><p>This function is called for each sets of parameters. We made 36 combinations in this time, thus called 36 times in parallel. Trained models are saved in Google Cloud Storage as written in <em>model_dir. </em>Here we set unique model_id for each models, so that you can find them later in BigQuery entry.</p><pre><strong>def</strong> <strong>train</strong>(param):<br>    <strong>import</strong> uuid<br>    <strong>import</strong> json<br>    <strong>import</strong> tensorflow <strong>as</strong> tf<br>    <strong>from</strong> sklearn <strong>import</strong> cross_validation<br><br>    model_id <strong>=</strong> str(uuid<strong>.</strong>uuid4())<br><br>    <em># Load &#39;Iris&#39; dataset</em><br>    iris <strong>=</strong> tf<strong>.</strong>contrib<strong>.</strong>learn<strong>.</strong>datasets<strong>.</strong>base<strong>.</strong>load_iris()<br>    train_x, test_x, train_y, test_y <strong>=</strong> cross_validation<strong>.</strong>train_test_split(<br>        iris<strong>.</strong>data, iris<strong>.</strong>target, test_size<strong>=</strong>0.2, random_state<strong>=</strong>0<br>    )<br><br>    <em># https://www.tensorflow.org/get_started/tflearn</em><br>    feature_columns <strong>=</strong> [tf<strong>.</strong>contrib<strong>.</strong>layers<strong>.</strong>real_valued_column(&quot;&quot;, dimension<strong>=</strong>4)]<br>    classifier <strong>=</strong> tf<strong>.</strong>contrib<strong>.</strong>learn<strong>.</strong>DNNClassifier(feature_columns<strong>=</strong>feature_columns,<br>                                                hidden_units<strong>=</strong>param[&#39;hidden_units&#39;],<br>                                                dropout<strong>=</strong>param[&#39;dropout&#39;],<br>                                                n_classes<strong>=</strong>3,<br>                                                model_dir<strong>=</strong>&#39;gs://{BUCKET_NAME}/models/%s&#39;<strong>%</strong> model_id)<br>    classifier<strong>.</strong>fit(x<strong>=</strong>train_x,<br>                   y<strong>=</strong>train_y,<br>                   steps<strong>=</strong>param[&#39;steps&#39;],<br>                   batch_size<strong>=</strong>50)<br>    result <strong>=</strong> classifier<strong>.</strong>evaluate(x<strong>=</strong>test_x, y<strong>=</strong>test_y)<br><br>    ret <strong>=</strong> {&#39;accuracy&#39;: float(result[&#39;accuracy&#39;]),<br>           &#39;loss&#39;: float(result[&#39;loss&#39;]),<br>           &#39;model_id&#39;: model_id,<br>           &#39;param&#39;: json<strong>.</strong>dumps(param)}<br><br>    <strong>return</strong> ret</pre><h4>Running a pipeline</h4><p>Now we want to run a pipeline, with three simple operations. First operation is in-memory data generation, which here we defined as grid parameters. Second one is the training. Third one is to save training output into BigQuery. Very simple isn’t it?</p><pre>(p <strong>|</strong> &#39;init&#39; <strong>&gt;&gt;</strong> beam<strong>.</strong>Create(params)<br>   <strong>|</strong> &#39;train&#39; <strong>&gt;&gt;</strong> beam<strong>.</strong>Map(train)<br>   <strong>|</strong> &#39;output&#39; <strong>&gt;&gt;</strong> beam<strong>.</strong>Write(beam<strong>.</strong>io<strong>.</strong>BigQuerySink(<br>       &#39;project:dataset.table&#39;,<br>       schema<strong>=</strong>&quot;accuracy:FLOAT, loss:FLOAT,<br>               model_id:STRING, param:STRING&quot;,<br>       write_disposition<strong>=</strong>beam<strong>.</strong>io<strong>.</strong>BigQueryDisposition<strong>.</strong>WRITE_APPEND,<br>   create_disposition<strong>=</strong>beam<strong>.</strong>io<strong>.</strong>BigQueryDisposition<strong>.</strong>CREATE_IF_NEEDED))<br>)<br><br>p<strong>.</strong>run()</pre><h4>Monitoring jobs</h4><p>We can monitor jobs on Cloud Console. In this example it took 20 minutes by 6 workers. and 10 minutes by 18 workers. <em>(It takes approx. 5 minutes for staging and so on.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MlYjoZ8WLypMj13BAyLdQ.png" /></figure><h4>Saving results into BigQuery</h4><p>The pipeline saves training results into BigQuery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rWQ3CS6Zw7Weda01LGxxg.png" /></figure><h4>How to use tensorboard for saved models?</h4><p>Now we want to look into details of trained models. Go to Cloud Console, launch Cloud Shell and type the command below.</p><pre>tensorboard --logdir=gs://{BUCKET_NAME}/models/{model_id} --port=8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eo_Jf97BMdUfbgJG-qsv7A.png" /></figure><p>Here is the whole code, Happy coding!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83df408bc8464a2d7efba213d16ac38c/href">https://medium.com/media/83df408bc8464a2d7efba213d16ac38c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a5a9efafe53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>