分類

展開全部 | 收合全部

分類

展開全部 | 收合全部

【Google ML】14 – 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 完)

本文同步發佈在: 第 11 屆 iT 邦幫忙鐵人賽
【Day 14】 Google ML – Lab 3 – Machine Learning APIs – (API實作篇) google圖片辨識, 語音辨識, 語言翻譯, 自然語言辨識(NL)


參考資料

⭐Google Machine Learning 相關文章整理⭐:
1.訂閱課程【Google ML】1 – Google ML – 參賽原因 與 就先從認識 coursera 與訂閱課程開始第一天吧
⭐ML 基礎知識篇⭐:
1.基礎ML知識什麼是ML? 為什麼ML最近才紅起來? 可參考:【Day 3】
2.設計ML問題如何設計一個ML問題?可參考:【Day 4】
3.ML與一般算法比較比較一般算法與ML算法,看出ML的優勢。可參考:【Day 11】
⭐ML 應用策略篇⭐:
1.ML的成功策略使用ML要成功,常需要的關鍵策略。可參考:【Day 5】
2.ML各階段與比重分配企業運行ML時,在ML的各階段應該放的比重與心力。可參考:【Day 6】
3.ML失敗的常見原因大部分企業使用ML卻失敗的前十大主因。可參考:【Day 6】
4.企業如何引入MLML在企業運行的五大階段與注意事項。 可參考:【Day 7】
⭐GCP 認識篇⭐:
1.在GCP上運行ML的階段在GCP上運行ML大概有哪五大階段? 可參考:【Day 2】
2.GCP上ML的介紹GCP上ML的介紹。可參考:【Day 8】【Day 11】
3.已訓練好的ML模型已訓練好的ML模型。建議可直接使用,不需要再自己訓練。如:Vision API(圖片辨識), Video intelligence API(影片辨識), Speech API(語音辨識), Translation API(語言翻譯), Natural Language API(自然語言處理)。介紹:【Day 4】詳細整理與比較:【Day 12】lab實作:【Day 14】
⭐GCP 上的 lab 實作篇⭐:
1.Lab 事前準備Lab 0 – 在GCP上開始lab前的事前準備與注意事項。可參考:【Day 9】
2.GCP上使用 VMLab 1 – 在GCP上分析地震資料與製圖,並儲存在雲端。可參考: 【Day 10】
3.BigQuery 與 DatalabLab 2 – 使用 BigQuery 與 Datalab 視覺化分析資料。可參考:【Day 13】
4.google ML APIsLab 3 – 使用google已訓練好的ML模型進行實作。如:Vision API(圖片辨識), Video intelligence API(影片辨識), Speech API(語音辨識), Translation API(語言翻譯), Natural Language API(自然語言處理)。可參考:【Day 14】
⭐ML中的不同學習種類⭐:
1.【Day 15】 監督式學習(Supervised Learning) 與 非監督式學習(Unsupervised Learning) 的介紹和比較
⭐訓練「一個」ML模型⭐:
(這裡以 監督式學習(Supervised Learning) 為例)
1. (訓練前)決定資料集與分析資料你想要預測的是什麼資料? 這邊需要先知道 example、label、features的概念。介紹可參考:【Day 15】而我們這次作為範例的訓練資料集介紹在:【Day 19】
2. (訓練前)決定問題種類依據資料,會知道是什麼類型的問題。regression problem(回歸問題)? classification problem(分類問題)? 此處可參考:【Day 16】與進階內容:【Day 17】
3. (訓練前)決定ML模型(ML models)依據問題的種類,會知道需要使用什麼對應的ML模型。回歸模型(Regression model)? 分類模型(Classification model)? 此處可參考:【Day 18】神經網路(neural network)? 簡介於:【Day 25】
4.(模型裡面的參數)ML模型裡面的參數(parameters)與超參數(hyper-parameters) 此處可參考:【Day 18】
5. (訓練中) 調整模型評估當前模型好壞損失函數(Loss Functions):使用損失函數評估目前模型的好與壞。以MSE(Mean Squared Error), RMSE(Root Mean Squared Error), 交叉熵(Cross Entropy)為例。此處可參考:【Day 20】
6. (訓練中) 調整模型修正模型參數以梯度下降法 (Gradient Descent)為例:決定模型中參數的修正「方向」與「步長(step size)」此處可參考:【Day 21】
7. (訓練中) 調整腳步調整學習腳步透過學習速率(learning rate)來調整ML模型訓練的步長(step size),調整學習腳步。(此參數在訓練前設定,為hyper-parameter)。此處可參考:【Day 22】
8. (訓練中) 加快訓練取樣與分堆設定batch size,透過batch從訓練目標中取樣,來加快ML模型訓練的速度。(此參數在訓練前設定,為hyper-parameter)。與迭代(iteration),epoch介紹。此處可參考:【Day 23】
9. (訓練中) 加快訓練檢查loss的頻率調整「檢查loss的頻率」,依據時間(Time-based)與步驟(Step-based)。此處可參考:【Day 23】
10. (訓練中) 完成訓練(loop) -> 完成重覆過程(評估當前模型好壞 -> 修正模型參數),直到能通過「驗證資料集(Validation)」的驗證即可結束訓練。此處可參考:【Day 27】
11. (訓練後)訓練結果可能問題「不適當的最小loss?」 此處可參考:【Day 28】
12. (訓練後)訓練結果可能問題欠擬合(underfitting)?過度擬合(overfitting)? 此處可參考:【Day 26】
13. (訓練後)評估 – 性能指標性能指標(performance metrics):以混淆矩陣(confusion matrix)分析,包含「Accuracy」、「Precision」、「Recall」三種評估指標。簡介於:【Day 28】詳細介紹於:【Day 29】
14. (訓練後)評估 – 新資料適用性泛化(Generalization):對於新資料、沒看過的資料的模型適用性。此處可參考:【Day 26】
15. (訓練後)評估 – 模型測試使用「獨立測試資料集(Test)」測試? 使用交叉驗證(cross-validation)(又稱bootstrapping)測試? 此處可參考:【Day 27】
16.(資料分堆的方式)(訓練前) 依據上方「模型測試」的方法,決定資料分堆的方式:訓練用(Training)、驗證用(Validation)、測試用(Test)。此處可參考:【Day 27】
⭐從所有ML模型的訓練結果中,找到「最好的」ML模型⭐:
( 原因:「訓練好一個模型」不等於「找到最好的模型」 )
1.(訓練模型)【Day 27】 使用「訓練資料集(Training)」訓練模型(調整參數),也就是「上方表格」在做的內容
2.(結束訓練)【Day 27】 訓練到通過「驗證資料集(Validation)」結束訓練(未達到overfitting的狀態前)
3.(模型再調整)【Day 27】 超參數(hyperparameters)調整或神經網路的「layer數」或「使用的node數」(一些訓練前就會先決定的東西)
4.(loop)【Day 27】 (模型再調整)後,重複上述(訓練模型)、(結束訓練),完成訓練新的模型
5.(找到最佳模型)【Day 27】 從「所有訓練的模型」中,找到能使「驗證用資料集(Validation)」最小的loss,完成(找到最佳模型)
6.(決定是否生產)【Day 27】 可以開始決定要不要將此ML模型投入生產。此時我們可以使用「獨立測試資料集(Test)」測試? 使用交叉驗證(cross-validation)(又稱bootstrapping)測試?
⭐訓練 ML 模型的小實驗⭐:
1.【Day 24】 TensorFlow Playground 的簡介與介面介紹
2.【Day 24】 learning rate 的改變對訓練過程的影響
3.【Day 25】 使用神經網路(neural network)分類資料
4.【Day 25】 觀察batch size如何影響gradient descent
⭐30天內容回顧與課程索引, 參賽心得, 未來計畫與感謝⭐:
1.【Google ML】30 – 30天內容回顧與課程索引, 參賽心得, 未來計畫與感謝
⭐【喜歡我的文章嗎? 歡迎幫我按讚~ 讓基金會請創作者喝一杯咖啡!
如果喜歡我的文章,請幫我在下方【按五下Like】 (Google, Facebook 免註冊),會由 「LikeCoin」 贊助作者鼓勵繼續創作,讀者們「只需幫忙按讚,完全不用出錢」哦!

likecoin-steps
Howard Weng
Howard Weng

我是 Howard Weng,很多人叫我嗡嗡。這個網站放了我的各種筆記。希望這些筆記也能順便幫助到有需要的人們!如果文章有幫助到你的話,歡迎幫我點讚哦!
另外,因為定位是「個人的隨手筆記」,有些文章內容「⚠️可能我理解有誤⚠️」或「?只寫到一半?」,如果有發現這樣的情況,歡迎在該文章的最下面留言提醒我!我會儘快修正或補上!感謝大家的建議與幫忙,讓網站能變得更好?

文章: 890

★留個言吧!內容有誤或想要補充也歡迎與我討論!