BigQuery ML で ML モデルを作成する

このチュートリアルでは、Google Cloud コンソールを使用して BigQuery ML を利用する方法を紹介します。

BigQuery ML を利用すると、BigQuery で SQL クエリと Python コードを使って ML モデルを作成、実行できます。ここでは、SQL のユーザーが簡単に ML を利用できるようにすることを目標としています。使い慣れたツールを使用してモデルを構築でき、データ移動の必要もないため、開発スピードを向上させることができます。

このチュートリアルでは、BigQuery 用の Google アナリティクス サンプル データセットを使用して、ウェブサイト訪問者がトランザクションを行うかどうかを予測するモデルを作成します。アナリティクス データセットのスキーマについては、Google アナリティクス ヘルプセンターで BigQuery Export スキーマをご覧ください。

目標

このチュートリアルでは、次のものを使用します。

  • BigQuery ML。CREATE MODEL ステートメントを使用して、2 項ロジスティック回帰モデルを作成します。
  • ML.EVALUATE 関数。ML モデルを評価します。
  • ML.PREDICT 関数。ML モデルを使用して予測を行います。

費用

このチュートリアルでは、Google Cloud の課金対象となる次のコンポーネントを使用します。

  • BigQuery
  • BigQuery ML

BigQuery の費用の詳細については、BigQuery の料金ページをご覧ください。

BigQuery ML の費用の詳細については、BigQuery ML の料金をご覧ください。

始める前に

  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. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  5. Google Cloud プロジェクトで課金が有効になっていることを確認します

  6. 新しいプロジェクトでは、BigQuery が自動的に有効になります。既存のプロジェクトで BigQuery を有効にするには、

    BigQuery API を有効にします。

    API を有効にする

    に移動します。

データセットを作成する

ML モデルを保存する BigQuery データセットを作成します。

  1. Google Cloud コンソールで [BigQuery] ページに移動します。

    [BigQuery] ページに移動

  2. [エクスプローラ] ペインで、プロジェクト名をクリックします。

  3. 「アクションを表示」> [データセットを作成] をクリックします。

    データセットを作成する。

  4. [データセットの作成] ページで、次の操作を行います。

    • [データセット ID] に「bqml_tutorial」と入力します。

    • [ロケーション タイプ] で [マルチリージョン] を選択してから、[US (米国の複数のリージョン)] を選択します。

      一般公開データセットは US マルチリージョンに保存されています。わかりやすくするため、データセットを同じロケーションに保存します。

    • 残りのデフォルトの設定は変更せず、[データセットを作成] をクリックします。

      データセットの作成ページ。

モデルを作成する

次に、BigQuery 用のアナリティクス サンプル データセットを使用して、ロジスティック回帰モデルを作成します。

SQL

次の GoogleSQL クエリを使用して、ウェブサイト訪問者がトランザクションを行うかどうかを予測するモデルを作成します。

#standardSQL
CREATE MODEL `bqml_tutorial.sample_model`
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 '20170630'

モデルを作成するだけでなく、CREATE MODEL ステートメントを含むクエリを実行し、クエリの SELECT ステートメントから得られたデータでモデルをトレーニングします。

クエリの詳細

CREATE MODEL 句は、bqml_tutorial.sample_model という名前のモデルを作成し、トレーニングするために使用されます。

OPTIONS(model_type='logistic_reg') 句を指定すると、ロジスティック回帰モデルを作成することを意味します。ロジスティック回帰モデルは、入力データを 2 つのクラスに分割し、データが各クラスに分類される確率を示します。通常、検出対象(たとえば、スパムメール)は 1 で表され、それ以外は 0 で表されます。ロジスティック回帰モデルの出力が 0.9 の場合、入力が検出対象である確率(スパムメールの確率)が 90% であることを意味します。

