iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 16
0

上一篇介紹完Pretrained ML API這篇要來實作啦~
首先我們的學習平台還是利用QiwiksLab進到GCP
(如果沒有參加課程直接使用GCP的話Google有可能會向你收費喔[超過免費流量的話])
OK和前一篇實作一樣,進到GCP平台就可以開始啦~
https://ithelp.ithome.com.tw/upload/images/20190919/20120163FVOF0hQua3.png


我們要利用的是,GCP上的IPython(Jupyter Notebook)交互式互動環境來引用我們的ML API,
和上一篇一樣先建立一個Ipython環境,在側欄找到AI Platform 並選擇 Notebook

然後在上方的Instance選擇 TENSORFLOW 1.xx 沒有GPU版本
(我其實想玩玩有GPU的但是不知道QiwiksLab會不會怎樣噗哈哈,所以只好跟著課程來~)
選擇完後不用改甚麼直接CREATE
https://ithelp.ithome.com.tw/upload/images/20190919/20120163tgzK5kgtIU.png
好了現在趁他在建立環境的時候,我們先左轉去啟用等等會用到的API並創建金鑰。
在側欄找到 APIs and services 並選擇 Library,
https://ithelp.ithome.com.tw/upload/images/20190919/20120163SF5BnVdntZ.png
進到Library頁面後再搜尋欄打上Google Cloud Vision API、Translate API、Speech API、Natural Language API。並確定他們都Enable了,如果沒有就點Enable ~讓他啟用,下面的圖只示範一個。
https://ithelp.ithome.com.tw/upload/images/20190919/20120163iHR2J0PihP.png
https://ithelp.ithome.com.tw/upload/images/20190919/20120163Cd8mSeUabO.png
如果沒有看到綠色勾勾點Enable開啟即可。
好的,我們的API已經啟用完了,現在要來創建API金鑰,創建金鑰是為了可以在程式中使用API的功能,
一個類似身分證的功能(GCP會根據金鑰來看這隻程式用的API流量要算哪隻ACCOUNT的~)
OK我們在側欄找到 APIs and services 並找到 Credentials 點進去後~
https://ithelp.ithome.com.tw/upload/images/20190919/20120163bbWhw8iAmf.png
點擊,Create Credentials --> API key
https://ithelp.ithome.com.tw/upload/images/20190919/20120163lMXHIYU4my.png
再來複製這一串Key就好囉~
https://ithelp.ithome.com.tw/upload/images/20190919/201201633TbfDWpXAY.png
好的回到我們Notebook頁面,基本上確認完API Key有沒又ENABLE時環境就會架好了。
進到Nootbook 頁面後,按 OPEN JUPYTERLAB就會在新分頁開啟IPython環境了!長這樣
https://ithelp.ithome.com.tw/upload/images/20190919/20120163lDVsSAJVCC.png

而我們要先從Google的Github上複製課程資料~
所以我們要先開Terminal,打上

git clone https://github.com/GoogleCloudPlatform/training-data-analyst 

沒有意外的話,執行完後左邊會多出一個資料夾,長這個樣子!
https://ithelp.ithome.com.tw/upload/images/20190919/20120163VvKraDsauU.png
好了再來我們看到左邊的資料夾,根據這個路徑~

training-data-analyst > courses > machine_learning > deepdive > 01_googleml > mlapis.ipynb

找到mlapis.ipynb把他打開!
只要更改第一行的API KEY(改成前面複製的那一串)就可以輕鬆執行啦~
https://ithelp.ithome.com.tw/upload/images/20190919/20120163WGPlh7MnNV.png
好的那我也把Notebook的內容轉貼過來吧~

APIKEY="這裡請改成你的KEY"  # Replace with your API key

這是定義APIKEY


!pip install --upgrade google-api-python-client

安裝google-api-python-client來用google的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']))

上面是翻譯的API,可以把文字轉成想要的語言喔~
(可以試試看把target='fr'改成target='zh-tw',這樣就會變中文啦~)

# 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)

圖片辨識API~這個可能就要自己做做看才會懂了XD因為她的Response JSON有點長所以我也不好放進文章QQ
(上面這段程式利用Vision API來擷取圖片的文字~)下面那段程式是用來顯示結果的~(上面那段顯示JSON~)

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

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']))
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))

我給大家看看上面這段程式的RESPONSE~大家可能就會懂Language API在做啥了!

POLARITY=1 MAGNITUDE=0.9 for To succeed, you must have tremendous perseverance, tremendous will.
POLARITY=-1 MAGNITUDE=0.5 for It’s not that I’m so smart, it’s just that I stay with problems longer.
POLARITY=1 MAGNITUDE=0.9 for Love is quivering happiness.
POLARITY=1 MAGNITUDE=0.9 for Love is of all passions the strongest, for it attacks simultaneously the head, the heart, and the senses.
POLARITY=1 MAGNITUDE=0.2 for 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?
POLARITY=-1 MAGNITUDE=0.4 for 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. 

有看到POLARITY這是代表一句話是肯定的還是否定的~這樣利用結構化Language API自然語言就可以讓電腦了解我們在話中想表達什麼了!


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)

Speech API是將語音轉為文字,這裡實際操作會比較清楚他在幹嘛~
上段程式是回傳Json,下面是提取Response的方法!

print(response['results'][0]['alternatives'][0]['transcript'])
print('Confidence=%f' % response['results'][0]['alternatives'][0]['confidence'])

上面的CODE都可以自己改改PARMS喔~還不錯玩!

-今天是第16天,早點睡!小心爆肝ˊˇˋ


上一篇
[Day15] Pretrained ML API
下一篇
[Day17]Launching into Machine Learning
系列文
Google'sMachineLearning-挑戰機器智慧極限30

尚未有邦友留言

立即登入留言