iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
Google Developers Machine Learning

Google machine learning 學習筆記系列 第 14

【Day 14】 Google ML - Lab 3 - Machine Learning APIs - (API實作篇) google圖片辨識, 語音辨識, 語言翻譯, 自然語言辨識(NL)

前言

我們來做 How Google does Machine Learning 的第二個lab~

這次鐵人賽的30天中,我目前所寫文章的所有課程目錄如下:

Course - How Google does Machine Learning

第五章節的課程地圖:(紅字標記為本篇文章中會介紹到的章節)

  • Python notebooks in the cloud
    • Module Introduction
    • Cloud Datalab
      • Cloud Datalab
      • Demo: Cloud Datalab
      • Development process
      • Demo of rehosting Cloud Datalab
    • Working with managed services
    • Computation and storage
    • Lab: Rent-a-VM
      • Intro to Qwiklabs
      • Intro to Renting-VM Lab
      • Lab: Rent-a-VM to process earthquake data
      • Lab debrief
    • Cloud Shell
    • Third wave of cloud
      • Third Wave of Cloud: Fully-Managed Services
      • Third Wave of Cloud: Serverless Data Analysis
      • Third Wave of Cloud: BigQuery and Cloud Datalab
    • Datalab and BigQuery
      • Lab Intro: Analyzing data using Datalab and BigQuery
      • Lab: Analyzing data using Datalab and BigQuery
      • Lab Debrief: Analyzing Data using Datalab and BigQuery
    • Machine Learning with Sara Robinson
      • ML, not rules
    • Pre-trained ML APIs
      • Vision API in action
      • Video intelligence API
      • Cloud Speech API
      • Translation and NL
    • Lab: Machine Learning APIs
      • Lab: Pretrained ML APIs Intro
      • Lab: Invoking Machine Learning APIs
      • Lab Solution

Lab: Machine Learning APIs

課程地圖

  • Python notebooks in the cloud
    • Lab: Machine Learning APIs
      • Lab: Pretrained ML APIs Intro
      • Lab: Invoking Machine Learning APIs
      • Lab Solution

在這個lab中,我們將實作之前 【Day 12】- google圖片辨識(Vision), 影片辨識(Video), 語音辨識, 語言翻譯, 自然語言辨識(NL) API功能總整理 的API應用

我們會示範如何進行API串接,讓我們能直接使用google已訓練好的ML API來直接實現功能。


part 0 : (事前準備) 開啟 GCP console


part 1 : (建立機器) 建立並執行 Cloud Datalab VM

Step 0 : 打開 Cloud Shell

Step 1 : 首先我們要先知道我們的 compute zones 在哪,我們可以透過以下指令知道我們所有的 compute zones 位置,我們會在其中一個 compute zones 運行我們的 Datalab。

gcloud compute zones list

註:影片中的範例使用的是 U.S. Central。

Step 2 : 我們透過以下指令創建我們的 datalab VM。

datalab create mydatalabvm --zone <ZONE>
  • <ZONE>: 這個必須更改為Step 2中,我們所找到compute zones的名字。
  • 依照影片中的範例,我們填入:datalab create mydatalabvm --zone us-central1-b

創建過程約需稍等五分鐘。

Step 3 : 創建過程中,可能會碰到如紅框處的問題(詢問ssh passphrase)。

第一個問題回答 "Y"
第二三個問題直接按 "Enter" return即可。

https://ithelp.ithome.com.tw/upload/images/20190913/20120424cCgWtjRWxm.png

Step 4 : 直到看到下方處出現請你開啟 "Web Preview" 的訊息才算建立完成,
這時按 Cloud Shell 的右上角,點選 Change Port,
並更換我們的 port 至 8081,完成後點選 CHANGE AND PREVIEW。

https://ithelp.ithome.com.tw/upload/images/20190913/20120424ROXbAmTiE1.png


part 2 : (啟用Cloud API) 開啟 Cloud Source Repositories API

Step 1 : 確定 Cloud Source Repositories API 是被開啟的:

  • 點選一下網址,記得要切換至"Qwiklabs所提供的帳號"開啟API應用。

https://console.cloud.google.com/apis/library/sourcerepo.googleapis.com/?q=Repositories


part 3 : (複製專案) 在 Cloud Datalab 將專案複製下來

Step 0 : 接下來會直接使用 Cloud Datalab 跑 pyhton 程式

Step 1 : 我們回到 part 1 所開啟的 Datalab,按左上角開啟一個新的 notebook。

https://ithelp.ithome.com.tw/upload/images/20190914/20120424hgoNuzUOPU.png

Step 2 : 我們可以點選紅框處更改notebook的名字,例如我們更改成:"checkout"。

https://ithelp.ithome.com.tw/upload/images/20190914/20120424ns2w7Piguw.png

Step 3 : 我們在第一格中貼上這段code,這段code主要是幫我們從github複製檔案下來。

%bash
git clone https://github.com/GoogleCloudPlatform/training-data-analyst
rm -rf training-data-analyst/.git

