Azure Machine Learning에서 테이블로 작업하기

적용 대상:Azure CLI ml 확장 v2(현재)Python SDK azure-ai-ml v2(현재)

Azure Machine Learning은 테이블 형식(mltable)을 지원합니다. 이를 통해 데이터 파일을 Pandas 또는 Spark 데이터 프레임으로 메모리에 로드하는 방법을 정의하는 청사진 을 만들 수 있습니다. 이 문서에서는 다음에 대해 알아봅니다.

  • 파일이나 폴더 대신 Azure Machine Learning 테이블을 사용해야 하는 경우
  • mltable SDK를 설치하는 방법
  • mltable 파일을 사용하여 데이터 로드 청사진을 정의하는 방법
  • Azure Machine Learning에서 mltable이 사용되는 방법을 보여 주는 예
  • 대화형 개발 중에(예: Notebook에서) mltable을 사용하는 방법

필수 구성 요소

Important

Python 환경에 최신 mltable 패키지가 설치되어 있는지 확인합니다.

pip install -U mltable azureml-dataprep[pandas]

예제 리포지토리 복제

이 문서의 코드 조각은 Azure Machine Learning 예제 GitHub 리포지토리의 예제를 기반으로 합니다. 리포지토리를 개발 환경에 복제하려면 다음 명령을 사용합니다.

git clone --depth 1 https://github.com/Azure/azureml-examples

--depth 1을 사용하여 최신 커밋만 리포지토리에 복제합니다. 이렇게 하면 작업을 완료하는 시간이 줄어듭니다.

복제된 리포지토리의 이 폴더에서 Azure Machine Learning 테이블과 관련된 예를 찾을 수 있습니다.

cd azureml-examples/sdk/python/using-mltable

소개

Azure Machine Learning 테이블(mltable)을 사용하면 데이터 파일을 Pandas 및/또는 Spark 데이터 프레임으로 메모리에 로드 하는 방법을 정의할 수 있습니다. 테이블에는 다음 두 가지 주요 기능이 있습니다.

  1. MLTable 파일. 데이터 로드 청사진을 정의하는 YAML 기반 파일입니다. MLTable 파일에서 다음을 지정할 수 있습니다.
    • 데이터의 스토리지 위치(로컬, 클라우드 또는 공용 http(s) 서버)입니다.
    • 클라우드 스토리지의 GLOB 패턴입니다. 이러한 위치는 와일드카드 문자(*)를 사용하여 파일 이름 집합을 지정할 수 있습니다.
    • 읽기 변환 - 예를 들어 파일 형식(구분된 텍스트, Parquet, Delta, json), 구분 기호, 헤더 등입니다.
    • 열 형식 변환(스키마 적용을 위해)
    • 폴더 구조 정보를 사용하여 새 열 만들기 - 예를 들어 경로의 {year}/{month} 폴더 구조를 사용하여 연도 및 월 열을 만듭니다.
    • 로드할 데이터의 하위 집합 - 예를 들어 행 필터링, 열 유지/삭제, 임의 샘플 사용입니다.
  2. MLTable 파일에 정의된 청사진에 따라 데이터를 Pandas 또는 Spark 데이터 프레임에 로드하는 빠르고 효율적인 엔진입니다. 엔진은 고속 및 메모리 효율을 위해 Rust를 사용합니다.

Azure Machine Learning 테이블은 다음 시나리오에 유용합니다.

  • 스토리지 위치를 glob해야 합니다.
  • 다른 스토리지 위치(예: 다른 BLOB 컨테이너)의 데이터를 사용하여 테이블을 만들어야 합니다.
  • 경로에는 데이터에서 캡처하려는 관련 정보(예: 날짜 및 시간)가 포함됩니다.
  • 데이터 스키마는 자주 변경됩니다.
  • 데이터 로드 단계를 쉽게 재현할 수 있습니다.
  • 대규모 데이터의 하위 집합만 필요합니다.
  • 데이터에는 Python 세션으로 스트리밍하려는 스토리지 위치가 포함됩니다. 예를 들어 JSON 줄 구조 [{"path": "abfss://fs@account.dfs.core.windows.net/my-images/cats/001.jpg", "label":"cat"}]에서 path을(를) 스트리밍하려고 합니다.
  • Azure Machine Learning AutoML을 사용하여 ML 모델을 학습하려고 합니다.

