Realizar análise semântica com funções de IA gerenciadas

Neste tutorial, mostramos como usar as funções de IA gerenciadas do BigQuery ML para realizar uma análise semântica no feedback dos clientes.

Objetivos

Neste tutorial, você aprenderá a:

  • Criar um conjunto de dados e carregar dados de sentimento em uma tabela
  • Use as seguintes funções de IA para realizar uma análise semântica:
    • AI.IF: para filtrar seus dados com condições de linguagem natural
    • AI.SCORE: para classificar a entrada por sentimento
    • AI.CLASSIFY: para classificar a entrada em categorias definidas pelo usuário

Custos

Neste tutorial, usamos 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

  1. Faça login na sua conta do Google Cloud . Se você começou a usar o Google Cloud, crie uma conta para avaliar o desempenho de nossos produtos em situações reais. Clientes novos também recebem US$ 300 em créditos para executar, testar e implantar cargas de trabalho.
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. 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.

  4. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. 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.

  6. 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ão serviceusage.services.enable. Saiba como conceder papéis.

    Ativar a API

    Para novos projetos, a API BigQuery é ativada automaticamente.

  7. 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 ao administrador para conceder a você os seguintes papéis do IAM no projeto:

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 papéis personalizados ou outros papéis predefinidos.

Criar dados de amostra

Para criar um conjunto de dados chamado my_dataset para este tutorial, execute a seguinte consulta.

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

É útil extrair o sentimento geral expresso no texto para oferecer suporte a casos de uso como:

  • Avalie a satisfação do cliente com base nas avaliações.
  • Monitore a percepção da marca nas redes sociais.
  • Priorize os tíquetes de suporte com base no nível de frustração dos usuários.

A consulta a seguir mostra como usar a função AI.CLASSIFY para classificar 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 em aspectos

Se um sentimento geral, como positivo ou negativo, não for suficiente para seu caso de uso, analise um aspecto específico do significado do texto. Por exemplo, você pode querer 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é 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 como cada avaliação na tabela customer_feedback é favorável ao preço, ao 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 filtrar esses casos 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 que selecionar. Isso é útil quando você quer entender melhor as respostas dos usuários ou sinalizar feedback muito emotivo 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

É possível usar a função AI.CLASSIFY para agrupar avaliações em tópicos predefinidos. Por exemplo, é possível:

  • Descubra temas comuns no feedback dos clientes.
  • Organize os documentos por assunto.
  • Encaminhar tíquetes de suporte por tema.

O exemplo a seguir mostra como classificar o feedback dos clientes 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 similaridade de significado. Isso pode ajudar você com tarefas como:

  • Encontrar entradas duplicadas ou quase duplicadas.
  • Agrupar feedbacks semelhantes.
  • Potencialize 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 a 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 com sentimento negativo e depois as classifica por 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 solicitação reutilizáveis

Para manter suas consultas legíveis, reutilize a lógica de comandos 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, ele chama essa função para filtrar por avaliações 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);

Limpar

Para evitar cobranças, exclua o projeto que contém os recursos criados ou mantenha o projeto e exclua os recursos individuais.

Excluir o projeto

Para excluir o projeto:

  1. No console Google Cloud , acesse a página Gerenciar recursos.

    Acessar "Gerenciar recursos"

  2. Na lista de projetos, selecione o projeto que você quer excluir e clique em Excluir .
  3. Na caixa de diálogo, digite o ID do projeto e clique em Encerrar para excluí-lo.

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 seguinte consulta:

DROP SCHEMA my_dataset CASCADE;