共用方式為


教學課程:使用 Synapse Machine Learning 建置機器學習應用程式

在本文中,您將了解如何使用 Synapse Machine Learning (SynapseML) 來建立機器學習應用程式。 SynapseML 藉由新增許多深度學習和資料科學工具 (例如 Azure AI 服務OpenCVLightGBM 等),來擴充 Apache Spark 的分散式機器學習解決方案。 SynapseML 可讓您從各種 Spark 資料來源建置功能強大且可調整程度高的預測和分析模型。 Synapse Spark 提供內建的 SynapseML 程式庫,包括:

  • Vowpal Wabbit – 適用於機器學習的程式庫服務,可啟用推文中的文字分析,例如情感分析。
  • MMLSpark:大規模整合機器學習生態系統 – 結合 SparkML 管線中的 Azure AI 服務功能,以衍生認知資料模型化服務的解決方案設計,例如異常偵測。
  • LightGBM – LightGBM 是使用樹狀型學習演算法的漸層提升架構。 其的設計旨在分散和提高效率。
  • 條件式 KNN - 具有條件式查詢的可調整 KNN 模型。
  • Spark 上的 HTTP – 可讓分散式微服務協調流程整合 Spark 和 HTTP 通訊協定型協助工具。

此教學課程涵蓋在 MMLSpark 中使用 Azure  AI 服務,進行下列動作的範例

  • 文字分析 - 取得一組句子的情感 (或情緒)。
  • 電腦視覺 - 取得與一組影像相關聯的標記 (單字描述)。
  • Bing 影像搜尋 - 在 Web 上搜尋與自然語言查詢相關的影像。
  • 異常偵測器 - 偵測時間序列資料中的異常。

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

必要條件

開始使用

若要開始使用,請匯入 SynapseML 並設定服務金鑰。

import synapse.ml
from synapse.ml.cognitive import *
from notebookutils import mssparkutils

# An Azure AI services multi-service resource key for Text Analytics and Computer Vision (or use separate keys that belong to each service)
ai_service_key = mssparkutils.credentials.getSecret("ADD_YOUR_KEY_VAULT_NAME", "ADD_YOUR_SERVICE_KEY","ADD_YOUR_KEY_VAULT_LINKED_SERVICE_NAME") 
# A Bing Search v7 subscription key
bingsearch_service_key = mssparkutils.credentials.getSecret("ADD_YOUR_KEY_VAULT_NAME", "ADD_YOUR_BING_SEARCH_KEY","ADD_YOUR_KEY_VAULT_LINKED_SERVICE_NAME")
# An Anomaly Detector subscription key
anomalydetector_key = mssparkutils.credentials.getSecret("ADD_YOUR_KEY_VAULT_NAME", "ADD_YOUR_ANOMALY_KEY","ADD_YOUR_KEY_VAULT_LINKED_SERVICE_NAME")

文字分析範例

文字分析服務提供數種演算法,可從文字中擷取智慧型深入解析。 例如,我們可以找到指定輸入文字的情感。 服務會傳回介於 0.0 和 1.0 之間的分數,低分表示負面情感,而高分表示正面情感。 此範例會使用三個簡單的句子,並傳回每個句子的情感。

from pyspark.sql.functions import col

# Create a dataframe that's tied to it's column names
df_sentences = spark.createDataFrame([
  ("I am so happy today, its sunny!", "en-US"), 
  ("this is a dog", "en-US"), 
  ("I am frustrated by this rush hour traffic!", "en-US") 
], ["text", "language"])

# Run the Text Analytics service with options
sentiment = (TextSentiment()
    .setTextCol("text")
    .setLocation("eastasia") # Set the location of your Azure AI services resource
    .setSubscriptionKey(ai_service_key)
    .setOutputCol("sentiment")
    .setErrorCol("error")
    .setLanguageCol("language"))

# Show the results of your text query in a table format

display(sentiment.transform(df_sentences).select("text", col("sentiment")[0].getItem("sentiment").alias("sentiment")))

預期的結果

text 情感
我因為此尖峰時間的交通感到沮喪!(I am frustrated by this rush hour traffic!) negative
這是一隻狗 (this is a dog) neutral
今天我很高興,天氣真晴朗!(I am so happy today, its sunny!) positive

電腦視覺範例

電腦視覺會分析影像,以識別臉部、物件和自然語言描述等結構。 在此範例中,我們會標記下列影像。 標記是影像中事項的單字描述,例如可辨識的物件、人員、景象和動作。

image

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

# Run the Computer Vision service. Analyze Image extracts information from/about the images.
analysis = (AnalyzeImage()
    .setLocation("eastasia") # Set the location of your Azure AI services resource
    .setSubscriptionKey(ai_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_images).select("image", "analysis_results.description.tags"))

預期的結果

image 標記
https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/objects.jpg [skating, person, man, outdoor, riding, sport, skateboard, young, board, shirt, air, park, boy, side, jumping, ramp, trick, doing, flying]

Bing 影像搜尋範例

Bing 影像搜尋會搜尋 Web,以擷取與使用者的自然語言查詢相關的影像。 在此範例中,我們會使用文字查詢來尋找引號中的影像。 其會傳回影像 URL 清單,其中包含與查詢相關的相片。

