Crea un modelo

Crea un modelo dentro de un conjunto de datos existente.

Muestra de código

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de BigQuery sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de BigQuery para Java.

Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para bibliotecas 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 probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de BigQuery sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de BigQuery para Node.js.

Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para bibliotecas 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();

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.