Azure Synapse Analytics 中的 Azure AI 服務

您可以使用 Azure AI 服務的預先訓練模型,在 Azure Synapse Analytics 中利用人工智慧 (AI) 來擴充資料。

Azure AI 服務可協助開發人員和組織使用現成、預先建置且可自訂的 API 和模型,快速建立智慧型、最先進的市場就緒及負責任應用程式。

您可以透過幾種方式搭配使用 Azure AI 服務的子集與 Synapse Analytics 中的資料:

  • Synapse Analytics 中的「Azure AI 服務」精靈會在 Synapse 筆記本中產生 PySpark 程式碼,其使用 Spark 資料表中的資料連線到 Azure AI 服務。 然後,服務會使用預先訓練的機器學習模型,為您將 AI 新增至資料中。 如需詳細資料,請參閱情感分析精靈異常偵測精靈

  • Synapse Machine Learning (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)

Speech

語音服務

  • 語音轉換文字:轉譯音訊串流 (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) 和發票理解深度學習模型,偵測並擷取發票的資料,讓您輕鬆擷取發票的結構化資料,例如客戶、供應商、發票識別碼、發票到期日、總額、發票應付金額、稅額、收件人、付款人、明細項目等。 (ScalaPython)
  • 分析身分證明文件:使用光學字元辨識 (OCR) 和身分證明文件模型偵測並擷取身份證明文件的資料,讓您輕鬆擷取身份證明文件的結構化資料,例如名字、姓氏、出生日期、文件編號等。 (ScalaPython)
  • 分析自訂表單:根據從一組代表性定型表單建立的模型,從表單 (PDF 和影像) 擷取資訊到結構化資料。 (ScalaPython)
  • 取得自訂模型:取得自訂模型的詳細資訊。 (ScalaPython)
  • 列出自訂模型:取得所有自訂模型的相關資訊。 (ScalaPython)

Decision

異常偵測器

  • 最新點的異常狀態:使用上述點產生模型,並判斷最新點是否異常 (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"))

Bing 影像搜尋範例

Bing 影像搜尋會搜尋 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 支援
Bing 影像搜尋 BingImageSearch 影像 - 圖像式搜尋 V7.0 不支援

異常偵測器

API 類型 SynapseML API Azure AI 服務 API (版本) DEP VNet 支援
偵測到最後一項異常 DetectLastAnomaly Detect Last Point V1.0 支援
偵測異常 DetectAnomalies Detect Entire Series V1.0 支援
簡單 DetectAnomalies SimpleDetectAnomalies Detect Entire Series V1.0 支援

電腦視覺

API 類型 SynapseML API Azure AI 服務 API (版本) DEP VNet 支援
OCR OCR Recognize Printed Text V2.0 支援
辨識文字 RecognizeText Recognize Text V2.0 支援
讀取影像 ReadImage Read V3.1 支援
產生縮圖 GenerateThumbnails Generate Thumbnail V2.0 支援
分析影像 AnalyzeImage Analyze Image V2.0 支援
辨識領域特定內容 RecognizeDomainSpecificContent Analyze Image By Domain V2.0 支援
標記影像 TagImage Tag Image V2.0 支援
描述影像 DescribeImage Describe Image V2.0 支援

Translator

API 類型 SynapseML API Azure AI 服務 API (版本) DEP VNet 支援
翻譯文字 翻譯 Translate V3.0 不支援
音譯文字 Transliterate Transliterate V3.0 不支援
偵測語言 偵測 Detect V3.0 不支援
中斷文句 BreakSentence Break Sentence V3.0 不支援
字典查閱 (替代翻譯) DictionaryLookup Dictionary Lookup V3.0 不支援
文件翻譯 DocumentTranslator Document Translation V1.0 不支援

臉部

API 類型 SynapseML API Azure AI 服務 API (版本) DEP VNet 支援
偵測臉部 DetectFace Detect With Url V1.0 支援
尋找類似臉部 FindSimilarFace Find Similar V1.0 支援
將臉部分組 GroupFaces Group V1.0 支援
識別臉部 IdentifyFaces Identify V1.0 支援
驗證臉部 VerifyFaces Verify Face To Face V1.0 支援

文件智慧服務

API 類型 SynapseML API Azure AI 服務 API (版本) DEP VNet 支援
分析版面配置 AnalyzeLayout Analyze Layout Async V2.1 支援
分析收據 AnalyzeReceipts Analyze Receipt Async V2.1 支援
分析名片 AnalyzeBusinessCards Analyze Business Card Async V2.1 支援
分析發票 AnalyzeInvoices Analyze Invoice Async V2.1 支援
分析身分證明文件 AnalyzeIDDocuments identification (ID) document model V2.1 支援
列出自訂模型 ListCustomModels List Custom Models V2.1 支援
取得自訂模型 GetCustomModel Get Custom Models V2.1 支援
分析自訂模型 AnalyzeCustomModel Analyze With Custom Model 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 支援
Text Sentiment V2 TextSentimentV2 Sentiment V2.0 支援
Language Detector V2 LanguageDetectorV2 Languages V2.0 支援
Entity Detector V2 EntityDetectorV2 Entities Linking V2.0 支援
NER V2 NERV2 Entities Recognition General V2.0 支援
Key Phrase Extractor V2 KeyPhraseExtractorV2 Key Phrases V2.0 支援
文字情感 TextSentiment Sentiment V3.1 支援
關鍵片語擷取器 KeyPhraseExtractor Key Phrases V3.1 支援
PII PII Entities Recognition Pii V3.1 支援
NER NER Entities Recognition General V3.1 支援
語言偵測器 LanguageDetector Languages V3.1 支援
實體偵測器 EntityDetector Entities Linking V3.1 支援

下一步