內容分類教學課程

目標對象

本教學課程旨在協助您快速起步,探索如何使用 Cloud Natural Language API 開發應用程式。課程內容以熟悉基本程式設計的人員為目標對象,然而即便您對程式設計瞭解不多,也應該能夠按步操作。完成本教學課程後,您應能使用參考資料說明文件建立自己的基本應用程式。

本教學課程採用 Python 程式碼,逐步建立 Natural Language 應用程式。本文目的並非提供 Python 用戶端程式庫的相關說明,而是解釋如何呼叫 Natural Language API。Java 和 Node.js 的應用程式大致類似。請參閱 Natural Language API 範例以取得其他語言的範例 (包括本教學課程的範例)。

必備條件

本教學課程有幾項必備條件:

總覽

本教學課程會透過 classifyText 要求,逐步引導您操作基本的 Natural Language 應用程式,將內容分類並提供信賴分數,例如:

category: "/Internet & Telecom/Mobile & Wireless/Mobile Apps & Add-Ons"
confidence: 0.6499999761581421

如要查看所有可用類別標籤的清單,請參閱類別

在這個教學課程中,您將建立應用程式來執行下列工作:

  • 分類多個文字檔案並將結果寫入索引檔案。
  • 處理輸入查詢文字以尋找類似的文字檔案。
  • 處理輸入查詢類別標籤以尋找類似的文字檔案。

本教學課程使用來自維基百科的內容。您可以建立類似的應用程式來處理新聞或線上評論等內容。

來源檔案

您可以在 GitHub 上的 Python 用戶端程式庫範例中找到教學課程原始碼。

本教學課程使用來自維基百科的範例原文。您可以在 GitHub 專案的 resources/texts 資料夾中找到範例文字檔。

匯入程式庫

如要使用 Cloud Natural Language API,您必須從 google-cloud-language 程式庫匯入 language 模組。language.types 模組包含建立要求時所需的類別。language.enums 模組用於指定輸入文字的類型。本教學課程是將純文字內容分類 (language.enums.Document.Type.PLAIN_TEXT)。

如要根據產生的內容分類結果計算文字之間的相似度,本教學課程會使用 numpy 進行向量計算。

Python

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱Natural Language 用戶端程式庫。 詳情請參閱 Natural Language Python API 參考說明文件

如要向 Natural Language 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import argparse
import json
import os

from google.cloud import language_v1
import numpy

步驟 1:將內容分類

您可以使用 Python 用戶端程式庫建立要求來呼叫 Natural Language API 以分類內容。Python 用戶端程式庫會封裝傳送至 Natural Language API 的要求詳細資料及其回應。

本教學課程中的 classify 函式會呼叫 Natural Language API 的 classifyText 方法,方法是先建立 LanguageServiceClient 類別的執行個體,然後呼叫 LanguageServiceClient 執行個體的 classify_text 方法。

本教學課程的 classify 函式只會分類這個範例的文字內容。如要分類網頁內容,請將網頁的來源 HTML 做為 text,並將 type 參數設為 language.enums.Document.Type.HTML

詳情請參閱「分類內容」。如要瞭解 Natural Language API 要求的結構,請參閱 Natural Language 參考資料

Python

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱Natural Language 用戶端程式庫。 詳情請參閱 Natural Language Python API 參考說明文件

如要向 Natural Language 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def classify(text, verbose=True):
    """Classify the input text into categories."""

    language_client = language_v1.LanguageServiceClient()

    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )
    response = language_client.classify_text(request={"document": document})
    categories = response.categories

    result = {}

    for category in categories:
        # Turn the categories into a dictionary of the form:
        # {category.name: category.confidence}, so that they can
        # be treated as a sparse vector.
        result[category.name] = category.confidence

    if verbose:
        print(text)
        for category in categories:
            print("=" * 20)
            print("{:<16}: {}".format("category", category.name))
            print("{:<16}: {}".format("confidence", category.confidence))

    return result

傳回的結果是使用類別標籤做為索引鍵並以信心分數做為值的字典,例如:

{
    "/Computers & Electronics": 0.800000011920929,
    "/Internet & Telecom/Mobile & Wireless/Mobile Apps & Add-Ons": 0.6499999761581421
}

教學課程中的 Python 指令碼經過編排,可從指令列執行以進行快速實驗。舉例來說,您可以執行:

python classify_text_tutorial.py classify "Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice. "

步驟 2:建立多個文字檔案的索引

本教學課程指令碼中的 index 函式會將含有多個文字檔的目錄,以及儲存已建立索引輸出內容的檔案路徑 (預設檔案名稱為 index.json) 做為輸入內容。index 函式會讀取輸入目錄中每個文字檔的內容,然後將文字檔傳遞至 Cloud Natural Language API,分類至內容類別。

Python

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱Natural Language 用戶端程式庫。 詳情請參閱 Natural Language Python API 參考說明文件

如要向 Natural Language 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def index(path, index_file):
    """Classify each text file in a directory and write
    the results to the index_file.
    """

    result = {}
    for filename in os.listdir(path):
        file_path = os.path.join(path, filename)

        if not os.path.isfile(file_path):
            continue

        try:
            with open(file_path) as f:
                text = f.read()
                categories = classify(text, verbose=False)

                result[filename] = categories
        except Exception:
            print(f"Failed to process {file_path}")

    with open(index_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(result, ensure_ascii=False))

    print(f"Texts indexed in file: {index_file}")
    return result

