BigQuery DataFrames 사용해 보기

BigQuery DataFrames는 확장 가능한 Python 분석 및 머신러닝 (ML)을 BigQuery에 제공합니다. 계산은 서버 측 처리를 통해 BigQuery에서 실행되므로 로컬 또는 노트북 메모리에 제약받지 않고 대규모 데이터 세트를 분석하고 모델링할 수 있습니다. SQL을 작성하지 않고도 pandas (bigframes.pandas) 및 BigQuery ML(bigframes.bigquery)과 유사한 구문을 사용할 수 있습니다.

이 빠른 시작에서는 BigQuery notebook에서 BigQuery DataFrames API 를 사용하여 다음 분석 및 ML 작업을 수행합니다.

시작하기 전에

  1. 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

  2. 프로젝트에 결제가 사용 설정되어 있는지 확인합니다 Google Cloud .

  3. BigQuery API가 사용 설정되었는지 확인합니다.

    API 사용 설정

    새 프로젝트를 만들면 BigQuery API가 자동으로 사용 설정됩니다.

필수 권한

노트북을 만들고 실행하려면 다음 Identity and Access Management(IAM) 역할이 필요합니다.

노트북 만들기

BigQuery 편집자에서 노트북 만들기의 안내에 따라 새 노트북을 만듭니다.

BigQuery DataFrames 사용해 보기

다음 단계에 따라 BigQuery DataFrames를 사용합니다.

  1. 노트북에 새 코드 셀을 만듭니다.
  2. 코드 셀에 다음 코드를 추가합니다.

    import bigframes.pandas as bpd
    
    # Set BigQuery DataFrames options
    # Note: The project option is not required in all environments.
    # On BigQuery Studio, the project ID is automatically detected.
    bpd.options.bigquery.project = your_gcp_project_id
    
    # Use "partial" ordering mode to generate more efficient queries, but the
    # order of the rows in DataFrames may not be deterministic if you have not
    # explictly sorted it. Some operations that depend on the order, such as
    # head() will not function until you explictly order the DataFrame. Set the
    # ordering mode to "strict" (default) for more pandas compatibility.
    bpd.options.bigquery.ordering_mode = "partial"
    
    # Create a DataFrame from a BigQuery table
    query_or_table = "bigquery-public-data.ml_datasets.penguins"
    df = bpd.read_gbq(query_or_table)
    
    # Efficiently preview the results using the .peek() method.
    df.peek()
    
  3. bpd.options.bigquery.project = your_gcp_project_id 줄을 수정하여 프로젝트 ID를 지정합니다. Google Cloud 예를 들면, bpd.options.bigquery.project = "myProjectID"

  4. 코드 셀을 실행합니다.

    코드는 펭귄에 관한 데이터가 포함된 DataFrame 객체를 반환합니다.

  5. 노트북에 새 코드 셀을 만들고 다음 코드를 추가합니다.

    # Use the DataFrame just as you would a pandas DataFrame, but calculations
    # happen in the BigQuery query engine instead of the local system.
    average_body_mass = df["body_mass_g"].mean()
    print(f"average_body_mass: {average_body_mass}")
    
  6. 코드 셀을 실행합니다.

    코드는 펭귄의 평균 몸무게를 계산하고 Google Cloud 콘솔에 출력합니다.

  7. 노트북에 새 코드 셀을 만들고 다음 코드를 추가합니다.

    import bigframes.bigquery as bbq
    from google.cloud import bigquery
    
    # Ensure a dataset exists to store the model
    client = bigquery.Client(project=bpd.options.bigquery.project)
    client.create_dataset("bq_quickstart", exists_ok=True)
    
    # Filter down to the Adelie Penguin species
    adelie_data = df[df.species == "Adelie Penguin (Pygoscelis adeliae)"]
    
    # Drop the columns that are not needed
    adelie_data = adelie_data.drop(columns=["species"])
    
    # Drop rows with nulls to get the training data
    training_data = adelie_data.dropna()
    
    # Train a linear regression model
    model_name = f"{bpd.options.bigquery.project}.bq_quickstart.penguin_weight"
    model_metadata = bbq.ml.create_model(
        model_name,
        replace=True,
        options={"model_type": "LINEAR_REG"},
        training_data=training_data.rename(columns={"body_mass_g": "label"}),
    )
    
    # Evaluate the model
    evaluation = bbq.ml.evaluate(model_name)
    print(evaluation)
    
  8. 코드 셀을 실행합니다.

    코드는 BigQuery에서 직접 선형 회귀 모델을 학습시키고 모델의 평가 측정항목을 반환합니다.

정리

비용이 청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.

프로젝트를 삭제하는 방법은 다음과 같습니다.

  1. 콘솔 Google Cloud 에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

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

다음 단계

  • BigQuery DataFrames에 대해 계속 알아봅니다.
  • BigQuery DataFrames를 사용하여 그래프를 시각화하는 방법 알아보기 .
  • BigQuery DataFrames 노트북을 사용하는 방법 알아보기