Eseguire l'analisi semantica con le funzioni di AI gestite

Questo tutorial mostra come utilizzare le funzioni di AI gestite di BigQuery ML per eseguire l'analisi semantica del feedback dei clienti.

Obiettivi

In questo tutorial:

  • Crea un set di dati e carica i dati sul sentiment in una tabella
  • Crea una connessione risorsa Cloud
  • Utilizza le seguenti funzioni AI per eseguire l'analisi semantica:
    • AI.IF: per filtrare i dati con condizioni in linguaggio naturale
    • AI.SCORE: per valutare l'input in base al sentiment
    • AI.CLASSIFY: per classificare l'input in categorie definite dall'utente

Costi

Questo tutorial utilizza componenti fatturabili di Google Cloud, tra cui:

  • BigQuery
  • BigQuery ML

Per ulteriori informazioni sui costi di BigQuery, consulta la pagina Prezzi di BigQuery.

Per ulteriori informazioni sui costi di BigQuery ML, vedi Prezzi di BigQuery ML.

Prima di iniziare

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  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. Se utilizzi un progetto esistente per questa guida, verifica di disporre delle autorizzazioni necessarie per completare la guida. Se hai creato un nuovo progetto, disponi già delle autorizzazioni necessarie.

  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. Se utilizzi un progetto esistente per questa guida, verifica di disporre delle autorizzazioni necessarie per completare la guida. Se hai creato un nuovo progetto, disponi già delle autorizzazioni necessarie.

  6. Enable the BigQuery API and BigQuery Connection API APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

    Per i nuovi progetti, l'API BigQuery viene abilitata automaticamente.

  7. (Facoltativo) Abilita la fatturazione per il progetto. Se non vuoi attivare la fatturazione o fornire una carta di credito, i passaggi descritti in questo documento funzionano comunque. BigQuery ti offre una sandbox per eseguire i passaggi. Per saperne di più, vedi Attiva la sandbox di BigQuery.
  8. Ruoli obbligatori

    Per ottenere le autorizzazioni necessarie per utilizzare le funzioni di AI, chiedi all'amministratore di concederti i seguenti ruoli IAM nel progetto:

    Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

    Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

    Crea dati di esempio

    Per creare un set di dati denominato my_dataset per questo tutorial, esegui la seguente query.

    CREATE SCHEMA my_dataset OPTIONS (location = 'LOCATION');
    

    Successivamente, crea una tabella denominata customer_feedback che contenga recensioni dei clienti di esempio per 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.") 
          ])
    );
    

    Crea una connessione

    Crea una connessione risorsa Cloud e ottieni il account di servizio della connessione.

    Seleziona una delle seguenti opzioni:

    Console

    1. Vai alla pagina BigQuery.

      Vai a BigQuery

    2. Nel riquadro a sinistra, fai clic su Explorer:

      Pulsante evidenziato per il riquadro Spazio di esplorazione.

      Se non vedi il riquadro a sinistra, fai clic su Espandi riquadro a sinistra per aprirlo.

    3. Nel riquadro Explorer, espandi il nome del progetto e fai clic su Connessioni.

    4. Nella pagina Connessioni, fai clic su Crea connessione.

    5. Per Tipo di connessione, scegli Modelli remoti di Vertex AI, funzioni remote, BigLake e Spanner (risorsa Cloud).

    6. Nel campo ID connessione, inserisci un nome per la connessione.

    7. Per Tipo di località, seleziona una località per la connessione. La connessione deve essere colocalizzata con le altre risorse, ad esempio i set di dati.

    8. Fai clic su Crea connessione.

    9. Fai clic su Vai alla connessione.

    10. Nel riquadro Informazioni sulla connessione, copia l'ID dell'account di servizio da utilizzare in un passaggio successivo.

    bq

    1. In un ambiente a riga di comando, crea una connessione:

      bq mk --connection --location=REGION --project_id=PROJECT_ID \
          --connection_type=CLOUD_RESOURCE CONNECTION_ID

      Il parametro --project_id sostituisce il progetto predefinito.

      Sostituisci quanto segue:

      • REGION: la tua regione di connessione
      • PROJECT_ID: il tuo Google Cloud ID progetto
      • CONNECTION_ID: un ID per la tua connessione

      Quando crei una risorsa di connessione, BigQuery crea un account di serviziot di sistema univoco e lo associa alla connessione.

      Risoluzione dei problemi: se viene visualizzato il seguente errore di connessione, aggiorna Google Cloud SDK:

      Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
      
    2. Recupera e copia l'ID account di servizio da utilizzare in un passaggio successivo:

      bq show --connection PROJECT_ID.REGION.CONNECTION_ID

      L'output è simile al seguente:

      name                          properties
      1234.REGION.CONNECTION_ID     {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
      

    Terraform

    Utilizza la risorsa google_bigquery_connection.

    Per eseguire l'autenticazione in BigQuery, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

    L'esempio seguente crea una connessione di risorsa Cloud denominata my_cloud_resource_connection nella regione US:

    
    # This queries the provider for project information.
    data "google_project" "default" {}
    
    # This creates a cloud resource connection in the US region named my_cloud_resource_connection.
    # Note: The cloud resource nested object has only one output field - serviceAccountId.
    resource "google_bigquery_connection" "default" {
      connection_id = "my_cloud_resource_connection"
      project       = data.google_project.default.project_id
      location      = "US"
      cloud_resource {}
    }

    Per applicare la configurazione di Terraform in un progetto Google Cloud , completa i passaggi descritti nelle sezioni seguenti.

    Prepara Cloud Shell

    1. Avvia Cloud Shell.
    2. Imposta il progetto Google Cloud predefinito in cui vuoi applicare le configurazioni Terraform.

      Devi eseguire questo comando una sola volta per progetto e puoi eseguirlo in qualsiasi directory.

      export GOOGLE_CLOUD_PROJECT=PROJECT_ID

      Le variabili di ambiente vengono sostituite se imposti valori espliciti nel file di configurazione Terraform.

    Preparare la directory

    Ogni file di configurazione Terraform deve avere la propria directory (chiamata anche modulo radice).

    1. In Cloud Shell, crea una directory e un nuovo file al suo interno. Il nome file deve avere l'estensione .tf, ad esempio main.tf. In questo tutorial, il file viene denominato main.tf.
      mkdir DIRECTORY && cd DIRECTORY && touch main.tf
    2. Se stai seguendo un tutorial, puoi copiare il codice campione in ogni sezione o passaggio.

      Copia il codice campione nel file main.tf appena creato.

      (Facoltativo) Copia il codice da GitHub. Questa operazione è consigliata quando lo snippet Terraform fa parte di una soluzione end-to-end.

    3. Rivedi e modifica i parametri di esempio da applicare al tuo ambiente.
    4. Salva le modifiche.
    5. Inizializza Terraform. Devi effettuare questa operazione una sola volta per directory.
      terraform init

      (Facoltativo) Per utilizzare l'ultima versione del provider Google, includi l'opzione -upgrade:

      terraform init -upgrade

    Applica le modifiche

    1. Rivedi la configurazione e verifica che le risorse che Terraform creerà o aggiornerà corrispondano alle tue aspettative:
      terraform plan

      Apporta le correzioni necessarie alla configurazione.

    2. Applica la configurazione Terraform eseguendo questo comando e inserendo yes al prompt:
      terraform apply

      Attendi che Terraform visualizzi il messaggio "Apply complete!".

    3. Apri il tuo Google Cloud progetto per visualizzare i risultati. Nella console Google Cloud , vai alle risorse nell'interfaccia utente per assicurarti che Terraform le abbia create o aggiornate.

    Concedi le autorizzazioni al account di servizio della connessione

    Concedi al account di servizio della connessione il ruolo Utente Vertex AI. Devi concedere questo ruolo nello stesso progetto che hai creato o selezionato nella sezione Prima di iniziare. La concessione del ruolo in un progetto diverso genera l'errore bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource.

    Per concedere il ruolo, segui questi passaggi:

    1. Vai alla pagina IAM e amministrazione.

      Vai a IAM e amministrazione

    2. Fai clic su Concedi l'accesso.

    3. Nel campo Nuove entità, inserisci l'ID account di servizio che hai copiato in precedenza.

    4. Nel campo Seleziona un ruolo, scegli Vertex AI e poi seleziona Ruolo utente Vertex AI.

    5. Fai clic su Salva.

    Classificare il sentiment generale

    Può essere utile estrarre il sentiment generale espresso nel testo per supportare casi d'uso come i seguenti:

    • Valuta la soddisfazione dei clienti dalle recensioni.
    • Monitorare la percezione del brand sui social media.
    • Assegna la priorità alle richieste di assistenza in base al livello di frustrazione degli utenti.

    La seguente query mostra come utilizzare la funzione AI.CLASSIFY per classificare le recensioni della tabella customer_feedback come positive, negative o neutre:

    SELECT
      review_id,
      review_text,
      AI.CLASSIFY(
        review_text,
        categories => ['positive', 'negative', 'neutral'],
        connection_id => "CONNECTION_ID") AS sentiment
    FROM
      my_dataset.customer_feedback;
    

    Il risultato è simile al seguente:

    +-----------+------------------------------------------+-----------+
    | 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."                                  |           |
    +-----------+------------------------------------------+-----------+
    

    Analizzare il sentiment basato sugli aspetti

    Se un sentiment generale come positivo o negativo non è sufficiente per il tuo caso d'uso, puoi analizzare un aspetto specifico del significato del testo. Ad esempio, potresti voler comprendere l'atteggiamento di un utente nei confronti della qualità del prodotto, senza considerare le sue opinioni sul prezzo. Puoi anche richiedere un valore personalizzato per indicare che un aspetto particolare non è applicabile.

    L'esempio seguente mostra come utilizzare la funzione AI.SCORE per valutare il sentiment degli utenti da 1 a 10 in base a quanto ogni recensione nella tabella customer_feedback è favorevole a prezzo, assistenza clienti e qualità. La funzione restituisce il valore personalizzato -1 nei casi in cui un aspetto non viene menzionato nella recensione, in modo da poterlo filtrare in un secondo momento.

    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"),
        connection_id => "CONNECTION_ID") 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"),
        connection_id => "CONNECTION_ID") 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"),
        connection_id => "CONNECTION_ID") AS quality_score
    FROM
      my_dataset.customer_feedback
    LIMIT 3;
    

    Il risultato è simile al seguente:

    +-----------+------------------------------------------+--------------+---------------+---------------+
    | 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."                                  |              |               |               |
    +-----------+------------------------------------------+--------------+---------------+---------------+
    

    Rilevare le emozioni

    Oltre al sentiment positivo o negativo, puoi classificare il testo in base a emozioni specifiche che selezioni. Questa funzionalità è utile quando vuoi comprendere meglio le risposte degli utenti o segnalare i feedback più emotivi per la revisione.

    SELECT
      review_id,
      review_text,
      AI.CLASSIFY(
        review_text,
        categories => ['joy', 'anger', 'sadness', 'surprise', 'fear', 'disgust', 'neutral', 'other'],
        connection_id => "CONNECTION_ID"
      ) AS emotion
    FROM
      my_dataset.customer_feedback;
    

    Il risultato è simile al seguente:

    +-----------+------------------------------------------+---------+
    | 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."                                  |         |
    +-----------+------------------------------------------+---------+
    

    Categorizzare le recensioni per argomento

    Puoi utilizzare la funzione AI.CLASSIFY per raggruppare le recensioni in argomenti predefiniti. Puoi ad esempio eseguire le seguenti operazioni:

    • Scopri i temi comuni nel feedback dei clienti.
    • Organizzare i documenti per argomento.
    • Instrada i ticket di assistenza in base all'argomento.

    L'esempio seguente mostra come classificare il feedback dei clienti in vari tipi, ad esempio problema di fatturazione o accesso all'account, e poi contare quante recensioni appartengono a ciascuna categoria:

    SELECT
      AI.CLASSIFY(
        review_text,
        categories => ['Billing Issue', 'Account Access',
                       'Product Bug', 'Feature Request',
                       'Shipping Delay', 'Other'],
        connection_id => "CONNECTION_ID") AS topic,
        COUNT(*) AS number_of_reviews,
    FROM
      my_dataset.customer_feedback
    GROUP BY topic
    ORDER BY number_of_reviews DESC;
    

    Il risultato è simile al seguente:

    +----------------+-------------------+
    | topic          | number_of_reviews |
    +----------------+-------------------+
    | Other          | 5                 |
    | Shipping Delay | 2                 |
    | Product Bug    | 1                 |
    +----------------+-------------------+
    

    Identificare recensioni semanticamente simili

    Puoi utilizzare la funzione AI.SCORE per valutare la somiglianza semantica di due brani di testo chiedendo di valutare la somiglianza di significato. Questo può aiutarti con attività come le seguenti:

    • Trovare voci duplicate o quasi duplicate.
    • Raggruppa i feedback simili.
    • Alimentare le applicazioni di ricerca semantica.

    La seguente query trova recensioni che parlano della difficoltà di configurazione del prodotto:

    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),
        connection_id => "CONNECTION_ID") AS setup_difficulty
    FROM my_dataset.customer_feedback
    ORDER BY setup_difficulty DESC
    LIMIT 2;
    

    Il risultato è simile al seguente:

    +-----------+------------------------------------------+------------------+
    | 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!         |                  |
    +-----------+------------------------------------------+------------------+
    

    Puoi anche utilizzare la funzione AI.IF per trovare recensioni relative al testo:

    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),
        connection_id => "CONNECTION_ID");
    

    Funzioni combinate

    Può essere utile combinare queste funzioni in un'unica query. Ad esempio, la seguente query filtra innanzitutto le recensioni in base al sentiment negativo, quindi le classifica in base al tipo di frustrazione:

    SELECT
      review_id,
      review_text,
      AI.CLASSIFY(
        review_text,
        categories => [
          'Poor Quality', 'Bad Customer Service', 'High Price', 'Other Negative'],
        connection_id => "CONNECTION_ID") AS negative_topic
    FROM my_dataset.customer_feedback
    WHERE
      AI.IF(
        ("Does this review express a negative sentiment? Review: ", review_text),
        connection_id => "CONNECTION_ID");
    

    Creare funzioni definite dall'utente per i prompt riutilizzabili

    Per mantenere le query leggibili, puoi riutilizzare la logica del prompt creando funzioni definite dall'utente. La seguente query crea una funzione per rilevare il sentiment negativo chiamando AI.IF con un prompt personalizzato. Poi, chiama questa funzione per filtrare in base alle recensioni negative.

    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),
          connection_id => "CONNECTION_ID")
    );
    
    SELECT
      review_id,
      review_text
    FROM my_dataset.customer_feedback
    WHERE my_dataset.is_negative_sentiment(review_text);
    

    Esegui la pulizia

    Per evitare addebiti, puoi eliminare il progetto che contiene le risorse che hai creato oppure mantenere il progetto ed eliminare le singole risorse.

    Elimina il progetto

    Per eliminare il progetto:

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    Elimina il set di dati

    Per eliminare il set di dati e tutte le risorse che contiene, incluse tutte le tabelle e le funzioni, esegui la seguente query:

    DROP SCHEMA my_dataset CASCADE;