표 형식 데이터의 경우 Azure Machine Learning에서는 Azure Machine Learning 테이블(mltable)을 사용할 필요가 없습니다. Azure Machine Learning 파일(uri_file) 및 폴더(uri_folder) 형식을 사용할 수 있으며 고유한 구문 분석 논리가 데이터를 Pandas 또는 Spark 데이터 프레임에 로드합니다.

간단한 CSV 파일 또는 Parquet 폴더의 경우 테이블 대신 Azure Machine Learning 파일/폴더를 사용하는 것이 더 쉽습니다.

Azure Machine Learning 테이블 빠른 시작

이 빠른 시작에서는 Azure Open Datasets에서 NYC Green Taxi Data의 테이블(mltable)을 만듭니다. 데이터는 parquet 형식이며 2008-2021년을 포함합니다. 공개적으로 액세스할 수 있는 Blob Storage 계정에서 데이터 파일의 폴더 구조는 다음과 같습니다.

/
└── green
    ├── puYear=2008
    │   ├── puMonth=1
    │   │   ├── _committed_2983805876188002631
    │   │   └── part-XXX.snappy.parquet
    │   ├── ...
    │   └── puMonth=12
    │       ├── _committed_2983805876188002631
    │       └── part-XXX.snappy.parquet
    ├── ...
    └── puYear=2021
        ├── puMonth=1
        │   ├── _committed_2983805876188002631
        │   └── part-XXX.snappy.parquet
        ├── ...
        └── puMonth=12
            ├── _committed_2983805876188002631
            └── part-XXX.snappy.parquet

이 데이터를 사용하여 Pandas 데이터 프레임에 로드해야 합니다.

  • 2015-19년 동안의 parquet 파일만 해당
  • 데이터의 임의 샘플
  • rip 거리가 0보다 큰 행만 해당
  • Machine Learning에 대한 관련 열
  • 경로 정보(puYear=X/puMonth=Y)를 사용한 새 열(연도 및 월)

Pandas 코드는 이를 처리합니다. 그러나 다음 중 하나를 수행해야 하므로 재현성을 달성하기가 어려워집니다.

  • 공유 코드 즉, 스키마가 변경되면(예: 열 이름 변경) 모든 사용자가 해당 코드를 업데이트해야 합니다. 또는
  • 오버헤드가 많은 ETL 파이프라인 작성

Azure Machine Learning 테이블은 MLTable 파일의 데이터 로드 단계를 직렬화(저장)하는 경량 메커니즘을 제공합니다. 그런 다음 사용자와 사용자의 팀 멤버는 Pandas 데이터 프레임을 생성할 수 있습니다. 스키마가 변경되면 Python 데이터 로드 코드가 포함된 여러 위치에서 업데이트하는 대신 MLTable 파일만 업데이트합니다.

빠른 시작 Notebook 복제 또는 새 Notebook/스크립트 만들기

Azure Machine Learning 컴퓨팅 인스턴스를 사용하는 경우 새 Notebook을 만듭니다. IDE를 사용하는 경우 새 Python 스크립트를 만들어야 합니다.

또한 빠른 시작 Notebook은 Azure Machine Learning 예제 GitHub 리포지토리에서 사용할 수 있습니다. 이 코드를 사용하여 Notebook을 복제하고 액세스합니다.

git clone --depth 1 https://github.com/Azure/azureml-examples
cd azureml-examples/sdk/python/using-mltable/quickstart

mltable Python SDK 설치

NYC Green Taxi 데이터를 Azure Machine Learning 테이블에 로드하려면 다음 명령을 사용하여 mltable Python SDK가 있고 pandas이(가) Python 환경에 설치되어 있어야 합니다.

pip install -U mltable azureml-dataprep[pandas]

MLTable 파일 작성

mltable Python SDK를 사용하여 MLTable 파일을 만들고 데이터 로드 청사진을 문서화합니다. 이를 위해 다음 코드를 Notebook/스크립트에 복사하여 붙여넣은 다음 해당 코드를 실행합니다.

import mltable

