Realiza análisis semánticos con funciones de IA administradas
En este instructivo, se muestra cómo usar las funciones de IA administradas de BigQuery ML para realizar un análisis semántico de los comentarios de los clientes.
Objetivos
En este instructivo, harás lo siguiente:
- Crea un conjunto de datos y carga datos de opiniones en una tabla
- Usa las siguientes funciones de IA para realizar el análisis semántico:
AI.IF: Para filtrar tus datos con condiciones de lenguaje naturalAI.SCORE: para calificar la entrada según el sentimientoAI.CLASSIFY: Para clasificar la entrada en categorías definidas por el usuario
Costos
En este instructivo, se usan los siguientes componentes facturables de Google Cloud:
- BigQuery
- BigQuery ML
Para obtener más información sobre los costos de BigQuery, consulta la página Precios de BigQuery.
Para obtener más información sobre los costos de BigQuery ML, consulta los precios de BigQuery ML.
Antes de comenzar
- Accede a tu cuenta de Google Cloud . Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Habilita la API de BigQuery.
Roles necesarios para habilitar las APIs
Para habilitar las APIs, necesitas el rol de IAM de administrador de Service Usage (
roles/serviceusage.serviceUsageAdmin), que contiene el permisoserviceusage.services.enable. Obtén más información para otorgar roles.Para los proyectos nuevos, la API de BigQuery se habilita de forma automática.
- Opcional: Habilita la facturación para el proyecto. Si no deseas habilitar la facturación ni proporcionar una tarjeta de crédito, los pasos que se indican en este documento seguirán funcionando. BigQuery proporciona una zona de pruebas para realizar los pasos. Para obtener más información, consulta Habilita la zona de pruebas de BigQuery.
Roles obligatorios
Para obtener los permisos que necesitas para usar las funciones basadas en IA, pídele a tu administrador que te otorgue los siguientes roles de IAM en el proyecto:
-
Ejecutar trabajos de consulta y trabajos de carga:
Usuario de trabajo de BigQuery (
roles/bigquery.jobUser) -
Crear un conjunto de datos, crear una tabla, cargar datos en una tabla y consultar una tabla:
Editor de datos de BigQuery (
roles/bigquery.dataEditor)
Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.
También puedes obtener los permisos necesarios a través de roles personalizados o cualquier otro rol predefinido.
Crea datos de muestra
Para crear un conjunto de datos llamado my_dataset para este instructivo, ejecuta la siguiente consulta.
CREATE SCHEMA my_dataset OPTIONS (location = 'LOCATION');
A continuación, crea una tabla llamada customer_feedback que contenga muestras de opiniones de clientes sobre un dispositivo:
CREATE TABLE my_dataset.customer_feedback AS (
SELECT
*
FROM
UNNEST( [STRUCT<review_id INT64, review_text STRING>
(1, "The battery life is incredible, and the screen is gorgeous! Best phone I've ever had. Totally worth the price."),
(2, "Customer support was a nightmare. It took three weeks for my order to arrive, and when it did, the box was damaged. Very frustrating!"),
(3, "The product does exactly what it says on the box. No complaints, but not exciting either."),
(4, "I'm so happy with this purchase! It arrived early and exceeded all my expectations. The quality is top-notch, although the setup was a bit tricky."),
(5, "The price is a bit too high for what you get. The material feels cheap and I'm worried it won't last. Service was okay."),
(6, "Absolutely furious! The item arrived broken, and getting a refund is proving impossible. I will never buy from them again."),
(7, "This new feature for account access is confusing. I can't find where to update my profile. Please fix this bug!"),
(8, "The shipping was delayed, but the support team was very helpful and kept me informed. The product itself is great, especially for the price.")
])
);
Categoriza la opinión general
Puede ser útil extraer la opinión general expresada en el texto para admitir casos de uso como los siguientes:
- Evalúa la satisfacción del cliente a partir de las opiniones.
- Supervisar la percepción de la marca en las redes sociales
- Prioriza los tickets de asistencia según el nivel de molestia de los usuarios.
La siguiente consulta muestra cómo usar la función AI.CLASSIFY para clasificar las opiniones de la tabla customer_feedback como positivas, negativas o neutrales:
SELECT
review_id,
review_text,
AI.CLASSIFY(
review_text,
categories => ['positive', 'negative', 'neutral']) AS sentiment
FROM
my_dataset.customer_feedback;
El resultado es similar al siguiente:
+-----------+------------------------------------------+-----------+ | review_id | review_text | sentiment | +-----------+------------------------------------------+-----------+ | 7 | This new feature for account access is | negative | | | confusing. I can't find where to update | | | | my profile. Please fix this bug! | | +-----------+------------------------------------------+-----------+ | 4 | "I'm so happy with this purchase! It | positive | | | arrived early and exceeded all my | | | | expectations. The quality is top-notch, | | | | although the setup was a bit tricky." | | +-----------+------------------------------------------+-----------+ | 2 | "Customer support was a nightmare. It | negative | | | took three weeks for my order to | | | | arrive, and when it did, the box was | | | | damaged. Very frustrating!" | | +-----------+------------------------------------------+-----------+ | 1 | "The battery life is incredible, and | positive | | | the screen is gorgeous! Best phone I've | | | | ever had. Totally worth the price." | | +-----------+------------------------------------------+-----------+ | 8 | "The shipping was delayed, but the | positive | | | support team was very helpful and kept | | | | me informed. The product itself is | | | | great, especially for the price." | | +-----------+------------------------------------------+-----------+ | 5 | The price is a bit too high for what | negative | | | you get. The material feels cheap and | | | | I'm worried it won't last. Service was | | | | okay. | | +-----------+------------------------------------------+-----------+ | 3 | "The product does exactly what it says | neutral | | | on the box. No complaints, but not | | | | exciting either." | | +-----------+------------------------------------------+-----------+ | 6 | "Absolutely furious! The item arrived | negative | | | broken, and getting a refund is proving | | | | impossible. I will never buy from them | | | | again." | | +-----------+------------------------------------------+-----------+
Analiza opiniones basadas en aspectos
Si una opinión general, como positiva o negativa, no es suficiente para tu caso de uso, puedes analizar un aspecto específico del significado del texto. Por ejemplo, es posible que desees comprender la actitud de un usuario hacia la calidad del producto, sin tener en cuenta sus opiniones sobre el precio. Incluso puedes solicitar un valor personalizado para indicar que un aspecto en particular no se aplica.
En el siguiente ejemplo, se muestra cómo usar la función AI.SCORE para calificar el sentimiento del usuario del 1 al 10 según qué tan favorable es cada opinión de la tabla customer_feedback hacia el precio, la atención al cliente y la calidad. La función devuelve el valor personalizado -1 en los casos en que no se menciona un aspecto en la revisión, de modo que puedas filtrar estos casos más adelante.
SELECT
review_id,
review_text,
AI.SCORE(
("Score 0.0 to 10 on positive sentiment about PRICE for review: ", review_text,
"If price is not mentioned, return -1.0")) AS price_score,
AI.SCORE(
("Score 0.0 to 10 on positive sentiment about CUSTOMER SERVICE for review: ", review_text,
"If customer service is not mentioned, return -1.0")) AS service_score,
AI.SCORE(
("Score 0.0 to 10 on positive sentiment about QUALITY for review: ", review_text,
"If quality is not mentioned, return -1.0")) AS quality_score
FROM
my_dataset.customer_feedback
LIMIT 3;
El resultado es similar al siguiente:
+-----------+------------------------------------------+--------------+---------------+---------------+ | review_id | review_text | price_score | service_score | quality_score | +-----------+------------------------------------------+--------------+---------------+---------------+ | 4 | "I'm so happy with this purchase! It | -1.0 | -1.0 | 9.5 | | | arrived early and exceeded all my | | | | | | expectations. The quality is top-notch, | | | | | | although the setup was a bit tricky." | | | | +-----------+------------------------------------------+--------------+---------------+---------------+ | 8 | "The shipping was delayed, but the | 9.0 | 8.5 | 9.0 | | | support team was very helpful and kept | | | | | | me informed. The product itself is | | | | | | great, especially for the price." | | | | +-----------+------------------------------------------+--------------+---------------+---------------+ | 6 | "Absolutely furious! The item arrived | -1.0 | 1.0 | 0.0 | | | broken, and getting a refund is proving | | | | | | impossible. I will never buy from them | | | | | | again." | | | | +-----------+------------------------------------------+--------------+---------------+---------------+
Detecta emociones
Además de la opinión positiva o negativa, puedes clasificar el texto según las emociones específicas que selecciones. Esto es útil cuando quieres comprender mejor las respuestas de los usuarios o marcar comentarios muy emocionales para su revisión.
SELECT
review_id,
review_text,
AI.CLASSIFY(
review_text,
categories => ['joy', 'anger', 'sadness', 'surprise', 'fear', 'disgust', 'neutral', 'other']
) AS emotion
FROM
my_dataset.customer_feedback;
El resultado es similar al siguiente:
+-----------+------------------------------------------+---------+ | review_id | review_text | emotion | +-----------+------------------------------------------+---------+ | 2 | "Customer support was a nightmare. It | anger | | | took three weeks for my order to | | | | arrive, and when it did, the box was | | | | damaged. Very frustrating!" | | +-----------+------------------------------------------+---------+ | 7 | This new feature for account access is | anger | | | confusing. I can't find where to update | | | | my profile. Please fix this bug! | | +-----------+------------------------------------------+---------+ | 4 | "I'm so happy with this purchase! It | joy | | | arrived early and exceeded all my | | | | expectations. The quality is top-notch, | | | | although the setup was a bit tricky." | | +-----------+------------------------------------------+---------+ | 1 | "The battery life is incredible, and | joy | | | the screen is gorgeous! Best phone I've | | | | ever had. Totally worth the price." | | +-----------+------------------------------------------+---------+ | 8 | "The shipping was delayed, but the | joy | | | support team was very helpful and kept | | | | me informed. The product itself is | | | | great, especially for the price." | | +-----------+------------------------------------------+---------+ | 5 | The price is a bit too high for what | sadness | | | you get. The material feels cheap and | | | | I'm worried it won't last. Service was | | | | okay. | | +-----------+------------------------------------------+---------+ | 3 | "The product does exactly what it says | neutral | | | on the box. No complaints, but not | | | | exciting either." | | +-----------+------------------------------------------+---------+ | 6 | "Absolutely furious! The item arrived | anger | | | broken, and getting a refund is proving | | | | impossible. I will never buy from them | | | | again." | | +-----------+------------------------------------------+---------+
Categorizar opiniones por tema
Puedes usar la función AI.CLASSIFY para agrupar las opiniones en temas predefinidos.
Por ejemplo, puedes hacer lo siguiente:
- Descubre temas comunes en los comentarios de los clientes.
- Organiza los documentos por tema.
- Enruta los tickets de asistencia por tema.
En el siguiente ejemplo, se muestra cómo clasificar los comentarios de los clientes en varios tipos, como problema de facturación o acceso a la cuenta, y, luego, contar cuántas opiniones pertenecen a cada categoría:
SELECT
AI.CLASSIFY(
review_text,
categories => ['Billing Issue', 'Account Access',
'Product Bug', 'Feature Request',
'Shipping Delay', 'Other']) AS topic,
COUNT(*) AS number_of_reviews,
FROM
my_dataset.customer_feedback
GROUP BY topic
ORDER BY number_of_reviews DESC;
El resultado es similar al siguiente:
+----------------+-------------------+ | topic | number_of_reviews | +----------------+-------------------+ | Other | 5 | | Shipping Delay | 2 | | Product Bug | 1 | +----------------+-------------------+
Identificar opiniones semánticamente similares
Puedes usar la función AI.SCORE para evaluar qué tan similares son dos fragmentos de texto desde el punto de vista semántico pidiéndole que califique la similitud de significado. Esto puede ayudarte con tareas como las siguientes:
- Encontrar entradas duplicadas o casi duplicadas
- Agrupar comentarios similares
- Potenciar las aplicaciones de búsqueda semántica
La siguiente búsqueda encuentra opiniones que mencionan la dificultad para configurar el producto:
SELECT
review_id,
review_text,
AI.SCORE(
(
"""How similar is the review to the concept of 'difficulty in setting up the product'?
A higher score indicates more similarity. Review: """,
review_text)) AS setup_difficulty
FROM my_dataset.customer_feedback
ORDER BY setup_difficulty DESC
LIMIT 2;
El resultado es similar al siguiente:
+-----------+------------------------------------------+------------------+ | review_id | review_text | setup_difficulty | +-----------+------------------------------------------+------------------+ | 4 | "I'm so happy with this purchase! It | 3 | | | arrived early and exceeded all my | | | | expectations. The quality is top-notch, | | | | although the setup was a bit tricky." | | +-----------+------------------------------------------+------------------+ | 7 | This new feature for account access is | 1 | | | confusing. I can't find where to update | | | | my profile. Please fix this bug! | | +-----------+------------------------------------------+------------------+
También puedes usar la función AI.IF para encontrar opiniones relacionadas con el texto:
SELECT
review_id,
review_text
FROM my_dataset.customer_feedback
WHERE
AI.IF(
(
"Does this review discuss difficulty setting up the product? Review: ",
review_text));
Cómo combinar funciones
Puede ser útil combinar estas funciones en una sola consulta. Por ejemplo, la siguiente consulta primero filtra las opiniones por sentimiento negativo y, luego, las clasifica según el tipo de frustración:
SELECT
review_id,
review_text,
AI.CLASSIFY(
review_text,
categories => [
'Poor Quality', 'Bad Customer Service', 'High Price', 'Other Negative']) AS negative_topic
FROM my_dataset.customer_feedback
WHERE
AI.IF(
("Does this review express a negative sentiment? Review: ", review_text));
Crea UDF de instrucciones reutilizables
Para que tus consultas sean fáciles de leer, puedes reutilizar la lógica de tus instrucciones creando funciones definidas por el usuario. La siguiente consulta crea una función para detectar opiniones negativas llamando a AI.IF con una instrucción personalizada. Luego, llama a esa función para filtrar por opiniones negativas.
CREATE OR REPLACE FUNCTION my_dataset.is_negative_sentiment(review_text STRING)
RETURNS BOOL
AS (
AI.IF(
("Does this review express a negative sentiment? Review: ", review_text))
);
SELECT
review_id,
review_text
FROM my_dataset.customer_feedback
WHERE my_dataset.is_negative_sentiment(review_text);
Realiza una limpieza
Para evitar que se apliquen cargos, puedes borrar el proyecto que contiene los recursos que creaste o conservar el proyecto y borrar los recursos individuales.
Borra tu proyecto
Para borrar el proyecto, haz lo siguiente:
- En la Google Cloud consola, ve a la página Administrar recursos.
- En la lista de proyectos, elige el proyecto que quieres borrar y haz clic en Borrar.
- En el diálogo, escribe el ID del proyecto y, luego, haz clic en Cerrar para borrar el proyecto.
Borra tu conjunto de datos
Para borrar el conjunto de datos y todos los recursos que contiene, incluidas todas las tablas y funciones, ejecuta la siguiente consulta:
DROP SCHEMA my_dataset CASCADE;