이 튜토리얼의 뒷부분에서 만드는 모델은 학습을 위해 데이터 세트가 필요합니다.
이 튜토리얼에 사용되는 데이터는 펭귄의 3가지 종에 대한 세부정보가 포함된 공개적으로 사용 가능한 데이터 세트입니다. 다음 데이터는 펭귄의 3가지 종을 예측하는 데 사용됩니다.
island - 펭귄의 종이 발견된 섬입니다.
culmen_length_mm - 펭귄 부리 위쪽으로 이어지는 융선의 길이입니다.
culmen_depth_mm - 펭귄 부리의 높이입니다.
flipper_length_mm - 지느러미처럼 생긴 펭귄 날개의 길이입니다.
body_mass_g - 펭귄의 체중입니다.
sex - 펭귄의 성별입니다.
데이터 다운로드, 사전 처리 및 분할
이 섹션에서는 공개적으로 사용 가능한 BigQuery 데이터 세트를 다운로드하고 데이터를 준비합니다. 데이터를 준비하려면 다음을 수행하세요.
범주형 특성(숫자 대신 문자열로 설명되는 특성)을 숫자 데이터로 변환합니다. 예를 들어 세 가지 유형의 펭귄 이름을 숫자 값 0, 1, 2로 변환합니다.
데이터 세트에서 사용되지 않는 열을 모두 삭제합니다.
사용할 수 없는 행을 모두 삭제합니다.
데이터를 두 개의 서로 다른 데이터 세트로 분할합니다. 각 데이터 세트는 pandas DataFrame 객체에 저장됩니다.
df_trainDataFrame에는 모델을 학습시키는 데 사용되는 데이터가 포함되어 있습니다.
df_for_predictionDataFrame에는 예측을 생성하는 데 사용되는 데이터가 포함됩니다.
데이터를 처리한 후 이 코드는 범주형 3개 열의 숫자 값을 문자열 값에 매핑한 다음 데이터가 어떻게 표시되는지 확인할 수 있도록 인쇄합니다.
데이터를 다운로드하고 처리하려면 노트북에서 다음 코드를 실행합니다.
importnumpyasnpimportpandasaspdLABEL_COLUMN="species"# Define the BigQuery source datasetBQ_SOURCE="bigquery-public-data.ml_datasets.penguins"# Define NA valuesNA_VALUES=["NA","."]# Download a tabletable=bq_client.get_table(BQ_SOURCE)df=bq_client.list_rows(table).to_dataframe()# Drop unusable rowsdf=df.replace(to_replace=NA_VALUES,value=np.NaN).dropna()# Convert categorical columns to numericdf["island"],island_values=pd.factorize(df["island"])df["species"],species_values=pd.factorize(df["species"])df["sex"],sex_values=pd.factorize(df["sex"])# Split into a training and holdout datasetdf_train=df.sample(frac=0.8,random_state=100)df_for_prediction=df[~df.index.isin(df_train.index)]# Map numeric values to string valuesindex_to_island=dict(enumerate(island_values))index_to_species=dict(enumerate(species_values))index_to_sex=dict(enumerate(sex_values))# View the mapped island, species, and sex dataprint(index_to_island)print(index_to_species)print(index_to_sex)
처음 세 개의 값은 펭귄이 서식할 수 있는 섬입니다. 두 번째 세 값은 이 튜토리얼의 끝부분에서 받는 예측에 매핑되므로 중요합니다. 세 번째 행은 FEMALE 성별 특성을 0에 매핑하고 MALE 성별 특성을 1에 매핑합니다.
모델 학습을 위한 테이블 형식 데이터 세트 만들기
이전 단계에서 데이터를 다운로드하고 처리했습니다. 이 단계에서는 df_trainDataFrame에 저장된 데이터를 BigQuery 데이터 세트에 로드합니다. 그런 다음 BigQuery 데이터 세트를 사용하여 Vertex AI 테이블 형식 데이터 세트를 만듭니다. 이 테이블 형식 데이터 세트는 모델을 학습시키는 데 사용됩니다. 자세한 내용은 관리형 데이터 세트 사용을 참조하세요.
BigQuery 데이터 세트 만들기
Vertex AI 데이터 세트를 만드는 데 사용되는 BigQuery 데이터 세트를 만들려면 다음 코드를 실행합니다. create_dataset 명령어는 새 BigQuery DataSet를 반환합니다.
BigQuery 데이터 세트를 Vertex AI 테이블 형식 데이터 세트로 변환하려면 다음 코드를 실행합니다. 테이블 형식 데이터를 사용하여 학습을 수행하는 데 필요한 행 수에 관한 경고는 무시할 수 있습니다. 이 튜토리얼의 목적은 예측을 가져오는 방법을 빠르게 보여주기 위한 것이며, 비교적 적은 데이터 집합을 사용하여 예측을 생성하는 방법을 보여줍니다. 실제 시나리오에서는 표 형식 데이터 세트에 최소 1,000개 이상 행이 필요합니다. create_from_dataframe 명령어는 Vertex AI TabularDataset를 반환합니다.
# Create a Vertex AI tabular dataset
dataset = aiplatform.TabularDataset.create_from_dataframe(
df_source=df_train,
staging_path=f"bq://{bq_dataset_id}.table-unique",
display_name="sample-penguins",
)
이제 모델을 학습시키는 데 사용할 Vertex AI 테이블 형식 데이터 세트를 확보했습니다.
(선택사항) BigQuery에서 공개 데이터 세트 보기
이 튜토리얼에 사용된 공개 데이터를 보려면 BigQuery에서 열면 됩니다.
Google Cloud의 검색에서 BigQuery를 입력한 다음 Return 키를 누릅니다.
검색 결과에서 BigQuery를 클릭합니다.
Explorer 창에서 bigquery-public-data를 펼칩니다.
bigquery-public-data에서 ml_datasets를 펼친 후 penguins를 클릭합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[],[],null,["# Create a Vertex AI tabular dataset\n\nThe model you create later in this tutorial requires a *dataset* to train it. The data that this tutorial uses is a publicly available dataset that contains details about three species of penguins. The following data are used to predict which of the three species a penguin is.\n\n\u003cbr /\u003e\n\n- `island` - The island where a species of penguin is found.\n- `culmen_length_mm` - The length of the ridge along the top of the bill of a penguin.\n- `culmen_depth_mm` - The height of the bill of a penguin.\n- `flipper_length_mm` - The length of the flipper-like wing of a penguin.\n- `body_mass_g` - The mass of the body of a penguin.\n- `sex` - The sex of the penguin.\n\nDownload, preprocess, and split the data\n----------------------------------------\n\nIn this section, you download the publicly available BigQuery dataset\nand prepare its data. To prepare the data, you do the following:\n\n- Convert categorical features (features described with a string instead of a\n number) to numeric data. For example, you convert the names of the three types\n of penguins to the numerical values `0`, `1`, and `2`.\n\n- Remove any columns in the dataset that aren't used.\n\n- Remove any rows that cannot be used.\n\n- Split the data into two distinct sets of data. Each set of data is stored in a\n [pandas `DataFrame`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html)\n object.\n\n - The `df_train` `DataFrame` contains data used to train your model.\n\n - the `df_for_prediction` `DataFrame` contains data used to generate predictions.\n\nAfter processing the data, the code maps the three categorical columns'\nnumerical values to their string values, then prints them so that you can see\nwhat the data looks like.\n\nTo download and process your data, run the following code in your notebook: \n\n import numpy as np\n import pandas as pd\n\n LABEL_COLUMN = \"species\"\n\n # Define the BigQuery source dataset\n BQ_SOURCE = \"bigquery-public-data.ml_datasets.penguins\"\n\n # Define NA values\n NA_VALUES = [\"NA\", \".\"]\n\n # Download a table\n table = bq_client.get_table(BQ_SOURCE)\n df = bq_client.list_rows(table).to_dataframe()\n\n # Drop unusable rows\n df = df.replace(to_replace=NA_VALUES, value=np.NaN).dropna()\n\n # Convert categorical columns to numeric\n df[\"island\"], island_values = pd.factorize(df[\"island\"])\n df[\"species\"], species_values = pd.factorize(df[\"species\"])\n df[\"sex\"], sex_values = pd.factorize(df[\"sex\"])\n\n # Split into a training and holdout dataset\n df_train = df.sample(frac=0.8, random_state=100)\n df_for_prediction = df[~df.index.isin(df_train.index)]\n\n # Map numeric values to string values\n index_to_island = dict(enumerate(island_values))\n index_to_species = dict(enumerate(species_values))\n index_to_sex = dict(enumerate(sex_values))\n\n # View the mapped island, species, and sex data\n print(index_to_island)\n print(index_to_species)\n print(index_to_sex)\n\nThe following are the printed mapped values for characteristics that are not\nnumeric: \n\n {0: 'Dream', 1: 'Biscoe', 2: 'Torgersen'}\n {0: 'Adelie Penguin (Pygoscelis adeliae)', 1: 'Chinstrap penguin (Pygoscelis antarctica)', 2: 'Gentoo penguin (Pygoscelis papua)'}\n {0: 'FEMALE', 1: 'MALE'}\n\nThe first three values are the islands a penguin might inhabit. The second three\nvalues are important because they map to the predictions you receive at the end\nof this tutorial. The third row shows the `FEMALE` sex characteristic maps to\n`0` and the `MALE` the sex characteristic maps to `1`.\n\nCreate a tabular dataset for training your model\n------------------------------------------------\n\nIn the previous step you downloaded and processed your data. In this step, you\nload the data stored in your `df_train` `DataFrame` into a BigQuery\ndataset. Then, you use the BigQuery dataset to create a\nVertex AI tabular dataset. This tabular dataset is used to train your\nmodel. For more information, see [Use managed\ndatasets](/vertex-ai/docs/training/using-managed-datasets).\n\n### Create a BigQuery dataset\n\nTo create your BigQuery dataset that's used to create a\nVertex AI dataset, run the following code. The [`create_dataset`](https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.client.Client#google_cloud_bigquery_client_Client_create_dataset) command\nreturns a new BigQuery [`DataSet`](https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.dataset.Dataset). \n\n # Create a BigQuery dataset\n bq_dataset_id = f\"{project_id}.dataset_id_unique\"\n bq_dataset = bigquery.Dataset(bq_dataset_id)\n bq_client.create_dataset(bq_dataset, exists_ok=True)\n\n### Create a Vertex AI tabular dataset\n\nTo convert your BigQuery dataset a Vertex AI tabular\ndataset, run the following code. You can ignore the warning about the required\nnumber of rows to train using tabular data. Because the purpose of this tutorial\nis to quickly show you how to get predictions, a relatively small set of data is\nused to show you how to generate predictions. In a real world scenario, you want\nat least 1000 rows in a tabular dataset. The\n[`create_from_dataframe`](https://cloud.google.com/python/docs/reference/aiplatform/latest/google.cloud.aiplatform.TabularDataset#google_cloud_aiplatform_TabularDataset_create_from_dataframe)\ncommand returns a Vertex AI\n[`TabularDataset`](https://cloud.google.com/python/docs/reference/aiplatform/latest/google.cloud.aiplatform.TabularDataset#google_cloud_aiplatform_TabularDataset). \n\n # Create a Vertex AI tabular dataset\n dataset = aiplatform.TabularDataset.create_from_dataframe(\n df_source=df_train,\n staging_path=f\"bq://{bq_dataset_id}.table-unique\",\n display_name=\"sample-penguins\",\n )\n\nYou now have the Vertex AI tabular dataset used to train your model.\n\n(Optional) View the public dataset in BigQuery\n----------------------------------------------\n\nIf you want to view the public data used in this tutorial, you can open it in\nBigQuery.\n\n1. In **Search** in the Google Cloud, enter BigQuery, then press\n return.\n\n2. In the search results, click on BigQuery\n\n3. In the **Explorer** window, expand **bigquery-public-data**.\n\n4. Under **bigquery-public-data** , expand **ml_datasets** , then click **penguins**.\n\n5. Click any of the names under **Field name** to view that field's data."]]