# glob the parquet file paths for years 2015-19, all months.
paths = [
    {
        "pattern": "wasbs://nyctlc@azureopendatastorage.blob.core.windows.net/green/puYear=2015/puMonth=*/*.parquet"
    },
    {
        "pattern": "wasbs://nyctlc@azureopendatastorage.blob.core.windows.net/green/puYear=2016/puMonth=*/*.parquet"
    },
    {
        "pattern": "wasbs://nyctlc@azureopendatastorage.blob.core.windows.net/green/puYear=2017/puMonth=*/*.parquet"
    },
    {
        "pattern": "wasbs://nyctlc@azureopendatastorage.blob.core.windows.net/green/puYear=2018/puMonth=*/*.parquet"
    },
    {
        "pattern": "wasbs://nyctlc@azureopendatastorage.blob.core.windows.net/green/puYear=2019/puMonth=*/*.parquet"
    },
]

# create a table from the parquet paths
tbl = mltable.from_parquet_files(paths)

# table a random sample
tbl = tbl.take_random_sample(probability=0.001, seed=735)

# filter trips with a distance > 0
tbl = tbl.filter("col('tripDistance') > 0")

# Drop columns
tbl = tbl.drop_columns(["puLocationId", "doLocationId", "storeAndFwdFlag"])

# Create two new columns - year and month - where the values are taken from the path
tbl = tbl.extract_columns_from_partition_format("/puYear={year}/puMonth={month}")

# print the first 5 records of the table as a check
tbl.show(5)

필요에 따라 다음을 사용하여 MLTable 개체를 Pandas에 로드하도록 선택할 수 있습니다.

# You can load the table into a pandas dataframe
# NOTE: The data is in East US region and the data is large, so this will take several minutes (~7mins)
# to load if you are in a different region.

# df = tbl.to_pandas_dataframe()

데이터 로드 단계 저장

다음으로, 모든 데이터 로드 단계를 MLTable 파일에 저장합니다. 데이터 로드 단계를 MLTable 파일에 저장하면 매번 코드를 다시 정의하지 않고도 나중에 Pandas 데이터 프레임을 재현할 수 있습니다.

MLTable yaml 파일을 클라우드 스토리지 리소스에 저장하거나 로컬 경로 리소스에 저장할 수 있습니다.

# save the data loading steps in an MLTable file to a cloud storage resource
# NOTE: the tbl object was defined in the previous snippet.
tbl.save(path="azureml://subscriptions/<subid>/resourcegroups/<rgname>/workspaces/<wsname>/datastores/<name>/paths/titanic", colocated=True, show_progress=True, overwrite=True)
# save the data loading steps in an MLTable file to a local resource
# NOTE: the tbl object was defined in the previous snippet.
tbl.save("./titanic")

Important

  • colocated == True인 경우 데이터가 현재 함께 배치되지 않은 경우 MLTable yaml 파일이 있는 동일한 폴더에 데이터를 복사하고 MLTable yaml의 상대 경로를 사용합니다.
  • colocated == False인 경우 데이터를 이동하지 않으며 클라우드 데이터에는 절대 경로를 사용하고 로컬 데이터에는 상대 경로를 사용합니다.
  • 이 매개 변수 조합을 지원하지 않습니다. 데이터는 로컬 리소스에 저장되고, 공동 배치 == False이며, path는 클라우드 디렉터리를 대상으로 합니다. 로컬 데이터를 클라우드에 업로드하고 대신 MLTable용 클라우드 데이터 경로를 사용하세요.

데이터 로드 단계 재현

이제 데이터 로드 단계를 파일로 직렬화했으므로 load() 메서드를 사용하여 언제든지 해당 단계를 재현할 수 있습니다. 이렇게 하면 코드에서 데이터 로드 단계를 다시 정의할 필요가 없으며 파일을 보다 쉽게 공유할 수 있습니다.

import mltable

# load the previously saved MLTable file
tbl = mltable.load("./nyc_taxi/")
tbl.show(5)

# You can load the table into a pandas dataframe
# NOTE: The data is in East US region and the data is large, so this will take several minutes (~7mins)
# to load if you are in a different region.

# load the table into pandas
# df = tbl.to_pandas_dataframe()

# print the head of the data frame
# df.head()
# print the shape and column types of the data frame
# print(f"Shape: {df.shape}")
# print(f"Columns:\n{df.dtypes}")