このクエリの SELECT ステートメントで次の列を取得します。作成したモデルは、この列を使用して訪問者がトランザクションを完了する確率を予測します。

  • totals.transactions - セッション内の電子商取引の合計数。トランザクション数が NULL の場合、label 列の値は 0 に設定されます。それ以外の場合は 1 に設定されます。これらの値は結果の確率を表します。CREATE MODEL ステートメントで input_label_cols= オプションを設定する代わりに、label というエイリアスを作成することもできます。
  • device.operatingSystem - ユーザーのデバイスのオペレーティング システムです。
  • device.isMobile - ユーザーのデバイスがモバイル デバイスかどうかを示します。
  • geoNetwork.country - セッションが発生した国。IP アドレスに基づいて特定されます。
  • totals.pageviews - セッション内のページビューの合計数です。

FROM 句 - bigquery-public-data.google_analytics_sample.ga_sessions_* - Google アナリティクスのサンプル データセットにクエリを実行していることを示します。このデータセットは bigquery-public-data プロジェクト中にあります。ここでは、日付によってシャーディングされた一連のテーブルにクエリを実行します。これを指定するため、テーブル名 google_analytics_sample.ga_sessions_* にワイルドカードを使用しています。

WHERE 句 - _TABLE_SUFFIX BETWEEN '20160801' AND '20170630' - クエリによってスキャンされるテーブルの数を制限します。スキャンする日付の範囲は 2016 年 8 月 1 日から 2017 年 6 月 30 日までです。

CREATE MODEL クエリを実行する

モデルを作成してトレーニングする CREATE MODEL クエリを実行するには:

  1. Google Cloud コンソールで、[クエリを新規作成] ボタンをクリックします。このテキストをクリックできない場合、クエリエディタはすでに開いています。

クエリの作成ボタン

  1. [クエリエディタ] のテキスト領域に、次の GoogleSQL クエリを入力します。

    #standardSQL
    CREATE MODEL `bqml_tutorial.sample_model`
    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 '20170630'
    
  2. [実行] をクリックします。

    クエリが完了するまでに数分かかります。最初のイテレーションが完了すると、モデル(sample_model)がナビゲーション パネルに表示されます。クエリは CREATE MODEL ステートメントを使用してモデルを作成するため、クエリの結果は表示されません。

    [モデルの統計情報] タブを表示すると、トレーニング中のモデルを確認できます。最初のイテレーションが完了すると、タブが更新されます。イテレーションが完了するたびに、統計情報が更新されます。

BigQuery DataFrames

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

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

from bigframes.ml.linear_model import LogisticRegression
import bigframes.pandas as bpd

# Start by selecting the data you'll use for training. `read_gbq` accepts
# either a SQL query or a table ID. Since this example selects from multiple
# tables via a wildcard, use SQL to define this data. Watch issue
# https://github.com/googleapis/python-bigquery-dataframes/issues/169
# for updates to `read_gbq` to support wildcard tables.

df = bpd.read_gbq_table(
    "bigquery-public-data.google_analytics_sample.ga_sessions_*",
    filters=[
        ("_table_suffix", ">=", "20160801"),
        ("_table_suffix", "<=", "20170630"),
    ],
)

# Extract the total number of transactions within
# the Google Analytics session.
#
# Because the totals column is a STRUCT data type, call
# Series.struct.field("transactions") to extract the transactions field.
# See the reference documentation below:
# https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.operations.structs.StructAccessor#bigframes_operations_structs_StructAccessor_field
transactions = df["totals"].struct.field("transactions")

# The "label" values represent the outcome of the model's
# prediction. In this case, the model predicts if there are any
# ecommerce transactions within the Google Analytics session.
# If the number of transactions is NULL, the value in the label
# column is set to 0. Otherwise, it is set to 1.
label = transactions.notnull().map({True: 1, False: 0}).rename("label")

# Extract the operating system of the visitor's device.
operating_system = df["device"].struct.field("operatingSystem")
operating_system = operating_system.fillna("")

# Extract whether the visitor's device is a mobile device.
is_mobile = df["device"].struct.field("isMobile")

# Extract the country from which the sessions originated, based on the IP address.
country = df["geoNetwork"].struct.field("country").fillna("")

# Extract the total number of page views within the session.
pageviews = df["totals"].struct.field("pageviews").fillna(0)

