你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure Synapse Analytics 中的 Azure AI 服务

使用来自 Azure AI 服务的预先训练模型,可以在 Azure Synapse Analytics 中通过人工智能 (AI) 丰富你的数据。

Azure AI 服务通过现成的预生成可定制 API 和模型,帮助开发人员和组织快速创建智能、前沿、面向市场且负责任的应用程序。

可以通过多种方式将部分 Azure AI 服务与 Synapse Analytics 中的数据结合使用:

  • Synapse Analytics 中的“Azure AI 服务”向导在 Synapse Notebook 中生成 PySpark 代码,Synapse Notebook 使用 Spark 表中的数据连接到 Azure AI 服务。 然后,使用预先训练的机器学习模型,该服务会为你完成将 AI 添加到数据的工作。 有关更多详细信息,请查看情绪分析向导异常情况检测向导

  • 使用 Synapse 机器学习 (SynapseML) 可以基于各种 Spark 数据源生成功能强大且高度可缩放的预测模型和分析模型。 Synapse Spark 提供内置的 SynapseML 库,包括 synapse.ml.cognitive。

  • 从向导生成的 PySpark 代码或本教程中提供的示例 SynapseML 代码开始,可以编写自己的代码,以将其他 Azure AI 服务与数据结合使用。 有关可用服务的详细信息,请参阅什么是 Azure AI 服务?

入门

本教程(在 Azure Synapse 中使用 Azure AI 服务的先决条件)指导你完成在 Synapse Analytics 中使用 Azure AI 服务之前需要执行的几个步骤。

使用情况

影像

