建立 k-means 模型,將倫敦自行車租用資料集分群

本教學課程說明如何使用 BigQuery ML 中的 k-means 模型,找出資料集中的叢集。

將資料分組成叢集的 k-means 演算法,是一種非監督式機器學習。監督式機器學習是關於預測性分析,而非監督式機器學習著重在描述性分析。非監督式機器學習可協助您瞭解資料,進而做出資料導向的決策。

本教學課程中的查詢使用地理空間分析服務提供的地理位置函式,詳情請參閱「地理空間分析簡介」。

本教學課程使用倫敦自行車租用公開資料集。資料包括租用開始和結束的時間戳記、車站名稱,以及騎乘時間。

目標

本教學課程會逐步引導您完成下列工作:

  • 檢查用於訓練模型的資料。
  • 建立 k-means 分群模型。
  • 使用 BigQuery ML 的叢集視覺化功能,解讀產生的資料叢集。
  • 在 k-means 模型上執行 ML.PREDICT 函式,預測一組自行車租借站可能屬於哪個叢集。

費用

本教學課程使用 Google Cloud的計費元件,包括:

  • BigQuery
  • BigQuery ML

如要瞭解 BigQuery 費用,請參閱 BigQuery 定價頁面。

如要瞭解 BigQuery ML 費用,請參閱 BigQuery ML 定價

事前準備

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. 新專案會自動啟用 BigQuery。如要在現有專案中啟用 BigQuery,請前往

    啟用 BigQuery API。

    啟用 API 時所需的角色

    如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「服務使用情形管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色

    啟用 API

所需權限

  • 如要建立資料集,您需要 bigquery.datasets.create IAM 權限。

  • 如要建立模型,您必須具備下列權限:

    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
  • 如要執行推論,您需要下列權限:

    • bigquery.models.getData
    • bigquery.jobs.create

如要進一步瞭解 BigQuery 中的 IAM 角色和權限,請參閱「IAM 簡介」。

建立資料集

建立 BigQuery 資料集來儲存 k 平均值模型:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往 BigQuery 頁面

  2. 點選左側窗格中的 「Explorer」

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」窗格中,按一下專案名稱。

  4. 依序點按 「View actions」(查看動作) >「Create dataset」(建立資料集)

    建立資料集。

  5. 在「建立資料集」頁面中,執行下列操作:

    • 在「Dataset ID」(資料集 ID) 中輸入 bqml_tutorial

    • 針對「Location type」(位置類型) 選取「Multi-region」(多區域),然後選取「EU (multiple regions in European Union)」(歐盟 (多個歐盟區域))

      倫敦自行車租用公開資料集存放在 EU 多區域。資料集必須位於相同位置。

    • 其餘設定請保留預設狀態,然後按一下「建立資料集」

      建立資料集頁面。

檢查訓練資料

檢查要用來訓練 k-means 模型的資料。在本教學課程中,您將根據下列屬性來將自行車站分群:

  • 租用時間
  • 每日租用次數
  • 距市中心的距離

SQL

這項查詢會擷取自行車的租用資料 (包括 start_station_nameduration 資料欄),並將該資料與車站資訊結合。包括建立計算結果欄,其中包含車站與市中心的距離。然後,查詢會計算 stationstats 資料欄中的車站屬性 (包括平均騎乘時間和租用次數),以及計算出的 distance_from_city_center 資料欄。

請按照下列步驟檢查訓練資料:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 在查詢編輯器中貼入下列查詢,然後點選「執行」

    WITH
    hs AS (
      SELECT
        h.start_station_name AS station_name,
        IF(
          EXTRACT(DAYOFWEEK FROM h.start_date) = 1
            OR EXTRACT(DAYOFWEEK FROM h.start_date) = 7,
          'weekend',
          'weekday') AS isweekday,
        h.duration,
        ST_DISTANCE(ST_GEOGPOINT(s.longitude, s.latitude), ST_GEOGPOINT(-0.1, 51.5)) / 1000
          AS distance_from_city_center
      FROM
        `bigquery-public-data.london_bicycles.cycle_hire` AS h
      JOIN
        `bigquery-public-data.london_bicycles.cycle_stations` AS s
        ON
          h.start_station_id = s.id
      WHERE
        h.start_date
        BETWEEN CAST('2015-01-01 00:00:00' AS TIMESTAMP)
        AND CAST('2016-01-01 00:00:00' AS TIMESTAMP)
    ),
    stationstats AS (
      SELECT
        station_name,
        isweekday,
        AVG(duration) AS duration,
        COUNT(duration) AS num_trips,
        MAX(distance_from_city_center) AS distance_from_city_center
      FROM
        hs
      GROUP BY
        station_name, isweekday
    )
    SELECT *
    FROM
    stationstats
    ORDER BY
    distance_from_city_center ASC;

結果應如下所示:

查詢結果

BigQuery DataFrames

在嘗試這個範例之前,請按照使用 BigQuery DataFrames 的 BigQuery 快速入門導覽課程,完成 BigQuery DataFrames 設定。詳情請參閱 BigQuery DataFrames 參考文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定 ADC」。

import datetime
import typing

import pandas as pd
from shapely.geometry import Point

import bigframes
import bigframes.bigquery as bbq
import bigframes.geopandas
import bigframes.pandas as bpd

bigframes.options.bigquery.project = your_gcp_project_id
# Compute in the EU multi-region to query the London bicycles dataset.
bigframes.options.bigquery.location = "EU"

# Extract the information you'll need to train the k-means model in this
# tutorial. Use the read_gbq function to represent cycle hires
# data as a DataFrame.
h = bpd.read_gbq(
    "bigquery-public-data.london_bicycles.cycle_hire",
    col_order=["start_station_name", "start_station_id", "start_date", "duration"],
).rename(
    columns={
        "start_station_name": "station_name",
        "start_station_id": "station_id",
    }
)

# Use GeoSeries.from_xy and BigQuery.st_distance to analyze geographical
# data. These functions determine spatial relationships between
# geographical features.
cycle_stations = bpd.read_gbq("bigquery-public-data.london_bicycles.cycle_stations")