# Combine all the feature columns into a single DataFrame
# to use as training data.
features = bpd.DataFrame(
    {
        "os": operating_system,
        "is_mobile": is_mobile,
        "country": country,
        "pageviews": pageviews,
    }
)

# Logistic Regression model splits data into two classes, giving the
# a confidence score that the data is in one of the classes.
model = LogisticRegression()
model.fit(features, label)

# The model.fit() call above created a temporary model.
# Use the to_gbq() method to write to a permanent location.
model.to_gbq(
    your_model_id,  # For example: "bqml_tutorial.sample_model",
    replace=True,
)

トレーニングの統計情報を取得する

モデルのトレーニング結果を確認するには、ML.TRAINING_INFO 関数を使用するか、Google Cloud コンソールで統計情報を表示します。このチュートリアルでは、Google Cloud コンソールを使用します。

機械学習では、データを使用して予測を行うモデルを作成します。モデルは、入力データを取得して計算を行い、出力(予測)を生成する関数です。

ML アルゴリズムは、すでに判明している複数のデータ(ユーザーの購入履歴データなど)を取得し、モデルの予測結果が実際の値と一致するように、モデルのさまざまな重み付けを繰り返し調整します。具体的には、モデルで誤った指標の使用(損失)回数を減らしていくことで調整します。

繰り返し調整を行うことで、損失を減らしていきます(ゼロになるのが理想的です)。損失ゼロは、モデルが 100% 正確であることを意味します。

CREATE MODEL クエリで生成したモデルのトレーニング統計を確認するには:

  1. Google Cloud コンソールのナビゲーション パネルの [リソース] セクションで、[PROJECT_ID] > [bqml_tutorial] と開き、[sample_model] をクリックします。

  2. [モデルの統計情報] タブをクリックします。結果は次のようになります。

    ML.TRAINING_INFO の出力

    [トレーニング データの損失] 列は、トレーニング データセットで所定の回数のイテレーションを行った後に計算された損失指標を表します。ロジスティック回帰モデルのため、この列は対数損失になります。[評価データの損失] 列は、ホールドアウト データセット(モデルを検証するためにトレーニングから返され、保存されているデータ)で計算された損失指標と同じになります。

    BigQuery ML は、入力データをトレーニング セットとホールドアウト セットに自動的に分割し、モデルの過学習を防ぎます。この処理は、トレーニング アルゴリズムが既知のデータに合わせすぎて、新しい未確認のサンプルに対応できなくなることを防ぐために行われます。

    [トレーニング データの損失] と [評価データの損失] 列の値は平均の損失値で、それぞれのセットのすべてのサンプルの平均値になります。

    ML.TRAINING_INFO 関数の詳細については、BigQuery ML 構文リファレンスをご覧ください。

モデルを評価する

モデルを作成したら、ML.EVALUATE 関数を使用して分類子の性能を評価します。ML.EVALUATE 関数は、実際のデータに対する予測値を評価します。ロジスティック回帰固有の指標を計算するには、ML.ROC_CURVE SQL 関数または bigframes.ml.metrics.roc_curve BigQuery DataFrames 関数を使用します。

このチュートリアルでは、トランザクションを検出する 2 項分類モデルを使用しています。label 列にクラスの値が示されます。0 は「トランザクションなし」、1 は「トランザクションあり」です。

SQL

モデルの評価に使用するクエリは次のとおりです。

#standardSQL
SELECT
*
FROM
ML.EVALUATE(MODEL `bqml_tutorial.sample_model`, (
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 '20170701' AND '20170801'))

クエリの詳細

先頭の SELECT ステートメントで、モデルから列を取得します。

FROM 句で、モデル bqml_tutorial.sample_model に対して ML.EVALUATE 関数を使用します。

このクエリでネストしている SELECT ステートメントと FROM 句は CREATE MODEL クエリと同じです。

