Ejemplos de Python para Cognitive Services para macrodatos
Los siguientes fragmentos están listos para ejecutarse y le ayudarán a empezar a usar Cognitive Services en Spark con Python.
En los ejemplos de este artículo se usan estos servicios de Cognitive Services:
- Language Service: para obtener la opinión (o el estado de ánimo) de un conjunto de frases.
- Computer Vision: para obtener las etiquetas (descripciones de una sola palabra) asociadas a un conjunto de imágenes.
- Bing Image Search: para buscar en la Web las imágenes relacionadas con una consulta en lenguaje natural.
- Speech to Text: transcripción de archivos de audio para extraer transcripciones basadas en texto.
- Anomaly Detector: para detectar anomalías en los datos de una serie temporal.
Requisitos previos
- Siga los pasos descritos en Introducción para configurar el entorno de Azure Databricks y Cognitive Services. En este tutorial se muestra cómo instalar MMLSpark y cómo crear el clúster de Spark en Databricks.
- Después de crear un nuevo cuaderno en Azure Databricks, copie el siguiente código compartido y péguelo en una nueva celda del cuaderno.
- Elija un ejemplo de servicio de entre los que se muestran a continuación y cópielo y péguelo en una segunda celda nueva del cuaderno.
- Reemplace cualquiera de los marcadores de posición de la clave de suscripción del servicio por su propia clave.
- Elija el botón Ejecutar (icono de triángulo) en la esquina superior derecha de la celda y, a continuación, seleccione Ejecutar celda.
- Puede ver los resultados en una tabla debajo de la celda.
Código compartido
Para empezar, es necesario agregar este código al proyecto:
from mmlspark.cognitive import *
# A general Cognitive Services key for the Language service and Computer Vision (or use separate keys that belong to each service)
service_key = "ADD_YOUR_SUBSCRIPION_KEY"
# A Bing Search v7 subscription key
bing_search_key = "ADD_YOUR_SUBSCRIPION_KEY"
# An Anomaly Dectector subscription key
anomaly_key = "ADD_YOUR_SUBSCRIPION_KEY"
# Validate the key
assert service_key != "ADD_YOUR_SUBSCRIPION_KEY"
Ejemplo del servicio de lenguaje
El servicio Language Service proporciona varios algoritmos para extraer conclusiones inteligentes de un texto. Por ejemplo, podemos encontrar la opinión de un texto de entrada determinado. El servicio devolverá una puntuación entre 0,0 y 1,0, donde las puntuaciones bajas indican una opinión negativa y una puntuación alta indica una opinión positiva. Este ejemplo utiliza tres frases simples y devuelve la opinión de cada una.
from pyspark.sql.functions import col
# 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 cognitive services on spark aint bad", "en-US"),
], ["text", "language"])
# Run the Language service with options
sentiment = (TextSentiment()
.setTextCol("text")
.setLocation("eastus")
.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")[0].getItem("sentiment").alias("sentiment")))
Resultado esperado
| text | opinión |
|---|---|
| I am so happy today, its sunny! (Hoy estoy muy feliz, el día está soleado) | positiva |
| I am frustrated by this rush hour traffic (Estoy frustrado por el tráfico de la hora punta) | negativa |
| The cognitive services on spark aint bad (Cognitive Services en Spark no está nada mal) | positiva |
Ejemplo de Computer Vision
Computer Vision analiza las imágenes para identificar estructuras como caras, objetos y descripciones en lenguaje natural. En este ejemplo, se etiqueta una lista de imágenes. Las etiquetas son descripciones de una sola palabra de las cosas que hay en la imagen, como objetos reconocibles, personas, escenarios y acciones.
# Create a dataframe with the image URLs
df = spark.createDataFrame([
("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/objects.jpg", ),
("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/dog.jpg", ),
("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/house.jpg", )
], ["image", ])
# Run the Computer Vision service. Analyze Image extracts infortmation from/about the images.
analysis = (AnalyzeImage()
.setLocation("eastus")
.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"))
Resultado esperado
| imagen | etiquetas |
|---|---|
| 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' 'black' 'park' 'boy' 'side' 'jumping' 'trick' 'ramp' 'doing' 'flying'] |
| https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/dog.jpg | ['dog' 'outdoor' 'fence' 'wooden' 'small' 'brown' 'building' 'sitting' 'front' 'bench' 'standing' 'table' 'walking' 'board' 'beach' 'white' 'holding' 'bridge' 'track'] |
| https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/house.jpg | ['outdoor' 'grass' 'house' 'building' 'old' 'home' 'front' 'small' 'church' 'stone' 'large' 'grazing' 'yard' 'green' 'sitting' 'leading' 'sheep' 'brick' 'bench' 'street' 'white' 'country' 'clock' 'sign' 'parked' 'field' 'standing' 'garden' 'water' 'red' 'horse' 'man' 'tall' 'fire' 'group'] |
Ejemplo de Bing Image Search
Bing Image Search busca en la Web para recuperar las imágenes relacionadas con una consulta en lenguaje natural del usuario. En este ejemplo, usamos una consulta de texto que busca imágenes con citas de un personaje célebre. Devuelve una lista de direcciones URL de las imágenes que contienen fotos relacionadas con la consulta.
from pyspark.ml import PipelineModel
# 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))
Resultado esperado
Ejemplo de Speech to Text
El servicio Speech to Text convierte secuencias o archivos de audio hablado en texto. En este ejemplo, se transcriben dos archivos de audio. El primer archivo es fácil de entender y el segundo es más desafiante.
# 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",),
("https://mmlspark.blob.core.windows.net/datasets/Speech/audio3.mp3",)
], ["url"])
# Run the Speech-to-text service to translate the audio into text
speech_to_text = (SpeechToTextSDK()
.setSubscriptionKey(service_key)
.setLocation("eastus")
.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"))
Resultado esperado
| url | Texto para mostrar |
|---|---|
| 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. 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. |
| https://mmlspark.blob.core.windows.net/datasets/Speech/audio3.mp3 | Add a gentleman Sir thinking visual check. |
| https://mmlspark.blob.core.windows.net/datasets/Speech/audio3.mp3 | I hear me. |
| https://mmlspark.blob.core.windows.net/datasets/Speech/audio3.mp3 | I like the reassurance for radio that I can hear it as well. |
Ejemplo de Anomaly Detector
Anomaly Detector es ideal para detectar irregularidades en los datos de series temporales. En este ejemplo, usamos el servicio para buscar anomalías en toda la serie temporal.
from pyspark.sql.functions import lit
# 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("eastus")
.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"))
Resultado esperado
| timestamp | value | isAnomaly |
|---|---|---|
| 1972-01-01T00:00:00Z | 826 | False |
| 1972-02-01T00:00:00Z | 799 | False |
| 1972-03-01T00:00:00Z | 890 | False |
| 1972-04-01T00:00:00Z | 900 | False |
| 1972-05-01T00:00:00Z | 766 | False |
| 1972-06-01T00:00:00Z | 805 | False |
| 1972-07-01T00:00:00Z | 821 | False |
| 1972-08-01T00:00:00Z | 20000 | True |
| 1972-09-01T00:00:00Z | 883 | False |
| 1972-10-01T00:00:00Z | 898 | False |
| 1972-11-01T00:00:00Z | 957 | False |
| 1972-12-01T00:00:00Z | 924 | False |
| 1973-01-01T00:00:00Z | 881 | False |
| 1973-02-01T00:00:00Z | 837 | False |
| 1973-03-01T00:00:00Z | 9000 | True |
API web arbitrarias
Con HTTP en Spark, se puede usar cualquier servicio web en la canalización de macrodatos. En este ejemplo, usamos la API de World Bank para obtener información sobre varios países de todo el mundo.
from requests import Request
from mmlspark.io.http import HTTPTransformer, http_udf
from pyspark.sql.functions import udf, col
# 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 spcificies 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")))
Resultado esperado
| country | respuesta |
|---|---|
| br | [{"page":1,"pages":1,"per_page":"50","total":1},[{"id":"BRA","iso2Code":"BR","name":"Brazil","region":{"id":"LCN","iso2code":"ZJ","value":"Latin America & Caribbean "},"adminregion":{"id":"LAC","iso2code":"XJ","value":"Latin America & Caribbean (excluding high income)"},"incomeLevel":{"id":"UMC","iso2code":"XT","value":"Upper middle income"},"lendingType":{"id":"IBD","iso2code":"XF","value":"IBRD"},"capitalCity":"Brasilia","longitude":"-47.9292","latitude":"-15.7801"}]] |
| usa | [{"page":1,"pages":1,"per_page":"50","total":1},[{"id":"USA","iso2Code":"US","name":"United States","region":{"id":"NAC","iso2code":"XU","value":"North America"},"adminregion":{"id":"","iso2code":"","value":""},"incomeLevel":{"id":"HIC","iso2code":"XD","value":"High income"},"lendingType":{"id":"LNX","iso2code":"XX","value":"Not classified"},"capitalCity":"Washington D.C.","longitude":"-77.032","latitude":"38.8895"}]] |