Criar um modelo

Crie um modelo dentro de um conjunto de dados atual.

Exemplo de código

Java

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Java.

Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.QueryJobConfiguration;

// Sample to create a model
public class CreateModel {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String modelName = "MY_MODEL_NAME";
    String sql =
        "CREATE MODEL `"
            + datasetName
            + "."
            + modelName
            + "`"
            + "OPTIONS ( "
            + "model_type='linear_reg', "
            + "max_iteration=1, "
            + "learn_rate=0.4, "
            + "learn_rate_strategy='constant' "
            + ") AS ( "
            + "SELECT 'a' AS f1, 2.0 AS label "
            + "UNION ALL "
            + "SELECT 'b' AS f1, 3.8 AS label "
            + ")";
    createModel(sql);
  }

  public static void createModel(String sql) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      QueryJobConfiguration config = QueryJobConfiguration.newBuilder(sql).build();

      // create a model using query and it will wait to complete job.
      Job job = bigquery.create(JobInfo.of(config));
      job = job.waitFor();
      if (job.isDone()) {
        System.out.println("Model created successfully");
      } else {
        System.out.println("Model was not created");
      }
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Model was not created. \n" + e.toString());
    }
  }
}

Node.js

Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Node.js.

Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function createModel() {
  // Creates a model named "my_model" in "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample
   */
  // const datasetId = "my_dataset";
  // const modelId = "my_model";

  const query = `CREATE OR REPLACE MODEL \`${datasetId}.${modelId}\`
       OPTIONS(model_type='logistic_reg') AS
       SELECT
         IF(totals.transactions IS NULL, 0, 1) AS label,
         IFNULL(device.operatingSystem, "") AS os,
         device.isMobile AS is_mobile,
         IFNULL(geoNetwork.country, "") AS country,
         IFNULL(totals.pageviews, 0) AS pageviews
       FROM
         \`bigquery-public-data.google_analytics_sample.ga_sessions_*\`
       WHERE
         _TABLE_SUFFIX BETWEEN '20160801' AND '20170631'
       LIMIT  100000;`;

  const queryOptions = {
    query: query,
  };

  // Run query to create a model
  const [job] = await bigquery.createQueryJob(queryOptions);

  // Wait for the query to finish
  await job.getQueryResults();

  console.log(`Model ${modelId} created.`);
}
createModel();

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.