공유 및 재현성을 지원하는 데이터 자산 만들기

현재 디스크에 MLTable 파일이 저장되어 있어 팀 멤버와 공유하기가 어려울 수 있습니다. Azure Machine Learning에서 데이터 자산을 만들면 MLTable이 클라우드 스토리지에 업로드되고 "책갈피가 지정"됩니다. 그러면 팀 멤버가 식별 이름으로 MLTable에 액세스할 수 있습니다. 또한 데이터 자산의 버전이 지정됩니다.

az ml data create --name green-quickstart --version 1 --path ./nyc_taxi --type mltable

참고 항목

경로는 MLTable 파일이 포함된 폴더를 가리킵니다.

대화형 세션에서 데이터 자산 읽기

이제 MLTable이 클라우드에 저장되었으므로 사용자와 팀 멤버는 대화형 세션(예: Notebook)에서 식별 이름으로 액세스할 수 있습니다.

import mltable
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential

# connect to the AzureML workspace
# NOTE: the subscription_id, resource_group, workspace variables are set
# in a previous code snippet.
ml_client = MLClient(
    DefaultAzureCredential(), subscription_id, resource_group, workspace
)

# get the latest version of the data asset
# Note: The version was set in the previous snippet. If you changed the version
# number, update the VERSION variable below.
VERSION="1"
data_asset = ml_client.data.get(name="green-quickstart", version=VERSION)

# create a table
tbl = mltable.load(f"azureml:/{data_asset.id}")
tbl.show(5)

# load into pandas
# NOTE: The data is in East US region and the data is large, so this will take several minutes (~7mins) to load if you are in a different region.
df = tbl.to_pandas_dataframe()

작업의 데이터 자산 읽기

사용자 또는 팀 멤버가 작업에서 테이블에 액세스하려는 경우 Python 학습 스크립트에는 다음이 포함됩니다.

# ./src/train.py
import argparse
import mltable

# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('--input', help='mltable to read')
args = parser.parse_args()

# load mltable
tbl = mltable.load(args.input)

# load into pandas
df = tbl.to_pandas_dataframe()

작업에는 Python 패키지 종속성이 포함된 conda 파일이 필요합니다.

# ./conda_dependencies.yml
dependencies:
  - python=3.10
  - pip=21.2.4
  - pip:
      - mltable
      - azureml-dataprep[pandas]

다음을 사용하여 작업을 제출합니다.

다음 작업 YAML 파일을 만듭니다.

# mltable-job.yml
$schema: https://azuremlschemas.azureedge.net/latest/commandJob.schema.json

code: ./src

command: python train.py --input ${{inputs.green}}
inputs:
    green:
      type: mltable
      path: azureml:green-quickstart:1

compute: cpu-cluster

environment:
  image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04
  conda_file: conda_dependencies.yml

CLI에서 작업을 만듭니다.

az ml job create -f mltable-job.yml

MLTable 파일 작성

MLTable 파일을 직접 만들려면 텍스트 편집기 대신 mltable Python SDK를 사용하여 Azure Machine Learning 테이블 빠른 시작 에 표시된 대로 MLTable 파일을 작성하는 것이 좋습니다. 이 섹션에서는 mltable Python SDK의 기능을 간략하게 설명합니다.

지원되는 파일 형식

다양한 파일 형식으로 MLTable을 만들 수 있습니다.

파일 유형 MLTable Python SDK
DelimitedText
(예: CSV 파일)
from_delimited_files(paths=[path])
Parquet from_parquet_files(paths=[path])
Delta Lake from_delta_lake(delta_table_uri=<uri_pointing_to_delta_table_directory>,timestamp_as_of='2022-08-26T00:00:00Z')
JSON Lines from_json_lines_files(paths=[path])
경로
(스트림할 경로 열이 있는 테이블 만들기)
from_paths(paths=[path])

자세한 내용은 MLTable 참조 리소스를 참조하세요.

경로 정의

구분된 텍스트, parquet, JSON 줄 및 경로의 경우 읽을 경로를 정의하는 Python 사전 목록을 정의합니다.

import mltable

# A List of paths to read into the table. The paths are a python dict that define if the path is
# a file, folder, or (glob) pattern.
paths = [
    {
        "file": "<supported_path>"
    }
]