WHERE 句 - _TABLE_SUFFIX BETWEEN '20170701' AND '20170801' - クエリによってスキャンされるテーブルの数を制限します。スキャンする日付の範囲は 2017 年 7 月 1 日から 2017 年 8 月 1 日までです。このデータは、モデルの予測性能の評価に使用します。これは、トレーニング データの期間の直後の月に収集されています。

ML.EVALUATE クエリを実行する

モデルを評価する ML.EVALUATE クエリを実行するには:

  1. Google Cloud コンソールで、[クエリを新規作成] ボタンをクリックします。

  2. [クエリエディタ] のテキスト領域に、次の GoogleSQL クエリを入力します。

    #standardSQL
    SELECT
    *
    FROM
    ML.EVALUATE(MODEL `bqml_tutorial.sample_model`, (
    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 '20170701' AND '20170801'))
    
  3. [実行] をクリックします。

  4. クエリが完了したら、クエリテキスト領域の下にある [結果] タブをクリックします。結果は次のようになります。

    +--------------------+---------------------+--------------------+--------------------+---------------------+----------+
    |     precision      |       recall        |      accuracy      |      f1_score      |      log_loss       | roc_auc  |
    +--------------------+---------------------+--------------------+--------------------+---------------------+----------+
    | 0.4451901565995526 | 0.08879964301651048 | 0.9716829479411401 | 0.1480654761904762 | 0.07921781778780206 | 0.970706 |
    +--------------------+---------------------+--------------------+--------------------+---------------------+----------+
    

    ロジスティック回帰を使用しているため、結果には次の列が含まれます。

    • precision - 分類モデルの指標。陽性のクラスの予測でモデルが正しかった確率を表します。

    • recall - 「全陽性のラベルの中でモデルが正しく識別したラベルの数は?」という質問に回答する分類モデルの指標。

    • accuracy - 分類モデルの予測のうち、正解の割合。

    • f1_score - モデルの精度を表す尺度。f1 値は適合率と再現率の調和平均を表します。最も精度の高い f1 値は 1 で、最も精度の悪い値は 0 です。

    • log_loss - ロジスティック回帰で使用される損失関数。モデルの予測が正しいラベルからどのくらい離れているかを表します。

    • roc_auc - ROC 曲線の下の面積。これは、無作為に選択した陽性のサンプルが陽性に分類される確率が、無作為に選択した陰性のサンプルが陽性に分類される確率よりも高い可能性を表します。詳細については、ML 集中講座の分類をご覧ください。

BigQuery DataFrames

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

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

import bigframes.pandas as bpd

# Select model you'll use for evaluating. `read_gbq_model` loads model data from a
# BigQuery, but you could also use the `model` object from the previous steps.
model = bpd.read_gbq_model(
    your_model_id,  # For example: "bqml_tutorial.sample_model",
)

# The filters parameter limits the number of tables scanned by the query.
# The date range scanned is July 1, 2017 to August 1, 2017. This is the
# data you're using to evaluate the predictive performance of the model.
# It was collected in the month immediately following the time period
# spanned by the training data.
df = bpd.read_gbq_table(
    "bigquery-public-data.google_analytics_sample.ga_sessions_*",
    filters=[
        ("_table_suffix", ">=", "20170701"),
        ("_table_suffix", "<=", "20170801"),
    ],
)

transactions = df["totals"].struct.field("transactions")
label = transactions.notnull().map({True: 1, False: 0}).rename("label")
operating_system = df["device"].struct.field("operatingSystem")
operating_system = operating_system.fillna("")
is_mobile = df["device"].struct.field("isMobile")
country = df["geoNetwork"].struct.field("country").fillna("")
pageviews = df["totals"].struct.field("pageviews").fillna(0)
features = bpd.DataFrame(
    {
        "os": operating_system,
        "is_mobile": is_mobile,
        "country": country,
        "pageviews": pageviews,
    }
)

# Some models include a convenient .score(X, y) method for evaluation with a preset accuracy metric:

# Because you performed a logistic regression, the results include the following columns:

# - precision — A metric for classification models. Precision identifies the frequency with
# which a model was correct when predicting the positive class.

