Realize análises semânticas com funções de IA gerenciadas
Neste tutorial, mostramos como usar as funções de IA gerenciadas do BigQuery ML para realizar análises semânticas no feedback dos clientes.
Objetivos
Neste tutorial, você aprenderá a:
- Criar um conjunto de dados e carregar dados de sentimento em uma tabela
- Usar as seguintes funções de IA para realizar análises semânticas:
AI.IF: para filtrar seus dados com condições de linguagem naturalAI.SCORE: para classificar a entrada por sentimentoAI.CLASSIFY: para classificar a entrada em categorias definidas pelo usuário
Custos
Este tutorial usa componentes faturáveis do Google Cloud, incluindo:
- BigQuery
- BigQuery ML
Para mais informações sobre os custos do BigQuery, consulte a página de preços do BigQuery.
Para mais informações sobre os custos do BigQuery ML, consulte os preços do BigQuery ML.
Antes de começar
- Faça login na sua Google Cloud conta do. Se você não conhece o Google Cloud, crie uma conta para avaliar o desempenho dos nossos produtos em cenários reais. Clientes novos também recebem US $300 em créditos para executar, testar e implantar cargas de trabalho.
-
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.
-
Ative a API BigQuery.
Funções necessárias para ativar APIs
Para ativar as APIs, é necessário ter o papel do IAM de administrador de uso do serviço (
roles/serviceusage.serviceUsageAdmin), que contém a permissãoserviceusage.services.enable. Saiba como conceder papéis.Para novos projetos, a API BigQuery é ativada automaticamente.
- Opcional: ative o faturamento do projeto. Se você não quiser ativar o faturamento ou informar um cartão de crédito, as etapas deste documento ainda funcionarão. O BigQuery fornece um sandbox para executar as etapas. Para mais informações, consulte Ativar o sandbox do BigQuery.
Funções exigidas
Para receber as permissões necessárias para usar as funções de IA, peça que o administrador conceda a você os seguintes papéis do IAM no projeto:
-
Executar jobs de consulta e de carregamento:
usuário de jobs do BigQuery (
roles/bigquery.jobUser) -
Criar um conjunto de dados, criar uma tabela, carregar dados em uma tabela e consultar uma tabela:
editor de dados do BigQuery (
roles/bigquery.dataEditor)
Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.
Também é possível conseguir as permissões necessárias usando personalizados papéis ou outros predefinidos papéis.
Criar dados de amostra
Para criar um conjunto de dados chamado my_dataset para este tutorial, execute a consulta a seguir.
CREATE SCHEMA my_dataset OPTIONS (location = 'LOCATION');
Em seguida, crie uma tabela chamada customer_feedback que contenha exemplos de avaliações de clientes para um 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.")
])
);
Categorizar o sentimento geral
Pode ser útil extrair o sentimento geral expresso no texto para oferecer suporte a casos de uso como:
- Medir a satisfação do cliente com base nas avaliações.
- Monitorar a percepção da marca na rede social.
- Priorizar tíquetes de suporte com base no nível de insatisfação dos usuários.
A consulta a seguir mostra como usar a função AI.CLASSIFY para classificar
as avaliações da tabela customer_feedback como positivas, negativas ou
neutras:
SELECT
review_id,
review_text,
AI.CLASSIFY(
review_text,
categories => ['positive', 'negative', 'neutral']) AS sentiment
FROM
my_dataset.customer_feedback;
O resultado será semelhante a este:
+-----------+------------------------------------------+-----------+ | 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." | | +-----------+------------------------------------------+-----------+
Analisar o sentimento com base no aspecto
Se um sentimento geral, como positivo ou negativo , não for suficiente para seu caso de uso, você poderá analisar um aspecto específico do significado do texto. Por exemplo, talvez você queira entender a atitude de um usuário em relação à qualidade do produto, sem considerar a opinião dele sobre o preço. Você pode até mesmo pedir um valor personalizado para indicar que um aspecto específico não se aplica.
O exemplo a seguir mostra como usar a função AI.SCORE para classificar o sentimento do usuário de 1 a 10 com base em quão favorável cada avaliação na tabela customer_feedback é em relação ao preço, atendimento ao cliente e qualidade. A função retorna o valor personalizado -1 nos casos em que um aspecto não é mencionado na avaliação para que você possa filtrá-los mais tarde.
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;
O resultado será semelhante a este:
+-----------+------------------------------------------+--------------+---------------+---------------+ | 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." | | | | +-----------+------------------------------------------+--------------+---------------+---------------+
Detectar emoções
Além do sentimento positivo ou negativo, você pode classificar o texto com base em emoções específicas selecionadas. Isso é útil quando você quer entender melhor as respostas do usuário ou sinalizar feedback altamente emocional para revisão.
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;
O resultado será semelhante a este:
+-----------+------------------------------------------+---------+ | 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 avaliações por tema
Você pode usar a função AI.CLASSIFY para agrupar avaliações em temas predefinidos.
Por exemplo, é possível:
- Descobrir temas comuns no feedback dos clientes.
- Organizar documentos por assunto.
- Encaminhar tíquetes de suporte por tema.
O exemplo a seguir mostra como classificar o feedback do cliente em vários tipos, como problema de faturamento ou acesso à conta , e contar quantas avaliações pertencem a cada categoria:
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;
O resultado será semelhante a este:
+----------------+-------------------+ | topic | number_of_reviews | +----------------+-------------------+ | Other | 5 | | Shipping Delay | 2 | | Product Bug | 1 | +----------------+-------------------+
Identificar avaliações semanticamente semelhantes
Você pode usar a função AI.SCORE para avaliar a semelhança semântica de dois textos pedindo que ela classifique a semelhança de significado. Isso pode ajudar você com tarefas como:
- Encontrar entradas duplicadas ou quase duplicadas.
- Agrupar feedbacks semelhantes.
- Aplicativos de pesquisa semântica.
A consulta a seguir encontra avaliações que discutem a dificuldade de configurar o produto:
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;
O resultado será semelhante a este:
+-----------+------------------------------------------+------------------+ | 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! | | +-----------+------------------------------------------+------------------+
Você também pode usar a função AI.IF para encontrar avaliações relacionadas ao 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));
Combinar funções
Pode ser útil combinar essas funções em uma única consulta. Por exemplo, a consulta a seguir primeiro filtra as avaliações para sentimentos negativos e, em seguida, as classifica pelo tipo de frustração:
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));
Criar UDFs de comando reutilizáveis
Para manter suas consultas legíveis, você pode reutilizar a lógica de comando criando
funções definidas pelo usuário. A consulta a seguir cria uma função para detectar sentimentos negativos chamando AI.IF com um comando personalizado. Em seguida, ela chama essa função para filtrar por avaliação negativa.
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);
Limpar
Para evitar cobranças, você pode excluir o projeto que contém os recursos criados ou manter o projeto e excluir os recursos individuais.
Excluir o projeto
Para excluir o projeto:
- No Google Cloud console, acesse a página Gerenciar recursos.
- Na lista de projetos, selecione o projeto que você quer excluir e clique em Excluir.
- Na caixa de diálogo, digite o ID do projeto e clique em Desligar para excluir o projeto.
Excluir o conjunto de dados
Para excluir o conjunto de dados e todos os recursos que ele contém, incluindo todas as tabelas e funções, execute a consulta a seguir:
DROP SCHEMA my_dataset CASCADE;