※解釋:

 %bash:此指令打在開頭,表示這整格cell之後皆執行Bash指令。

Step 4 : 我們確認是否檔案有被成功的複製下來,我們輸入!ls,只要有看到"training-data-analyst"資料夾就是成功了。

!ls

結果如下圖:
https://ithelp.ithome.com.tw/upload/images/20190914/20120424E34FqdZ5wq.png

※解釋:

 !ls:!表示執行單行Bash指令,後面接指令內容,例如這段我們執行ls

Step 5 : 現在我們可以回到上一頁,點進"training-data-analyst"資料夾,裡面有我們這次會使用到的code。
(點擊左上角的Cloud Datalab即可回到索引頁。)

https://ithelp.ithome.com.tw/upload/images/20190914/20120424rkrb2tupDw.png

Step 6 : 開啟 mlapis.ipynb。

檔案路徑為:training-data-analyst > courses > machine_learning > deepdive > 01_googleml > mlapis.ipynb


part 4 : (取得API key) 取得圖片辨識, 語音辨識...相關的ML API key

再來我們要先去啟用我們的API服務,這樣才能執行Vision API, Translate API, Speech API...

Step 1 : 在APIs & services找到Library

https://ithelp.ithome.com.tw/upload/images/20190914/201204245mtvJZMRts.png

Step 2 : 我們搜尋Vision API
https://ithelp.ithome.com.tw/upload/images/20190914/20120424GBsrvngBa2.png

Step 3 : 確認Vision API已經被開啟
https://ithelp.ithome.com.tw/upload/images/20190914/201204244imAeIB8O8.png

Step 4 : 我們重複Step 2, 3,依序確認Translate API, Speech API...等要用的API,確認這些都是已經被開啟的。

Step 5 : 我們需要去取得 credentials(類似金鑰的證明文件),我們在APIs & services找到credentials

https://ithelp.ithome.com.tw/upload/images/20190914/20120424fzTfPiomps.png

Step 6 : 我們點選Create Credentials找到API key

https://ithelp.ithome.com.tw/upload/images/20190914/20120424qjeanBAFsN.png

Step 7 : 我們就會得到我們的API key了,我們將他複製下來。

https://ithelp.ithome.com.tw/upload/images/20190914/20120424QXr7iKC025.png

part 5 : (實作API) 實作各種 API

  • 我們要回到 part 3 的 mlapis.ipynb檔案。

Step 1 : 將我們剛剛所複製的API key取代原本key的地方。

https://ithelp.ithome.com.tw/upload/images/20190914/20120424tZ7CZFNUqU.png

Step 2 : 執行第二格cell的pip程式碼,我們要安裝Python client的服務。

https://ithelp.ithome.com.tw/upload/images/20190914/20120424oiqiA2pItC.png

翻譯語言 Translate API

Step 3 : 執行第三格cell的程式碼,這行是Translate API的測試。

# running Translate API
from googleapiclient.discovery import build
service = build('translate', 'v2', developerKey=APIKEY)

# use the service
inputs = ['is it really this easy?', 'amazing technology', 'wow']
outputs = service.translations().list(source='en', target='fr', q=inputs).execute()
# print outputs
for input, output in zip(inputs, outputs['translations']):
  print("{0} -> {1}".format(input, output['translatedText']))

https://ithelp.ithome.com.tw/upload/images/20190914/20120424q3efTVPYA9.png

我們可以在紅框處看到執行結果,我們也可以在綠框處更改想要翻譯的語言。
註:fr:French

※解釋:

我們先輸入了input字串,再拿這些inputs向伺服器請求此內容的翻譯,
而伺服器會回傳給我們outputs,這些outputs就是翻譯的結果。

圖像辨識 Vision API

Step 4 : 我們執行第四格cell的程式碼,這行是Vision API的測試。
我們會需要一張圖做為input,而此處已經有一個路標作為我們的範例使用。

# Running Vision API
import base64
IMAGE="gs://cloud-training-demos/vision/sign2.jpg"
vservice = build('vision', 'v1', developerKey=APIKEY)
request = vservice.images().annotate(body={
        'requests': [{
                'image': {
                    'source': {
                        'gcs_image_uri': IMAGE
                    }
                },
                'features': [{
                    'type': 'TEXT_DETECTION',
                    'maxResults': 3,
                }]
            }],
        })
responses = request.execute(num_retries=3)
print(responses)

https://ithelp.ithome.com.tw/upload/images/20190915/20120424bkKTeJdDY4.png

※解釋:

我們可以注意到紅框處,他是一個雲端的圖片位置,就是我們的input圖片
綠框處與籃框處,代表的是我們運行的Vision APIv1版本
橘框處代表的是我們透過gcs_image_uri這個參數擺放我們的圖片內容(此處為變數IMAGE),傳送至雲端
(這裡直接使用雲端圖片位置會更快,因為我們不需要再次上傳圖片。)
GCS就是Google Cloud Storage的簡稱
紫框處代表我們要求作TEXT_DETECTION,代表文字偵測。