# - recall — A metric for classification models that answers the following question:
# Out of all the possible positive labels, how many did the model correctly identify?

# - accuracy — Accuracy is the fraction of predictions that a classification model got right.

# - f1_score — A measure of the accuracy of the model. The f1 score is the harmonic average of
# the precision and recall. An f1 score's best value is 1. The worst value is 0.

# - log_loss — The loss function used in a logistic regression. This is the measure of how far the
# model's predictions are from the correct labels.

# - roc_auc — The area under the ROC curve. This is the probability that a classifier is more confident that
# a randomly chosen positive example
# is actually positive than that a randomly chosen negative example is positive. For more information,
# see ['Classification']('https://developers.google.com/machine-learning/crash-course/classification/video-lecture')
# in the Machine Learning Crash Course.

model.score(features, label)
#    precision    recall  accuracy  f1_score  log_loss   roc_auc
# 0   0.412621  0.079143  0.985074  0.132812  0.049764  0.974285
# [1 rows x 6 columns]

モデルを使用して結果を予測する

モデルの評価を行ったので、モデルを使用して結果を予測します。このモデルを使用して、ウェブサイトの訪問者が行ったトランザクションの数を国別に予測します。

SQL

結果の予測に使用するクエリは次のとおりです。

#standardSQL
SELECT
country,
SUM(predicted_label) as total_predicted_purchases
FROM
ML.PREDICT(MODEL `bqml_tutorial.sample_model`, (
SELECT
IFNULL(device.operatingSystem, "") AS os,
device.isMobile AS is_mobile,
IFNULL(totals.pageviews, 0) AS pageviews,
IFNULL(geoNetwork.country, "") AS country
FROM
`bigquery-public-data.google_analytics_sample.ga_sessions_*`
WHERE
_TABLE_SUFFIX BETWEEN '20170701' AND '20170801'))
GROUP BY country
ORDER BY total_predicted_purchases DESC
LIMIT 10

クエリの詳細

先頭の SELECT ステートメントで、country 列を取得し、predicted_label 列を合計します。この列は、ML.PREDICT 関数によって生成されます。ML.PREDICT 関数を使用した場合は、モデルの出力列名は predicted_<label_column_name> です。線形回帰モデルの場合、predicted_labellabel の推定値になります。ロジスティック回帰モデルでは、predicted_label が最も可能性の高いラベルで、この場合、0 または 1 になります。

ML.PREDICT 関数は、モデル bqml_tutorial.sample_model を使用して結果を予測するために使われます。

このクエリでネストしている SELECT ステートメントと FROM 句は CREATE MODEL クエリと同じです。

WHERE 句 - _TABLE_SUFFIX BETWEEN '20170701' AND '20170801' - クエリによってスキャンされるテーブルの数を制限します。スキャンする日付の範囲は 2017 年 7 月 1 日から 2017 年 8 月 1 日までです。このデータは予測に使用されます。これは、トレーニング データの期間の直後の月に収集されています。

GROUP BYORDER BY 句は、結果を国別に分類し、予測された購入回数の合計を降順で並べ替えます。

ここでは、LIMIT 句を使用して上位 10 件のみを表示します。

ML.PREDICT クエリを実行する

モデルを使用して結果を予測するクエリを実行するには:

  1. Google Cloud コンソールで、[クエリを新規作成] ボタンをクリックします。

  2. [クエリエディタ] のテキスト領域に、次の GoogleSQL クエリを入力します。

    #standardSQL
    SELECT
    country,
    SUM(predicted_label) as total_predicted_purchases
    FROM
    ML.PREDICT(MODEL `bqml_tutorial.sample_model`, (
    SELECT
    IFNULL(device.operatingSystem, "") AS os,
    device.isMobile AS is_mobile,
    IFNULL(totals.pageviews, 0) AS pageviews,
    IFNULL(geoNetwork.country, "") AS country
    FROM
    `bigquery-public-data.google_analytics_sample.ga_sessions_*`
    WHERE
    _TABLE_SUFFIX BETWEEN '20170701' AND '20170801'))
    GROUP BY country
    ORDER BY total_predicted_purchases DESC
    LIMIT 10
    
  3. [実行] をクリックします。

  4. クエリが完了したら、クエリテキスト領域の下にある [結果] タブをクリックします。結果は次のようになります。

