内容分类教程

受众

本教程旨在让您快速开始通过 Cloud Natural Language 探索和开发应用它专为熟悉基本编程的人设计,但即使没有太多编程知识,您也应该能够按照说明操作。阅读完本教程后,您应该能够根据参考文档创建您自己的基本应用。

本教程介绍使用 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 请求的结构,请参阅 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 函数完成该查询。您可以在 classify_text_tutorial.py 文件中找到辅助函数(例如 similarity)的实现。在您的应用中,应该围绕特定用例仔细设计相似性评分和排名。

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 是一种自然且方便的索引数据存储选择。