计算机视觉

  • 描述:以用户可读的语言提供图像描述(ScalaPython
  • 分析(颜色、图像类型、人脸、成人/猥亵内容):分析图像的视觉特征(ScalaPython
  • OCR:读取图像中的文本(ScalaPython
  • 识别文本:读取图像中的文本(ScalaPython
  • 缩略图:从图像生成用户指定大小的缩略图(ScalaPython
  • 识别特定于领域的内容:识别特定于领域的内容(名人、地标)(ScalaPython
  • 标记:标识与输入图像相关的单词列表(ScalaPython

人脸

  • 检测:检测图像中的人脸(ScalaPython
  • 验证:验证两张人脸是否属于同一个人,或者一张人脸是否属于某一个人(ScalaPython
  • 识别:在人员组中查找与特定查询人脸最接近的匹配项(ScalaPython
  • 查找相似人脸:在人脸列表中查找与查询人脸相似的人脸(ScalaPython
  • 分组:根据相似性将一组人脸划分成不相交的组(ScalaPython

语音

语音服务

  • 语音转文本:听录音频流(ScalaPython
  • 对话听录:将已识别说话人的音频流听录到实时脚本。 (ScalaPython
  • 文本转语音:将文本转换为真实的音频(ScalaPython

语言

文本分析

  • 语言检测:检测输入文本的语言(ScalaPython
  • 关键短语提取:识别输入文本中的关键论题(ScalaPython
  • 命名实体识别:识别输入文本中的已知实体和常规命名实体(ScalaPython
  • 情绪分析:返回介于 0 和 1 之间的分数,指示输入文本中的情绪(ScalaPython
  • 医疗保健实体提取:从文本中提取医疗实体和关系。 (ScalaPython

翻译

翻译工具

  • 翻译:翻译文本。 (ScalaPython
  • 音译:将一种语言的文本从一个脚本转换为另一个脚本。 (ScalaPython
  • 检测:识别一段文本的语言。 (ScalaPython
  • 断句:识别文本段中的句子边界的位置。 (ScalaPython
  • 字典查找:为某个单词和少量的惯用语提供替代翻译。 (ScalaPython
  • 字典示例:提供示例,说明如何在上下文中使用字典中的术语。 (ScalaPython
  • 文档翻译:翻译所有支持的语言和方言的文档,同时保留文档结构和数据格式。 (ScalaPython

文档智能

文档智能(以前称为 Azure AI 文档智能)

  • 分析布局:从给定文档中提取文本和布局信息。 (ScalaPython
  • 分析收据:使用光学字符识别 (OCR) 和我们的收据模型从收据中检测和提取数据,这让你可以轻松地从收据中提取结构化数据,例如商店名称、商家电话号码、交易日期、交易总额等。 (ScalaPython
  • 分析名片:使用光学字符识别 (OCR) 和名片模型从名片中检测和提取数据,这让你可以轻松地从名片中提取结构化数据,例如联系人姓名、公司名称、电话号码、电子邮件等。 (ScalaPython
  • 分析发票:使用光学字符识别 (OCR) 以及我们的发票理解深度学习模型从发票中检测和提取数据,这让你可以轻松地从发票中提取结构化数据,例如客户、供应商、发票 ID、发票截止日期、总金额、发票应付金额、税额、发货人、帐单付款、行项等。 (ScalaPython
  • 分析 ID 文档:使用光学字符识别 (OCR) 和我们的 ID 文档模型从标识文档中检测和提取数据,从而轻松从 ID 文档中提取结构化数据,例如名字、姓氏、出生日期、文档编号等。 (ScalaPython
  • 分析自定义表单:根据从一组有代表性的训练表单创建的模型,将表单(PDF 和图像)中的信息提取到结构化数据中。 (ScalaPython
  • 获取自定义模型:获取有关自定义模型的详细信息。 (ScalaPython
  • 列出自定义模型:获取有关所有自定义模型的信息。 (ScalaPython

决策

异常检测器

  • 最新点的异常状态:使用前面的点生成模型,并确定最新点是否有异常(ScalaPython
  • 查找异常:使用整个系列生成模型,并在系列中查找异常(ScalaPython

先决条件

  1. 按照为 Azure AI 服务设置环境中的步骤设置 Azure Databricks 和 Azure AI 服务环境。 本教程介绍如何安装 SynapseML 以及如何在 Databricks 中创建 Spark 群集。
  2. 在 Azure Databricks 中创建新笔记本后,复制下面的“共享代码”并粘贴到笔记本中的新单元格中。
  3. 选择下面的一个服务示例,并将其复制粘贴到笔记本的第二个新单元格中。
  4. 将所有服务订阅密钥占位符替换为自己的密钥。
  5. 选择单元格右上角的运行按钮(三角形图标),然后选择“运行单元格”。
  6. 在单元格下方的表格中查看结果。

共享代码

若要开始,我们需要将此代码添加到项目中:

from pyspark.sql.functions import udf, col
from synapse.ml.io.http import HTTPTransformer, http_udf
from requests import Request
from pyspark.sql.functions import lit
from pyspark.ml import PipelineModel
from pyspark.sql.functions import col
import os
from pyspark.sql import SparkSession
from synapse.ml.core.platform import *

# Bootstrap Spark Session
spark = SparkSession.builder.getOrCreate()

from synapse.ml.core.platform import materializing_display as display
from synapse.ml.cognitive import *

# A multi-service resource key for Text Analytics, Computer Vision and Document Intelligence (or use separate keys that belong to each service)
service_key = find_secret("cognitive-api-key")
service_loc = "eastus"

# A Bing Search v7 subscription key
bing_search_key = find_secret("bing-search-key")

# An Anomaly Detector subscription key
anomaly_key = find_secret("anomaly-api-key")
anomaly_loc = "westus2"

# A Translator subscription key
translator_key = find_secret("translator-key")
translator_loc = "eastus"

# An Azure search key
search_key = find_secret("azure-search-key")

文本分析示例

文本分析服务提供了几种从文本中提取智能见解的算法。 例如,我们可以找到给定输入文本的情绪。 服务将返回介于 0.0 和 1.0 之间的分数,其中低分数表示负面情绪,高分表示正面情绪。 此示例使用三个简单的句子,并返回每个句子的情绪。

# Create a dataframe that's tied to it's column names
df = spark.createDataFrame(
    [
        ("I am so happy today, its sunny!", "en-US"),
        ("I am frustrated by this rush hour traffic", "en-US"),
        ("The Azure AI services on spark aint bad", "en-US"),
    ],
    ["text", "language"],
)

# Run the Text Analytics service with options
sentiment = (
    TextSentiment()
    .setTextCol("text")
    .setLocation(service_loc)
    .setSubscriptionKey(service_key)
    .setOutputCol("sentiment")
    .setErrorCol("error")
    .setLanguageCol("language")
)

# Show the results of your text query in a table format
display(
    sentiment.transform(df).select(
        "text", col("sentiment.document.sentiment").alias("sentiment")
    )
)

健康服务文本分析示例

健康服务文本分析从非结构化文本(如医生处方、出院小结、临床文档和电子健康记录)中提取和标记相关的医疗信息。

df = spark.createDataFrame(
    [
        ("20mg of ibuprofen twice a day",),
        ("1tsp of Tylenol every 4 hours",),
        ("6-drops of Vitamin B-12 every evening",),
    ],
    ["text"],
)

healthcare = (
    AnalyzeHealthText()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setLanguage("en")
    .setOutputCol("response")
)

display(healthcare.transform(df))

翻译器示例

翻译器是一种基于云的机器翻译服务,是用于构建智能应用的 Azure AI 服务系列 API 的一部分。 “翻译”可以轻松地集成到应用程序、网站、工具和解决方案中。 通过它,您可以在 90 种语言和方言中添加多语言用户体验,并且可以用任何操作系统进行文本翻译。 在此示例中,我们通过提供要翻译的句子和要翻译到的目标语言来执行简单文本翻译。

from pyspark.sql.functions import col, flatten

# Create a dataframe including sentences you want to translate
df = spark.createDataFrame(
    [(["Hello, what is your name?", "Bye"],)],
    [
        "text",
    ],
)

# Run the Translator service with options
translate = (
    Translate()
    .setSubscriptionKey(translator_key)
    .setLocation(translator_loc)
    .setTextCol("text")
    .setToLanguage(["zh-Hans"])
    .setOutputCol("translation")
)

# Show the results of the translation.
display(
    translate.transform(df)
    .withColumn("translation", flatten(col("translation.translations")))
    .withColumn("translation", col("translation.text"))
    .select("translation")
)

文档智能示例

文档智能(以前称为“Azure AI 文档智能”)是 Azure AI 服务的一部分,可让你使用机器学习技术构建自动化数据处理软件。 标识并提取文档中的文本、键/值对、选择标记、表和结构。 该服务会输出结构化数据,其中包含原始文件中的关系、边界框、置信度,等等。 在此示例中,我们将分析名片图像并将其信息提取到结构化数据中。

from pyspark.sql.functions import col, explode

# Create a dataframe containing the source files
imageDf = spark.createDataFrame(
    [
        (
            "https://mmlspark.blob.core.windows.net/datasets/FormRecognizer/business_card.jpg",
        )
    ],
    [
        "source",
    ],
)

# Run the Document Intelligence service
analyzeBusinessCards = (
    AnalyzeBusinessCards()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setImageUrlCol("source")
    .setOutputCol("businessCards")
)

# Show the results of recognition.
display(
    analyzeBusinessCards.transform(imageDf)
    .withColumn(
        "documents", explode(col("businessCards.analyzeResult.documentResults.fields"))
    )
    .select("source", "documents")
)

计算机视觉示例

计算机视觉会分析图像以识别结构,例如人脸、对象和自然语言说明。 在此示例中,我们标记一系列图像。 标记是对图像中可识别的对象、人物、风景和动作等事物的单个词说明。

# Create a dataframe with the image URLs
base_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/"
df = spark.createDataFrame(
    [
        (base_url + "objects.jpg",),
        (base_url + "dog.jpg",),
        (base_url + "house.jpg",),
    ],
    [
        "image",
    ],
)

# Run the Computer Vision service. Analyze Image extracts information from/about the images.
analysis = (
    AnalyzeImage()
    .setLocation(service_loc)
    .setSubscriptionKey(service_key)
    .setVisualFeatures(
        ["Categories", "Color", "Description", "Faces", "Objects", "Tags"]
    )
    .setOutputCol("analysis_results")
    .setImageUrlCol("image")
    .setErrorCol("error")
)

# Show the results of what you wanted to pull out of the images.
display(analysis.transform(df).select("image", "analysis_results.description.tags"))

必应图像搜索示例

必应图像搜索在 Web 中搜索以检索与用户自然语言查询相关的图像。 在此示例中,我们将使用一个文本查询来查找带引号的图像。 它返回包含与我们的查询相关的照片的图像 URL 列表。

# Number of images Bing will return per query
imgsPerBatch = 10
# A list of offsets, used to page into the search results
offsets = [(i * imgsPerBatch,) for i in range(100)]
# Since web content is our data, we create a dataframe with options on that data: offsets
bingParameters = spark.createDataFrame(offsets, ["offset"])

# Run the Bing Image Search service with our text query
bingSearch = (
    BingImageSearch()
    .setSubscriptionKey(bing_search_key)
    .setOffsetCol("offset")
    .setQuery("Martin Luther King Jr. quotes")
    .setCount(imgsPerBatch)
    .setOutputCol("images")
)

# Transformer that extracts and flattens the richly structured output of Bing Image Search into a simple URL column
getUrls = BingImageSearch.getUrlTransformer("images", "url")

# This displays the full results returned, uncomment to use
# display(bingSearch.transform(bingParameters))

# Since we have two services, they are put into a pipeline
pipeline = PipelineModel(stages=[bingSearch, getUrls])

# Show the results of your search: image URLs
display(pipeline.transform(bingParameters))

语音转文本示例

语音转文本服务将语音音频的流或文件转换为文本。 在此示例中,我们将听录一个音频文件。

# Create a dataframe with our audio URLs, tied to the column called "url"
df = spark.createDataFrame(
    [("https://mmlspark.blob.core.windows.net/datasets/Speech/audio2.wav",)], ["url"]
)

# Run the Speech-to-text service to translate the audio into text
speech_to_text = (
    SpeechToTextSDK()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setOutputCol("text")
    .setAudioDataCol("url")
    .setLanguage("en-US")
    .setProfanity("Masked")
)

# Show the results of the translation
display(speech_to_text.transform(df).select("url", "text.DisplayText"))

文本转语音示例

文本转语音服务允许用户从 119 种语言和变体的 270 多种神经语音中进行选择,以构建讲述自然语言的应用和服务。

from synapse.ml.cognitive import TextToSpeech

fs = ""
if running_on_databricks():
    fs = "dbfs:"
elif running_on_synapse_internal():
    fs = "Files"

# Create a dataframe with text and an output file location
df = spark.createDataFrame(
    [
        (
            "Reading out loud is fun! Check out aka.ms/spark for more information",
            fs + "/output.mp3",
        )
    ],
    ["text", "output_file"],
)

tts = (
    TextToSpeech()
    .setSubscriptionKey(service_key)
    .setTextCol("text")
    .setLocation(service_loc)
    .setVoiceName("en-US-JennyNeural")
    .setOutputFileCol("output_file")
)

# Check to make sure there were no errors during audio creation
display(tts.transform(df))

异常检测器示例

异常检测器对于检测时间序列数据中的不规则性非常有用。 在此示例中,我们使用该服务来查找整个时间序列中的异常情况。

# Create a dataframe with the point data that Anomaly Detector requires
df = spark.createDataFrame(
    [
        ("1972-01-01T00:00:00Z", 826.0),
        ("1972-02-01T00:00:00Z", 799.0),
        ("1972-03-01T00:00:00Z", 890.0),
        ("1972-04-01T00:00:00Z", 900.0),
        ("1972-05-01T00:00:00Z", 766.0),
        ("1972-06-01T00:00:00Z", 805.0),
        ("1972-07-01T00:00:00Z", 821.0),
        ("1972-08-01T00:00:00Z", 20000.0),
        ("1972-09-01T00:00:00Z", 883.0),
        ("1972-10-01T00:00:00Z", 898.0),
        ("1972-11-01T00:00:00Z", 957.0),
        ("1972-12-01T00:00:00Z", 924.0),
        ("1973-01-01T00:00:00Z", 881.0),
        ("1973-02-01T00:00:00Z", 837.0),
        ("1973-03-01T00:00:00Z", 9000.0),
    ],
    ["timestamp", "value"],
).withColumn("group", lit("series1"))

# Run the Anomaly Detector service to look for irregular data
anomaly_detector = (
    SimpleDetectAnomalies()
    .setSubscriptionKey(anomaly_key)
    .setLocation(anomaly_loc)
    .setTimestampCol("timestamp")
    .setValueCol("value")
    .setOutputCol("anomalies")
    .setGroupbyCol("group")
    .setGranularity("monthly")
)

# Show the full results of the analysis with the anomalies marked as "True"
display(
    anomaly_detector.transform(df).select("timestamp", "value", "anomalies.isAnomaly")
)

任意 Web API

借助 Spark 上的 HTTP,可以在大数据管道中使用任何 Web 服务。 在此示例中,我们使用 World Bank API 获取有关全球各个国家/地区的信息。

# Use any requests from the python requests library


def world_bank_request(country):
    return Request(
        "GET", "http://api.worldbank.org/v2/country/{}?format=json".format(country)
    )


# Create a dataframe with specifies which countries/regions we want data on
df = spark.createDataFrame([("br",), ("usa",)], ["country"]).withColumn(
    "request", http_udf(world_bank_request)(col("country"))
)

# Much faster for big data because of the concurrency :)
client = (
    HTTPTransformer().setConcurrency(3).setInputCol("request").setOutputCol("response")
)

# Get the body of the response


def get_response_body(resp):
    return resp.entity.content.decode()


# Show the details of the country data returned
display(
    client.transform(df).select(
        "country", udf(get_response_body)(col("response")).alias("response")
    )
)

Azure AI 搜索示例

此示例演示如何使用认知技能扩充数据,并使用 SynapseML 写入 Azure 搜索索引。

search_service = "mmlspark-azure-search"
search_index = "test-33467690"

df = spark.createDataFrame(
    [
        (
            "upload",
            "0",
            "https://mmlspark.blob.core.windows.net/datasets/DSIR/test1.jpg",
        ),
        (
            "upload",
            "1",
            "https://mmlspark.blob.core.windows.net/datasets/DSIR/test2.jpg",
        ),
    ],
    ["searchAction", "id", "url"],
)

tdf = (
    AnalyzeImage()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setImageUrlCol("url")
    .setOutputCol("analyzed")
    .setErrorCol("errors")
    .setVisualFeatures(
        ["Categories", "Tags", "Description", "Faces", "ImageType", "Color", "Adult"]
    )
    .transform(df)
    .select("*", "analyzed.*")
    .drop("errors", "analyzed")
)

tdf.writeToAzureSearch(
    subscriptionKey=search_key,
    actionCol="searchAction",
    serviceName=search_service,
    indexName=search_index,
    keyCol="id",
)

其他教程

以下教程提供了在 Synapse Analytics 中使用 Azure AI 服务的完整示例。

可用的 Azure AI 服务 API

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
必应图像搜索 BingImageSearch 映像 - 视觉搜索 V7.0 不支持

异常检测器

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
检测上次异常 DetectLastAnomaly 检测上一个点 V1.0 支持
检测异常 DetectAnomalies 检测整个系列 V1.0 支持
简单 DetectAnomalies SimpleDetectAnomalies 检测整个系列 V1.0 支持

计算机视觉

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
OCR OCR 识别打印文本 V2.0 支持
识别文本 RecognizeText 识别文本 V2.0 支持
读取映像 ReadImage 读取 V3.1 支持
生成缩略图 GenerateThumbnails 生成缩略图 V2.0 支持
分析图像 AnalyzeImage 分析映像 V2.0 支持
识别特定于域的内容 RecognizeDomainSpecificContent 按域分析映像 V2.0 支持
标记映像 TagImage 标记映像 V2.0 支持
描述图像 DescribeImage 描述映像 V2.0 支持

转换器

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
翻译文本 Translate 翻译 V3.0 不支持
直译文本 Transliterate 直译 V3.0 不支持
检测语言 Detect 检测 V3.0 不支持
断句 BreakSentence 断句 V3.0 不支持
字典查找(替代翻译) DictionaryLookup 字典查找 V3.0 不支持
文档翻译 DocumentTranslator 文档翻译 V1.0 不支持

人脸

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
检测人脸 DetectFace 用 Url 检测 V1.0 支持
查找相似人脸 FindSimilarFace 查找相似 V1.0 支持
分组人脸 GroupFaces 分组 V1.0 支持
标识人脸 IdentifyFaces 标识 V1.0 支持
验证人脸 VerifyFaces 验证人脸到人脸 V1.0 支持

文档智能

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
分析布局 AnalyzeLayout 分析布局 Async V2.1 支持
分析回执 AnalyzeReceipts 分析回执 Async V2.1 支持
分析名片 AnalyzeBusinessCards 分析名片 Async V2.1 支持
分析发票 AnalyzeInvoices 分析 Invoice Async V2.1 支持
分析 ID 文档 AnalyzeIDDocuments 标识 (ID) 文档模型 V2.1 支持
列出自定义模型 ListCustomModels 列出自定义模型 V2.1 支持
获取自定义模型 GetCustomModel 获取自定义模型 V2.1 支持
分析自定义模型 AnalyzeCustomModel 用自定义模型分析 V2.1 支持

语音转文本

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
语音转文本 SpeechToText SpeechToText V1.0 不支持
语音转文本 SDK SpeechToTextSDK 使用 Speech SDK 版本 1.14.0 不支持

文本分析

API 类型 SynapseML API Azure AI 服务 API(版本) DEP VNet 支持
文本情绪 V2 TextSentimentV2 情绪 V2.0 支持
语言检测程序 V2 LanguageDetectorV2 语言 V2.0 支持
实体检测程序 V2 EntityDetectorV2 实体链接 V2.0 支持
NER V2 NERV2 实体识别常规 V2.0 支持
关键短语提取程序 V2 KeyPhraseExtractorV2 关键短语 V2.0 支持
文本情绪 TextSentiment 情绪 V3.1 支持
关键短语提取程序 KeyPhraseExtractor 关键短语 V3.1 支持
PII PII 实体识别 Pii V3.1 支持
NER NER 实体识别常规 V3.1 支持
语言检测程序 LanguageDetector 语言 V3.1 支持
实体检测程序 EntityDetector 实体链接 V3.1 支持

后续步骤