+----------------+---------------------------+
|    country     | total_predicted_purchases |
+----------------+---------------------------+
| United States  |                       209 |
| Taiwan         |                         6 |
| Canada         |                         4 |
| Turkey         |                         2 |
| India          |                         2 |
| Japan          |                         2 |
| Indonesia      |                         1 |
| United Kingdom |                         1 |
| Guyana         |                         1 |
+----------------+---------------------------+

BigQuery DataFrames

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

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

import bigframes.pandas as bpd

# Select model you'll use for predicting.
# `read_gbq_model` loads model data from
# BigQuery, but you could also use the `model`
# object from the previous steps.
model = bpd.read_gbq_model(
    your_model_id,  # For example: "bqml_tutorial.sample_model",
)

# The filters parameter limits the number of tables scanned by the query.
# The date range scanned is July 1, 2017 to August 1, 2017. This is the
# data you're using to make the prediction.
# It was collected in the month immediately following the time period
# spanned by the training data.
df = bpd.read_gbq_table(
    "bigquery-public-data.google_analytics_sample.ga_sessions_*",
    filters=[
        ("_table_suffix", ">=", "20170701"),
        ("_table_suffix", "<=", "20170801"),
    ],
)

operating_system = df["device"].struct.field("operatingSystem")
operating_system = operating_system.fillna("")
is_mobile = df["device"].struct.field("isMobile")
country = df["geoNetwork"].struct.field("country").fillna("")
pageviews = df["totals"].struct.field("pageviews").fillna(0)
features = bpd.DataFrame(
    {
        "os": operating_system,
        "is_mobile": is_mobile,
        "country": country,
        "pageviews": pageviews,
    }
)
# Use Logistic Regression predict method to predict results
# using your model.
# Find more information here in
# [BigFrames](https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.linear_model.LogisticRegression#bigframes_ml_linear_model_LogisticRegression_predict)

predictions = model.predict(features)

# Call groupby method to group predicted_label by country.
# Call sum method to get the total_predicted_label by country.
total_predicted_purchases = predictions.groupby(["country"])[
    ["predicted_label"]
].sum()

# Call the sort_values method with the parameter
# ascending = False to get the highest values.
# Call head method to limit to the 10 highest values.
total_predicted_purchases.sort_values(ascending=False).head(10)

# country
# United States    220
# Taiwan             8
# Canada             7
# India              2
# Japan              2
# Turkey             2
# Australia          1
# Brazil             1
# Germany            1
# Guyana             1
# Name: predicted_label, dtype: Int64

ユーザーごとの購入数を予測する

この例では、ウェブサイトの訪問者が行うトランザクションの数を予測します。

SQL

GROUP BY 句を除くと、このクエリは前のクエリと同じです。ここでは、GROUP BY 句(GROUP BY fullVisitorId)を使用して、結果を訪問者 ID で分類します。

クエリを実行するには:

  1. Google Cloud コンソールで、[クエリを新規作成] ボタンをクリックします。

  2. [クエリエディタ] のテキスト領域に、次の GoogleSQL クエリを入力します。

    #standardSQL
    SELECT
    fullVisitorId,
    SUM(predicted_label) as total_predicted_purchases
    FROM
    ML.PREDICT(MODEL `bqml_tutorial.sample_model`, (
    SELECT
    IFNULL(device.operatingSystem, "") AS os,
    device.isMobile AS is_mobile,
    IFNULL(totals.pageviews, 0) AS pageviews,
    IFNULL(geoNetwork.country, "") AS country,
    fullVisitorId
    FROM
    `bigquery-public-data.google_analytics_sample.ga_sessions_*`
    WHERE
    _TABLE_SUFFIX BETWEEN '20170701' AND '20170801'))
    GROUP BY fullVisitorId
    ORDER BY total_predicted_purchases DESC
    LIMIT 10
    
  3. [実行] をクリックします。

  4. クエリが完了したら、クエリテキスト領域の下にある [結果] タブをクリックします。結果は次のようになります。

    +---------------------+---------------------------+
    |    fullVisitorId    | total_predicted_purchases |
    +---------------------+---------------------------+
    | 9417857471295131045 |                         4 |
    | 2158257269735455737 |                         3 |
    | 5073919761051630191 |                         3 |
    | 7104098063250586249 |                         2 |
    | 4668039979320382648 |                         2 |
    | 1280993661204347450 |                         2 |
    | 7701613595320832147 |                         2 |
    | 0376394056092189113 |                         2 |
    | 9097465012770697796 |                         2 |
    | 4419259211147428491 |                         2 |
    +---------------------+---------------------------+
    