tbl = mltable.from_delimited_files(paths=paths)

# alternatively
# tbl = mltable.from_parquet_files(paths=paths)
# tbl = mltable.from_json_lines_files(paths=paths)
# tbl = mltable.from_paths(paths=paths)

MLTable은 다음 경로 형식을 지원합니다.

위치 예제
로컬 컴퓨터의 경로 ./home/username/data/my_data
퍼블릭 http(s) 서버의 경로 https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv
Azure Storage의 경로 wasbs://<container_name>@<account_name>.blob.core.windows.net/<path>
abfss://<file_system>@<account_name>.dfs.core.windows.net/<path>
긴 형식의 Azure Machine Learning 데이터 저장소 azureml://subscriptions/<subid>/resourcegroups/<rgname>/workspaces/<wsname>/datastores/<name>/paths/<path>

참고 항목

mltable은(는) Azure Storage 및 Azure Machine Learning 데이터 저장소의 경로에 대한 사용자 자격 증명 통과를 수행합니다. 기본 스토리지의 데이터에 대한 권한이 없는 경우 데이터에 액세스할 수 없습니다.

Delta Lake 테이블의 경로 정의에 대한 참고 사항

다른 파일 형식과 비교하여 Delta Lake 테이블을 읽는 경로를 정의하는 방법은 다릅니다. Delta Lake 테이블의 경우 경로는 "_delta_log" 폴더와 데이터 파일이 포함된 단일 폴더(일반적으로 ADLS gen2)를 가리킵니다. 시간 이동이 지원됩니다. 다음 코드는 Delta Lake 테이블의 경로를 정의하는 방법을 보여주는 코드입니다.

import mltable

# define the cloud path containing the delta table (where the _delta_log file is stored)
delta_table = "abfss://<file_system>@<account_name>.dfs.core.windows.net/<path_to_delta_table>"

# create an MLTable. Note the timestamp_as_of parameter for time travel.
tbl = mltable.from_delta_lake(
    delta_table_uri=delta_table,
    timestamp_as_of='2022-08-26T00:00:00Z'
)

최신 버전의 Delta Lake 데이터를 가져오려면 현재 타임스탬프를 timestamp_as_of에 전달할 수 있습니다.

import mltable

# define the relative path containing the delta table (where the _delta_log file is stored)
delta_table_path = "./working-directory/delta-sample-data"

# get the current timestamp in the required format
current_timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
print(current_timestamp)
tbl = mltable.from_delta_lake(delta_table_path, timestamp_as_of=current_timestamp)
df = tbl.to_pandas_dataframe()

Important

제한 사항: mltable은 Delta Lake에서 데이터를 읽을 때 파티션 키 추출을 지원하지 않습니다. mltable을 통해 Delta Lake 데이터를 읽는 경우 mltable 변환 extract_columns_from_partition_format이 작동하지 않습니다.

Important

mltable은(는) Azure Storage 및 Azure Machine Learning 데이터 저장소의 경로에 대한 사용자 자격 증명 통과를 수행합니다. 기본 스토리지의 데이터에 대한 권한이 없는 경우 데이터에 액세스할 수 없습니다.

파일, 폴더 및 GLOB

