Azure AI 服务
Azure AI 服务帮助开发者和组织快速创建智能、前沿、市场就绪且负责任的应用程序,提供开箱即用、预构建且可定制的 API 和模型。
SynapseML 允许您从各种 Spark 数据源构建强大且高度可扩展的预测和分析模型。Synapse Spark 提供了内置的 SynapseML 库,包括 synapse.ml.services。
重要
从2023年9月20日开始,您将无法创建新的异常检测器资源。异常检测器服务将于2026年10月1日停用。
Azure Databricks 上的先决条件
- 按照入门指南中的步骤设置您的Azure Databricks和Azure AI服务环境。本教程将向您展示如何安装SynapseML以及如何在Databricks中创建您的Spark集群。
- 在 Azure Databricks 中创建新笔记本后,复制下面的共享代码并粘贴到笔记本的新单元格中。
- 选择一个服务示例,如下所示,并将其复制粘贴到您的笔记本中的第二个新单元格中。
- 将任何服务订阅密钥占位符替换为您自己的密钥。
- 选择单元格右上角的运行按钮(三角形图标),然后选择运行单元格。
- 在单元格下方的表格中查看结果。
Azure Synapse Analytics 的先决条件
教程在Azure Synapse中使用Azure AI服务的前提条件,将引导您完成在Synapse Analytics中使用Azure AI服务之前需要执行的几个步骤。
Azure AI services 是一套API、SDK和服务,开发者可以使用它们为应用程序添加智能功能。即使开发者没有直接的AI或数据科学技能或知识,AI服务也能赋予他们能力。Azure AI服务帮助开发者创建能够看、听、说、理解甚至开始推理的应用程序。Azure AI服务中的服务目录可以分为五大支柱:视觉、语音、语言、网络搜索和决策。
用法
愿景
- 描述:以人类可读的语言提供图像的描述 (Scala, Python)
- 分析(颜色、图像类型、面部、成人/色情内容):分析图像的视觉特征(Scala, Python)
- OCR: 从图像中读取文本 (Scala, Python)
- 识别文本:从图像中读取文本 (Scala, Python)
- 缩略图:从图像生成用户指定大小的缩略图 (Scala, Python)
- 识别特定领域内容:识别特定领域内容(名人、地标)(Scala, Python)
- 标签:识别与输入图像相关的单词列表(Scala, Python)
- 检测:检测图像中的人脸 (Scala, Python)
- 验证:验证两张脸是否属于同一个人,或者一张脸是否属于一个人 (Scala, Python)
- 识别:从一个人群组中找到特定查询人脸的最近匹配项(Scala, Python)
- 查找相似:在面部列表中查找与查询面部相似的面部(Scala, Python)
- 组:根据相似性将一组面部分割成不相交的组 (Scala, Python)
演讲
- 语音转文字:转录音频流 (Scala, Python)
- 对话转录:将音频流转录为带有识别发言者的实时文字记录。(Scala, Python)
- 文本转语音:将文本转换为逼真的音频 (Scala, Python)
语言
- 语言检测:检测输入文本的语言(Scala, Python)
- 关键词提取:识别输入文本中的关键讨论点(Scala, Python)
- 命名实体识别:识别输入文本中的已知实体和通用命名实体(Scala, Python)
- 情感分析:返回一个介于0和1之间的分数,表示输入文本中的情感(Scala, Python)
- 医疗实体提取:从文本中提取医疗实体和关系。(Scala, Python)
翻译
- 翻译:翻译文本。(Scala, Python)
- 音译:将一种语言的文本从一种文字转换为另一种文字。(Scala, Python)
- 检测:识别一段文本的语言。(Scala, Python)
- BreakSentence: 识别一段文本中句子边界的位置。(Scala, Python)
- 字典查找:为单词和少量惯用短语提供替代翻译。(Scala, Python)
- 字典示例:提供展示字典中的术语在上下文中如何使用的示例。(Scala, Python)
- 文档翻译:在所有支持的语言和方言之间翻译文档,同时保留文档结构和数据格式。(Scala, Python)
文档智能
- 分析布局:从给定文档中提取文本和布局信息。(Scala, Python)
- 分析收据:使用光学字符识别(OCR)和我们的收据模型检测并提取收据中的数据,使您能够轻松提取收据中的结构化数据,如商家名称、商家电话号码、交易日期、交易总额等。(Scala, Python)
- 分析名片:使用光学字符识别(OCR)和我们的名片模型检测并提取名片中的数据,使您能够轻松地从名片中提取结构化数据,如联系人姓名、公司名称、电话号码、电子邮件等。(Scala, Python)
- 分析发票:使用光学字符识别(OCR)和我们的发票理解深度学习模型检测和提取发票中的数据,使您能够轻松地从发票中提取结构化数据,如客户、供应商、发票ID、发票到期日、总额、应付发票金额、税额、发货地址、账单地址、行项目等。(Scala, Python)
- 分析身份证件:使用光学字符识别(OCR)和我们的身份证件模型检测并提取身份证件中的数据,使您能够轻松地从身份证件中提取结构化数据,如名字、姓氏、出生日期、证件号码等。(Scala, Python)
- 分析自定义表单:从表单(PDF和图像)中提取信息,基于一组代表性训练表单创建的模型,将其转换为结构化数据。(Scala, Python)
- 获取自定义模型:获取有关自定义模型的详细信息。(Scala, Python)
- 列出自定义模型:获取所有自定义模型的信息。(Scala, Python)
决策
搜索
准备您的系统
首先,导入所需的库并初始化您的Spark会话。
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
导入 Azure AI 服务库,并将以下代码片段中的密钥和位置替换为您的 Azure AI 服务密钥和位置。
from synapse.ml.services import *
from synapse.ml.core.platform import *
# A general AI services key for AI Language, Computer Vision and Document Intelligence (or use separate keys that belong to each service)
service_key = find_secret(
secret_name="ai-services-api-key", keyvault="mmlspark-build-keys"
) # Replace the call to find_secret with your key as a python string. e.g. service_key="27snaiw..."
service_loc = "eastus"
# A Bing Search v7 subscription key
bing_search_key = find_secret(
secret_name="bing-search-key", keyvault="mmlspark-build-keys"
) # Replace the call to find_secret with your key as a python string.
# An Anomaly Detector subscription key
anomaly_key = find_secret(
secret_name="anomaly-api-key", keyvault="mmlspark-build-keys"
) # Replace the call to find_secret with your key as a python string. If you don't have an anomaly detection resource created before Sep 20th 2023, you won't be able to create one.
anomaly_loc = "westus2"
# A Translator subscription key
translator_key = find_secret(
secret_name="translator-key", keyvault="mmlspark-build-keys"
) # Replace the call to find_secret with your key as a python string.
translator_loc = "eastus"
# An Azure search key
search_key = find_secret(
secret_name="azure-search-key", keyvault="mmlspark-build-keys"
) # Replace the call to find_secret with your key as a python string.
对文本进行情感分析
AI Language 服务提供了多种算法,用于从文本中提取智能洞察。例如,我们可以找到给定输入文本的情感。该服务将返回一个介于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 AI services on spark aint bad", "en-US"),
],
["text", "language"],
)
# Run the Text Analytics service with options
sentiment = (
AnalyzeText()
.setKind("SentimentAnalysis")
.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.documents.sentiment").alias("sentiment")
)
)
对健康数据进行文本分析
Text Analytics for Health Service 从非结构化文本(如医生的笔记、出院摘要、临床文档和电子健康记录)中提取并标记相关的医疗信息。
以下代码示例分析并将医生笔记中的文本转换为结构化数据。
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))
将文本翻译成不同的语言
Translator 是一个基于云的机器翻译服务,属于用于构建智能应用程序的 Azure AI 服务系列 AI API 的一部分。Translator 易于集成到您的应用程序、网站、工具和解决方案中。它允许您添加 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 Document Intelligence 是 Azure 应用人工智能服务的一部分,它允许您使用机器学习技术构建自动化数据处理软件。通过 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 Form Recognizer 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")
)
计算机视觉示例
Azure AI Vision 分析图像以识别结构,如人脸、物体和自然语言描述。
以下代码示例分析图像并使用标签对其进行标记。标签是图像中事物的一词描述,例如可识别的物体、人物、风景和动作。
# 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 Image Search 搜索网络以检索与用户的自然语言查询相关的图像。
以下代码示例使用了一个文本查询,该查询寻找带有引号的图像。代码的输出是一个包含与查询相关的照片的图像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))
将语音转换为文本
Speech-to-text 服务将语音音频流或文件转换为文本。以下代码示例将一个音频文件转录为文本。
# 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"))
将文本转换为语音
Text to speech 是一项服务,允许您构建能够自然说话的应用程序和服务,从119种语言和变体中的270多种神经语音中进行选择。
以下代码示例将文本转换为包含文本内容的音频文件。
from synapse.ml.services.speech 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))
检测时间序列数据中的异常
如果您在2023年9月20日之前没有创建异常检测资源,您将无法创建一个。您可能想跳过这一部分。
Anomaly Detector 非常适合检测时间序列数据中的异常。以下代码示例使用 Anomaly Detector 服务来查找时间序列中的异常。
# 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
anamoly_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(
anamoly_detector.transform(df).select("timestamp", "value", "anomalies.isAnomaly")
)
从任意网络API获取信息
使用Spark上的HTTP,任何网络服务都可以用于您的大数据管道。在这个例子中,我们使用世界银行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 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",
)