モデルの作成

既存のデータセット内にモデルを作成します。

コードサンプル

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートJava の手順に沿って設定を行ってください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートNode.js の手順に沿って設定を行ってください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

// 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();

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。