我們請求 Vision API 幫我們分析這張圖的內容,他會回傳 JSON 格式給我們。
我來看回傳的所有內容,

https://ithelp.ithome.com.tw/upload/images/20190915/20120424D2keqV60hZ.png

※解釋:

開頭的zh指的是中文
boundingPoly : 指的是bounding polygon,表示偵測這個文字邊界範圍所圍成的多邊形。

Step 5 : 因為回傳的結果很多,我們往下一格cell看,這格cell能幫我們只先取得第一個文字片段。

foreigntext = responses['responses'][0]['textAnnotations'][0]['description']
foreignlang = responses['responses'][0]['textAnnotations'][0]['locale']
print(foreignlang, foreigntext)

https://ithelp.ithome.com.tw/upload/images/20190915/201204245N2Gken8y1.png

※解釋:

第一行description: 幫我們取得文字內容 (可以看到剩下的中文內容)
第二行locale: 幫我們取得語言種類 (得到zh,表示中文)

Step 6 : 再往下一格cell看,這裡我們再使用一下Translate API幫我們翻譯內容變成英文。

inputs=[foreigntext]
outputs = service.translations().list(source=foreignlang, target='en', q=inputs).execute()
# print(outputs)
for input, output in zip(inputs, outputs['translations']):
  print("{0} -> {1}".format(input, output['translatedText']))

https://ithelp.ithome.com.tw/upload/images/20190915/20120424Bt2IX2AnvI.png

※解釋:

可以看到紅框處分別表示翻譯的目標語言,以及翻譯的結果。

自然語言辨識 Language API

Step 7 : 往下一格cell看,我們接下來要實作自然語言辨識的功能,我們已經預先準備好一些引文。
我們直接來看這些內容的情緒如何。

lservice = build('language', 'v1beta1', developerKey=APIKEY)
quotes = [
  'To succeed, you must have tremendous perseverance, tremendous will.',
  'It’s not that I’m so smart, it’s just that I stay with problems longer.',
  'Love is quivering happiness.',
  'Love is of all passions the strongest, for it attacks simultaneously the head, the heart, and the senses.',
  'What difference does it make to the dead, the orphans and the homeless, whether the mad destruction is wrought under the name of totalitarianism or in the holy name of liberty or democracy?',
  'When someone you love dies, and you’re not expecting it, you don’t lose her all at once; you lose her in pieces over a long time — the way the mail stops coming, and her scent fades from the pillows and even from the clothes in her closet and drawers. '
]
for quote in quotes:
  response = lservice.documents().analyzeSentiment(
    body={
      'document': {
         'type': 'PLAIN_TEXT',
         'content': quote
      }
    }).execute()
  polarity = response['documentSentiment']['polarity']
  magnitude = response['documentSentiment']['magnitude']
  print('POLARITY=%s MAGNITUDE=%s for %s' % (polarity, magnitude, quote))

https://ithelp.ithome.com.tw/upload/images/20190915/201204240GKn53Gnfv.png

※解釋:

可以看到紅框處的polarity: 如果為正,表示情緒正面;如果為負,表示情緒負面
紅框處的另一個magnitude: 表示這段文字中的情緒詞有多強烈 (非常強烈的正面詞彙或負面詞彙)
可以以綠框處的結果作為參考。

語音辨識 Speech API

Step 8 : 往下一格cell看,我們接下來要實作語音辨識功能,我們一樣已經先準備好了一段語音。
這段語音被存放在雲端中,我們只要下指令請求他幫我們將這段語音轉成文字稿即可得到回傳的JSON檔案。

sservice = build('speech', 'v1', developerKey=APIKEY)
response = sservice.speech().recognize(
    body={
        'config': {
            'languageCode' : 'en-US',
            'encoding': 'LINEAR16',
            'sampleRateHertz': 16000
        },
        'audio': {
            'uri': 'gs://cloud-training-demos/vision/audio.raw'
            }
        }).execute()
print(response)

https://ithelp.ithome.com.tw/upload/images/20190915/20120424pkwfhOK579.png

※解釋:

圖中紅框處 : 語音檔的雲端連結。
綠框處confidence : 指的是他對這個語音轉換文字稿的結果有多少的信心水準。
從圖片中可以看見,信心水準非常高。

這個lab中我們利用了一些已經訓練好的ML模型,
透過API的串接我們能直接運算出結果。
我們想讓讀者知道的是,「並不是所有的ML訓練皆要從0開始建立模型」,
很多已經訓練好的結果,例如圖片辨識或語音辨識,
是可以直接使用而無需從頭開始建的。

而之後的課程,我們就要開始學習「從0開始建立屬於自己的ML模型」。

  • (Course - How Google does Machine Learning 完)

參考資料


上一篇
【Day 13】 Google ML - Lab 2 - Analyzing Data using Datalab and BigQuery - 使用 BigQuery與Datalab視覺化分析資料
下一篇
【Day 15】 Google ML - Lesson 1 - Supervised Learning 與 Unsupervised Learning 監督式學習與非監督式學習的介紹和比較
系列文
Google machine learning 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言