BigQuery DataFrames

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

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


import bigframes.pandas as bpd

# Select model you'll use for predicting.
# `read_gbq_model` loads model data from
# BigQuery, but you could also use the `model`
# object from the previous steps.
model = bpd.read_gbq_model(
    your_model_id,  # For example: "bqml_tutorial.sample_model",
)

# The filters parameter limits the number of tables scanned by the query.
# The date range scanned is July 1, 2017 to August 1, 2017. This is the
# data you're using to make the prediction.
# It was collected in the month immediately following the time period
# spanned by the training data.
df = bpd.read_gbq_table(
    "bigquery-public-data.google_analytics_sample.ga_sessions_*",
    filters=[
        ("_table_suffix", ">=", "20170701"),
        ("_table_suffix", "<=", "20170801"),
    ],
)

operating_system = df["device"].struct.field("operatingSystem")
operating_system = operating_system.fillna("")
is_mobile = df["device"].struct.field("isMobile")
country = df["geoNetwork"].struct.field("country").fillna("")
pageviews = df["totals"].struct.field("pageviews").fillna(0)
full_visitor_id = df["fullVisitorId"]

features = bpd.DataFrame(
    {
        "os": operating_system,
        "is_mobile": is_mobile,
        "country": country,
        "pageviews": pageviews,
        "fullVisitorId": full_visitor_id,
    }
)

predictions = model.predict(features)

# Call groupby method to group predicted_label by visitor.
# Call sum method to get the total_predicted_label by visitor.
total_predicted_purchases = predictions.groupby(["fullVisitorId"])[
    ["predicted_label"]
].sum()

# Call the sort_values method with the parameter
# ascending = False to get the highest values.
# Call head method to limit to the 10 highest values.
total_predicted_purchases.sort_values(ascending=False).head(10)

# fullVisitorId
# 9417857471295131045    4
# 0376394056092189113    2
# 0456807427403774085    2
# 057693500927581077     2
# 112288330928895942     2
# 1280993661204347450    2
# 2105122376016897629    2
# 2158257269735455737    2
# 2969418676126258798    2
# 489038402765684003     2
# Name: predicted_label, dtype: Int64

クリーンアップ

このページで使用したリソースに関して Google Cloud アカウントに課金されないようにするには、次の操作を行います。

  • 作成したプロジェクトを削除する。
  • または、プロジェクトを保存して、データセットを削除する。

データセットを削除する

プロジェクトを削除すると、プロジェクト内のデータセットとテーブルがすべて削除されます。プロジェクトを再利用する場合は、このチュートリアルで作成したデータセットを削除できます。

  1. 必要に応じて、Google Cloud コンソールで [BigQuery] ページを開きます。

    [BigQuery] ページに移動

  2. ナビゲーションで、作成した bqml_tutorial データセットを選択します。

  3. ウィンドウの右側にある [データセットを削除] をクリックします。この操作を行うと、データセット、テーブル、すべてのデータが削除されます。

    データセットの削除

  4. [データセットの削除] ダイアログ ボックスでデータセットの名前(bqml_tutorial)を入力して、[削除] をクリックします。

プロジェクトを削除する

プロジェクトを削除するには:

  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.

次のステップ