Azure Machine Learning 테이블은 다음에서 읽기를 지원합니다.

  • 파일(예: abfss://<file_system>@<account_name>.dfs.core.windows.net/my-csv.csv)
  • 폴더(예: abfss://<file_system>@<account_name>.dfs.core.windows.net/my-folder/)
  • GLOB 패턴(예: abfss://<file_system>@<account_name>.dfs.core.windows.net/my-folder/*.csv)
  • 파일, 폴더 및 GLOB 패턴의 조합

지원되는 데이터 로드 변환

MLTable 참조 설명서에서 지원되는 데이터 로드 변환에 대한 전체 최신 세부 정보를 찾습니다.

예제

Azure Machine Learning 예 GitHub 리포지토리의 예가 이 문서의 코드 조각의 기초가 되었습니다. 이 명령을 사용하여 리포지토리를 개발 환경에 복제합니다.

git clone --depth 1 https://github.com/Azure/azureml-examples

--depth 1을 사용하여 최신 커밋만 리포지토리에 복제합니다. 이렇게 하면 작업을 완료하는 시간이 줄어듭니다.

이 복제 리포지토리 폴더는 Azure Machine Learning 테이블과 관련된 예제를 호스트합니다.

cd azureml-examples/sdk/python/using-mltable

구분 기호로 분리된 파일

먼저 다음 코드를 사용하여 CSV 파일에서 MLTable을 만듭니다.

import mltable
from mltable import MLTableHeaders, MLTableFileEncoding, DataType

# create paths to the data files
paths = [{"file": "wasbs://data@azuremlexampledata.blob.core.windows.net/titanic.csv"}]

# create an MLTable from the data files
tbl = mltable.from_delimited_files(
    paths=paths,
    delimiter=",",
    header=MLTableHeaders.all_files_same_headers,
    infer_column_types=True,
    include_path_column=False,
    encoding=MLTableFileEncoding.utf8,
)

# filter out rows undefined ages
tbl = tbl.filter("col('Age') > 0")

# drop PassengerId
tbl = tbl.drop_columns(["PassengerId"])

# ensure survived column is treated as boolean
data_types = {
    "Survived": DataType.to_bool(
        true_values=["True", "true", "1"], false_values=["False", "false", "0"]
    )
}
tbl = tbl.convert_column_types(data_types)

# show the first 5 records
tbl.show(5)

# You can also load into pandas...
# df = tbl.to_pandas_dataframe()
# df.head(5)

데이터 로드 단계 저장

다음으로, 모든 데이터 로드 단계를 MLTable 파일에 저장합니다. MLTable 파일에 데이터 로드 단계를 저장하면 매번 코드를 다시 정의할 필요 없이 나중에 Pandas 데이터 프레임을 재현할 수 있습니다.

# save the data loading steps in an MLTable file
# NOTE: the tbl object was defined in the previous snippet.
tbl.save("./titanic")

데이터 로드 단계 재현

이제 파일에 직렬화된 데이터 로드 단계가 있으므로 load() 메서드를 사용하여 언제든지 재현할 수 있습니다. 이렇게 하면 코드에서 데이터 로드 단계를 다시 정의할 필요가 없으며 파일을 보다 쉽게 공유할 수 있습니다.

import mltable

# load the previously saved MLTable file
tbl = mltable.load("./titanic/")

공유 및 재현성을 지원하는 데이터 자산 만들기

현재 디스크에 MLTable 파일이 저장되어 있어 팀 멤버와 공유하기가 어려울 수 있습니다. Azure Machine Learning에서 데이터 자산을 만들면 MLTable이 클라우드 스토리지에 업로드되고 "책갈피가 지정"됩니다. 그러면 팀 멤버가 식별 이름으로 MLTable에 액세스할 수 있습니다. 또한 데이터 자산의 버전이 지정됩니다.

import time
from azure.ai.ml import MLClient
from azure.ai.ml.entities import Data
from azure.ai.ml.constants import AssetTypes
from azure.identity import DefaultAzureCredential

# Update with your details...
subscription_id = "<SUBSCRIPTION_ID>"
resource_group = "<RESOURCE_GROUP>"
workspace = "<AML_WORKSPACE_NAME>"

# set the version number of the data asset to the current UTC time
VERSION = time.strftime("%Y.%m.%d.%H%M%S", time.gmtime())

# connect to the AzureML workspace
ml_client = MLClient(
    DefaultAzureCredential(), subscription_id, resource_group, workspace
)

my_data = Data(
    path="./titanic",
    type=AssetTypes.MLTABLE,
    description="The titanic dataset.",
    name="titanic-cloud-example",
    version=VERSION,
)

ml_client.data.create_or_update(my_data)

이제 MLTable이 클라우드에 저장되었으므로 사용자와 팀 멤버는 대화형 세션(예: Notebook)에서 식별 이름으로 액세스할 수 있습니다.

import mltable
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential

# connect to the AzureML workspace
# NOTE:  subscription_id, resource_group, workspace were set in a previous snippet.
ml_client = MLClient(
    DefaultAzureCredential(), subscription_id, resource_group, workspace
)

# get the latest version of the data asset
# Note: The version was set in the previous code cell.
data_asset = ml_client.data.get(name="titanic-cloud-example", version=VERSION)

# create a table
tbl = mltable.load(f"azureml:/{data_asset.id}")

# load into pandas
df = tbl.to_pandas_dataframe()
df.head(5)

작업의 데이터 자산에 쉽게 액세스할 수도 있습니다.

Parquet 파일

Azure Machine Learning 테이블 빠른 시작에서는 Parquet 파일을 읽는 방법을 설명합니다.

경로: 이미지 파일 테이블 만들기

클라우드 저장소의 경로를 포함하는 테이블을 만들 수 있습니다. 이 예제에는 다음 폴더 구조의 클라우드 저장소에 있는 여러 개의 개 및 고양이 이미지가 있습니다.

/pet-images
  /cat
    0.jpeg
    1.jpeg
    ...
  /dog
    0.jpeg
    1.jpeg

mltable은 이러한 이미지의 스토리지 경로와 해당 폴더 이름(레이블)이 포함된 테이블을 생성할 수 있으며, 이는 이미지를 스트리밍하는 데 사용할 수 있습니다. 이 코드는 MLTable을 만듭니다.

import mltable

# create paths to the data files
paths = [{"pattern": "wasbs://data@azuremlexampledata.blob.core.windows.net/pet-images/**/*.jpg"}]

# create the mltable
tbl = mltable.from_paths(paths)

# extract useful information from the path
tbl = tbl.extract_columns_from_partition_format("{account}/{container}/{folder}/{label}")

tbl = tbl.drop_columns(["account", "container", "folder"])

df = tbl.to_pandas_dataframe()
print(df.head())

# save the data loading steps in an MLTable file
tbl.save("./pets")

이 코드는 Pandas 데이터 프레임에서 스토리지 위치를 열고 이미지를 그리는 방법을 보여 줍니다.

# plot images on a grid. Note this takes ~1min to execute.
import matplotlib.pyplot as plt
from PIL import Image

fig = plt.figure(figsize=(20, 20))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    with df.Path[i].open() as f:
        img = Image.open(f)
        fig.add_subplot(rows, columns, i)
        plt.imshow(img)
        plt.title(df.label[i])

공유 및 재현성을 지원하는 데이터 자산 만들기

현재 mltable 파일이 디스크에 저장되어 있을 수 있으므로 팀 멤버와 공유하기가 어렵습니다. Azure Machine Learning에서 데이터 자산을 만들면 mltable이 클라우드 스토리지에 업로드되고 "책갈피가 지정"됩니다. 그러면 팀 멤버가 식별 이름으로 mltable에 액세스할 수 있습니다. 또한 데이터 자산의 버전이 지정됩니다.

import time
from azure.ai.ml import MLClient
from azure.ai.ml.entities import Data
from azure.ai.ml.constants import AssetTypes
from azure.identity import DefaultAzureCredential

# set the version number of the data asset to the current UTC time
VERSION = time.strftime("%Y.%m.%d.%H%M%S", time.gmtime())

# connect to the AzureML workspace
# NOTE: subscription_id, resource_group, workspace were set in a previous snippet.
ml_client = MLClient(
    DefaultAzureCredential(), subscription_id, resource_group, workspace
)

my_data = Data(
    path="./pets",
    type=AssetTypes.MLTABLE,
    description="A sample of cat and dog images",
    name="pets-mltable-example",
    version=VERSION,
)

ml_client.data.create_or_update(my_data)

이제 mltable이 클라우드에 저장되었으므로 사용자와 팀 멤버는 대화형 세션(예: Notebook)에서 식별 이름으로 액세스할 수 있습니다.

import mltable
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential

# connect to the AzureML workspace
# NOTE: subscription_id, resource_group, workspace were set in a previous snippet.
ml_client = MLClient(
    DefaultAzureCredential(), subscription_id, resource_group, workspace
)

# get the latest version of the data asset
# Note: the variable VERSION is set in the previous code
data_asset = ml_client.data.get(name="pets-mltable-example", version=VERSION)

# the table from the data asset id
tbl = mltable.load(f"azureml:/{data_asset.id}")

# load into pandas
df = tbl.to_pandas_dataframe()
df.head()

데이터를 작업에 로드할 수도 있습니다.

다음 단계