BigQuery ML에서 머신러닝 모델 만들기

이 튜토리얼에서는 Google Cloud 콘솔을 사용하여 BigQuery ML을 소개합니다.

BigQuery ML을 사용하면 BigQuery에서 SQL 쿼리 및 Python 코드를 사용하여 머신러닝 모델을 만들고 실행할 수 있습니다. BigQuery ML의 목표는 SQL 실무자가 기존 도구를 사용하여 모델을 빌드할 수 있도록 지원하여 머신러닝을 대중화하고 데이터 이동의 필요성을 제거하여 개발 속도를 높이는 데 있습니다.

이 튜토리얼에서는 BigQuery용 Google 애널리틱스 샘플 데이터 세트 샘플을 사용하여 웹사이트 방문자의 트랜잭션 여부를 예측하는 모델을 만듭니다. 애널리틱스 데이터 세트 스키마에 대한 자세한 내용은 애널리틱스 고객센터의 BigQuery Export 스키마를 참조하세요.

목표

이 튜토리얼에서는 다음을 수행합니다.

  • BigQuery ML에서 CREATE MODEL 문을 사용하여 바이너리 로지스틱 회귀 모델 만들기
  • ML.EVALUATE 함수를 사용하여 ML 모델 평가
  • ML.PREDICT 함수를 사용하여 ML 모델로 예측

비용

이 튜토리얼에서는 다음을 포함하여 Google Cloud의 청구 가능한 구성요소가 사용됩니다.

  • BigQuery
  • BigQuery ML

BigQuery 비용에 대한 자세한 내용은 BigQuery 가격 책정 페이지를 참조하세요.

BigQuery ML 비용에 대한 자세한 내용은 BigQuery ML 가격 책정을 참조하세요.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  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. 데이터 세트 만들기 페이지에서 다음을 수행합니다.

    • 데이터 세트 IDbqml_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') 절은 로지스틱 회귀 모델을 만든다는 것을 나타냅니다. 로지스틱 회귀 모델은 입력 데이터를 두 클래스로 분할하려 시도한 후 데이터가 클래스 중 하나일 확률을 제공합니다. 일반적으로 감지하려는 항목(예: 이메일이 스팸인지 여부)은 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 콘솔을 사용합니다.

머신러닝에서는 데이터를 사용하여 예측할 수 있는 모델을 만듭니다. 모델은 기본적으로 입력을 받으면 입력에 계산을 적용하여 예측 출력을 생성하는 함수입니다.

머신러닝 알고리즘은 예측이 이미 알려져 있는 여러 예(사용자 구매의 이전 데이터 등)를 사용하고 모델의 여러 가중치를 반복적으로 조정하여 작동합니다. 이에 따라 모델의 예측이 실제 값과 일치하게 됩니다. 모델이 잘못되었음을 나타내는 손실이라는 통계를 최소화하여 이를 수행합니다.

반복할 때마다 손실이 감소할 것입니다(이상적으로는 0으로). 손실이 0인 경우 이는 모델이 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 함수를 사용합니다.

이 가이드에서는 트랜잭션을 감지하는 이진 분류 모델을 사용합니다. 두 클래스는 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 곡선 아래 영역입니다. 분류 기준에서 임의로 선택한 양성 예시가 실제로 양성일 확률이 임의로 선택한 음성 예시가 양성일 확률보다 높습니다. 자세한 내용은 머신러닝 단기집중과정의 분류를 참조하세요.

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. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

다음 단계