iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
Google Developers Machine Learning

Overview of Machine Learning Products系列 第 12

[Day 12] Google Natural Language - 3

今天來Google Natural Language第三篇,我本來想按照Natural Language裡分析情緒這個部分實作,可是看完以後發現它code有點短,只有下面這樣:

func analyzeSentimentFromGCS(ctx context.Context, gcsURI string) (*languagepb.AnalyzeSentimentResponse, error) {
        return client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
                Document: &languagepb.Document{
                        Source: &languagepb.Document_GcsContentUri{
                                GcsContentUri: gcsURI,
                        },
                        Type: languagepb.Document_PLAIN_TEXT,
                },
        })
}

遲遲找不到適合的範例,恰巧看到Natural Language基礎知識有一個蓋茨堡宣言的範例,gcsURI是gs://cloud-samples-tests/natural-language/gettysburg.txt,我把gcsURI帶入gs://cloud-samples-tests/natural-language/gettysburg.txt,發現跑出來結果很難閱讀
https://ithelp.ithome.com.tw/upload/images/20190919/20103835YiF5vDmVjT.jpg

好吧,就照著之前Video跟Vision那樣,把它改寫得比較好閱讀一點:

func AnalyzeSentiment(gcsURI string) error {
  ctx := context.Background()

  // Creates a client.
  client, err := language.NewClient(ctx)
  if err != nil {
    log.Fatalf("Failed to create client: %v", err)
    return err
  }
  op, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
    Document: &languagepb.Document{
      Source: &languagepb.Document_GcsContentUri{
        GcsContentUri: gcsURI,
      },
      Type: languagepb.Document_PLAIN_TEXT,
    },
  })
  if err != nil {
    return err
  }

  fmt.Printf("Document Sentiment:\n")
  fmt.Printf("\tScore: %.2f\n", op.DocumentSentiment.Score)
  fmt.Printf("\tMagnitude: %.2f\n", op.DocumentSentiment.Magnitude)
  fmt.Printf("Language: %q\n\n", op.Language)
  for _, annotation := range op.Sentences {
    text := annotation.GetText()
    fmt.Printf("Text:\n")
    fmt.Printf("\tContent: %s\n", text.Content)
    fmt.Printf("\tSentiment: %q\n", annotation.Sentiment)
  }

  return nil
}

再丟入一樣的蓋茨堡宣言進去運算以後,我們再來看看漂亮的output。
https://ithelp.ithome.com.tw/upload/images/20190919/201038354PWonaEpH9.jpg

但我始終算不出Natural Language基礎知識裡的{score: 0.2, magnitude: 3.6}。靈機一動看看其他版本的宣言,來研究一下其他結果。
https://ithelp.ithome.com.tw/upload/images/20190919/20103835Ej72eptvPT.jpg

嗯?都是蓋茨堡宣言,竟然結果不完全一樣,可以看到最後兩段gcs沒辨識出來,但wiki上的有結果,不過每個句子的比重差不多,可能是不同結構造成的誤差,剩下就看實際使用時的情境去做調整。

好了,今天是個很有實驗精神的一篇,測了不同的蓋茨堡宣言、改寫了範例程式。
今天就到這邊了,這是今天的Github: https://github.com/josephMG/ithelp-2019/tree/Day-12 。謝謝大家~


上一篇
[Day 11] Google Natural Language - 2
下一篇
[Day 13] Google Natural Language - 子系列最終章
系列文
Overview of Machine Learning Products30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言