from pyspark.ml import PipelineModel

# Number of images Bing will return per query
imgsPerBatch = 2
# A list of offsets, used to page into the search results
offsets = [(i*imgsPerBatch,) for i in range(10)]
# 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(bingsearch_service_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")
pipeline_bingsearch = PipelineModel(stages=[bingSearch, getUrls])

# Show the results of your search: image URLs
res_bingsearch = pipeline_bingsearch.transform(bingParameters)
display(res_bingsearch.dropDuplicates())

預期的結果

image
http://everydaypowerblog.com/wp-content/uploads/2014/01/Martin-Luther-King-Jr.-Quotes-16.jpg
http://www.scrolldroll.com/wp-content/uploads/2017/06/6-25.png
http://abettertodaymedia.com/wp-content/uploads/2017/01/86783bd7a92960aedd058c91a1d10253.jpg
https://weneedfun.com/wp-content/uploads/2016/05/martin-luther-king-jr-quotes-11.jpg
http://www.sofreshandsogreen.com/wp-content/uploads/2012/01/martin-luther-king-jr-quote-sofreshandsogreendotcom.jpg
https://cdn.quotesgram.com/img/72/57/1104209728-martin_luther_king_jr_quotes_16.jpg
http://comicbookandbeyond.com/wp-content/uploads/2019/05/Martin-Luther-King-Jr.-Quotes.jpg
https://exposingthepain.files.wordpress.com/2015/01/martin-luther-king-jr-quotes-08.png
https://topmemes.me/wp-content/uploads/2020/01/Top-10-Martin-Luther-King-jr.-Quotes2-1024x538.jpg
http://img.picturequotes.com/2/581/580286/dr-martin-luther-king-jr-quote-1-picture-quote-1.jpg
http://parryz.com/wp-content/uploads/2017/06/Amazing-Martin-Luther-King-Jr-Quotes.jpg
http://everydaypowerblog.com/wp-content/uploads/2014/01/Martin-Luther-King-Jr.-Quotes1.jpg
https://lessonslearnedinlife.net/wp-content/uploads/2020/05/Martin-Luther-King-Jr.-Quotes-2020.jpg
https://quotesblog.net/wp-content/uploads/2015/10/Martin-Luther-King-Jr-Quotes-Wallpaper.jpg

異常偵測器範例

異常偵測器非常適合用來偵測時間序列資料中的異常狀況。 在此範例中,我們會使用該服務來尋找整個時間序列中的異常。

from pyspark.sql.functions import lit

# Create a dataframe with the point data that Anomaly Detector requires
df_timeseriesdata = 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), # anomaly
    ("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) # anomaly
], ["timestamp", "value"]).withColumn("group", lit("series1"))

# Run the Anomaly Detector service to look for irregular data
anomaly_detector = (SimpleDetectAnomalies()
  .setSubscriptionKey(anomalydetector_key)
  .setLocation("eastasia")
  .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_timeseriesdata).select("timestamp", "value", "anomalies.isAnomaly"))

預期的結果

timestamp value 是否異常
1972-01-01T00:00:00Z 826.0 false
1972-02-01T00:00:00Z 799.0 false
1972-03-01T00:00:00Z 890.0 false
1972-04-01T00:00:00Z 900.0 false
1972-05-01T00:00:00Z 766.0 false
1972-06-01T00:00:00Z 805.0 false
1972-07-01T00:00:00Z 821.0 false
1972-08-01T00:00:00Z 20000.0 true
1972-09-01T00:00:00Z 883.0 false
1972-10-01T00:00:00Z 898.0 false
1972-11-01T00:00:00Z 957.0 false
1972-12-01T00:00:00Z 924.0 false
1973-01-01T00:00:00Z 881.0 false
1973-02-01T00:00:00Z 837.0 false
1973-03-01T00:00:00Z 9000.0 true

語音轉文字範例

語音轉換文字服務會將說話音訊的串流或檔案轉換成文字。 在此範例中,我們會將一個音訊檔轉錄為文字。

# 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("northeurope") # Set the location of your Azure AI services resource
    .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"))

預期的結果

URL DisplayText
https://mmlspark.blob.core.windows.net/datasets/Speech/audio2.wav 自訂語音提供的工具可讓您比較音訊資料與自訂語音入口網站中的對應辨識結果,透過視覺化方式檢查模型的辨識品質。(Custom speech provides tools that allow you to visually inspect the recognition quality of a model by comparing audio data with the corresponding recognition result from the custom speech portal.) 您可以播放上傳的音訊,並判斷提供的辨識結果是否正確。(You can playback uploaded audio and determine if the provided recognition result is correct.) 此工具可讓您快速檢查 Microsoft 的基準語音轉換文字模型品質或定型的自訂模型,而不需要轉譯任何音訊資料。(This tool allows you to quickly inspect quality of Microsoft's baseline speech to text model or a trained custom model without having to transcribe any audio data.)

清除資源

為確保 Spark 執行個體已關閉,請結束任何已連線的工作階段 (Notebook)。 當達到 Apache Spark 集區中指定的閒置時間時,集區就會關閉。 您也可以在筆記本右上方的狀態列,選取 [停止工作階段]

顯示停止工作階段的螢幕快照

下一步