Cloud Natural Language API 針對各個檔案傳回的結果會整理為單一字典,接著序列化為 JSON 字串並寫入檔案。例如:

{
    "android.txt": {
        "/Computers & Electronics": 0.800000011920929,
        "/Internet & Telecom/Mobile & Wireless/Mobile Apps & Add-Ons": 0.6499999761581421
    },
    "google.txt": {
        "/Internet & Telecom": 0.5799999833106995,
        "/Business & Industrial": 0.5400000214576721
    }
}

如要從指令列為文字檔建立索引,並使用預設輸出檔名 index.json,請執行下列指令:

python classify_text_tutorial.py index resources/texts

步驟 3:查詢索引

透過類別標籤查詢

建立索引檔案 (預設檔案名稱 = index.json) 後,我們就能查詢索引,擷取部分檔案名稱及其信賴分數。

其中一種做法是使用類別標籤做為查詢,本教學課程會透過 query_category 函式完成這項操作。輔助函式 (例如 similarity) 的實作項目位於 classify_text_tutorial.py 檔案中。您的應用程式應根據特定用途審慎設計相似度分數與評等。

Python

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱Natural Language 用戶端程式庫。 詳情請參閱 Natural Language Python API 參考說明文件

如要向 Natural Language 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def query_category(index_file, category_string, n_top=3):
    """Find the indexed files that are the most similar to
    the query label.

    The list of all available labels:
    https://cloud.google.com/natural-language/docs/categories
    """

    with open(index_file) as f:
        index = json.load(f)

    # Make the category_string into a dictionary so that it is
    # of the same format as what we get by calling classify.
    query_categories = {category_string: 1.0}

    similarities = []
    for filename, categories in index.items():
        similarities.append((filename, similarity(query_categories, categories)))

    similarities = sorted(similarities, key=lambda p: p[1], reverse=True)

    print("=" * 20)
    print(f"Query: {category_string}\n")
    print(f"\nMost similar {n_top} indexed texts:")
    for filename, sim in similarities[:n_top]:
        print(f"\tFilename: {filename}")
        print(f"\tSimilarity: {sim}")
        print("\n")

    return similarities

如需所有可用類別的清單,請參閱類別

與先前一樣,您可以從指令列呼叫 query_category 函式:

python classify_text_tutorial.py query-category index.json "/Internet & Telecom/Mobile & Wireless"

輸出結果應該會類似下列內容:

Query: /Internet & Telecom/Mobile & Wireless


Most similar 3 indexed texts:
  Filename: android.txt
  Similarity: 0.665573579045


  Filename: google.txt
  Similarity: 0.517527175966


  Filename: gcp.txt
  Similarity: 0.5

透過文字查詢

您還可以使用不屬於索引的文字進行查詢。本教學課程的 query 函式與 query_category 函式類似, 但多了提出 classifyText 要求以取得文字輸入內容的步驟, 並使用結果查詢索引檔案。

Python

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱Natural Language 用戶端程式庫。 詳情請參閱 Natural Language Python API 參考說明文件

如要向 Natural Language 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def query(index_file, text, n_top=3):
    """Find the indexed files that are the most similar to
    the query text.
    """

    with open(index_file) as f:
        index = json.load(f)

    # Get the categories of the query text.
    query_categories = classify(text, verbose=False)

    similarities = []
    for filename, categories in index.items():
        similarities.append((filename, similarity(query_categories, categories)))

    similarities = sorted(similarities, key=lambda p: p[1], reverse=True)

    print("=" * 20)
    print(f"Query: {text}\n")
    for category, confidence in query_categories.items():
        print(f"\tCategory: {category}, confidence: {confidence}")
    print(f"\nMost similar {n_top} indexed texts:")
    for filename, sim in similarities[:n_top]:
        print(f"\tFilename: {filename}")
        print(f"\tSimilarity: {sim}")
        print("\n")

    return similarities

如要執行此操作,請透過指令列執行:

python classify_text_tutorial.py query index.json "Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice. "

這會顯示類似下面的內容:

Query: Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice.

  Category: /Internet & Telecom, confidence: 0.509999990463
  Category: /Computers & Electronics/Software, confidence: 0.550000011921

Most similar 3 indexed texts:
  Filename: android.txt
  Similarity: 0.600579500049


  Filename: google.txt
  Similarity: 0.401314790229


  Filename: gcp.txt
  Similarity: 0.38772339779

相關資源

透過內容分類 API,您可以建立其他應用程式。例如:

  • 將文章的各個段落分類,藉此查看主題之間的轉換。

  • 將具有時間戳記的內容分類並分析各段時間的趨勢主題。

  • 使用 analyzeSentiment 方法比較內容類別和內容情緒。

  • 比較內容類別分類以及文字提及實體的分析。

此外,您還可以使用其他 Google Cloud Platform 產品來簡化工作流程:

  • 在本教學課程的範例應用程式中,我們處理的是本機文字檔,但您可以修改程式碼,將 Google Cloud Storage URI 傳遞至 classify_text 方法,以便處理儲存在 Google Cloud Storage 值區的文字檔。

  • 在這個教學課程的應用程式範例中,我們是將索引檔案儲存在本機,且每次查詢都會讀取整個索引檔案。也就是說,如果索引資料龐大或需要處理多個查詢,就會出現高度延遲狀況。儲存索引資料時,Datastore 是理所當然的便利選擇。