Azure Machine Learning でのテーブルの操作

適用対象:Azure CLI ml extension v2 (現行)Python SDK azure-ai-ml v2 (現行)

Azure Machine Learning では、テーブル型 (mltable) がサポートされています。 これにより、データ ファイルを Pandas または Spark のデータ フレームとしてメモリに読み込む方法を定義する "ブループリント" を作成できます。 この記事では、次のことについて説明します。

  • ファイルまたはフォルダーの代わりに Azure Machine Learning テーブルを使用する場合
  • mltable SDK をインストールする方法
  • mltable ファイルを使用してデータ読み込みブループリントを定義する方法
  • Azure Machine Learning での mltable の使用方法を示す例
  • 対話型開発時 (ノートブックなど) に mltable を使用する方法

前提条件

重要

Python 環境に最新の mltable パッケージがインストールされていることを確認してください。

pip install -U mltable azureml-dataprep[pandas]

examples リポジトリをクローンします

この記事のコード スニペットは、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 のデータ フレームとしてメモリに "読み込む" 方法を定義できます。 テーブルには次の 2 つの主要機能があります。

  1. MLTable ファイル。 データ読み込み "ブループリント" を定義する YAML ベースのファイルです。 MLTable ファイルでは、次を指定できます。
    • データの保存場所 - ローカル、クラウド、またはパブリックの http(s) サーバー。
    • クラウド ストレージ上の glob パターン。 これらの場所には、ワイルドカード文字 (*) を使用してファイル名のセットを指定できます。
    • "読み取り変換" - たとえば、ファイル形式の種類 (区切りテキスト、Parquet、Delta、json)、区切り記号、ヘッダーなど。
    • 列の型変換 (スキーマの適用)。
    • フォルダー構造情報を使用した新しい列の作成 - たとえば、パスに {year}/{month} フォルダー構造を使用した年と月の列の作成。
    • 読み込む "データのサブセット" - 行のフィルター処理、列の保持/削除、ランダムなサンプルの取得など。
  2. 高速で効率的なエンジン。MLTable ファイルに定義されているブループリントに従って、データを Pandas または Spark のデータフレームに読み込みます。 エンジンでは、高速処理とメモリ効率のために Rust を利用しています。

Azure Machine Learning テーブルは、次のシナリオで役立ちます。

  • ストレージの場所を glob で指定する必要がある。
  • さまざまなストレージの場所 (複数の異なる BLOB コンテナーなど) にあるデータを使用してテーブルを作成する必要がある。
  • データでキャプチャする関連情報 (日時など) がパスに含まれている。
  • データ スキーマが頻繁に変更される。
  • データの読み込み手順を簡単に "再現できる" ようにしたい。
  • 大規模なデータのサブセットのみが必要である。
  • Python セッションにストリーミングするストレージの場所がデータに含まれている。 たとえば、path[{"path": "abfss://fs@account.dfs.core.windows.net/my-images/cats/001.jpg", "label":"cat"}] の JSON 行構造でストリーミングする場合などです。
  • 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 からニューヨーク市のグリーン タクシー データのテーブル (mltable) を作成します。 このデータは Parquet 形式で、2008 年から 2021 年の情報が含まれています。 一般公開されている BLOB ストレージ アカウント上で、データ ファイルのフォルダー構造は次のようになっています。

/
└── 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 年から 2019 年の Parquet ファイルのみ
  • データのランダムなサンプル
  • RIP の距離が 0 より大きい行のみ
  • Machine Learning 用の関連する列
  • 新しい列 - 年と月 - パス情報 (puYear=X/puMonth=Y) を使用

この処理は Pandas コードで行います。 ただし、次のいずれかを行う必要があるため、"再現性" を確保するのが難しくなります。

  • コードを共有する。スキーマが変更された場合 (列名が変更されるなど)、すべてのユーザーが自分のコードを更新する必要があります
  • ETL パイプラインを書き込む。この処理では多大なオーバーヘッドが生じます

Azure Machine Learning テーブルには、データの読み込み手順を MLTable ファイルにシリアル化 (保存) するための軽量メカニズムが用意されています。 後で、ユーザーとそのチームのメンバーが Pandas データ フレームを "再現" できます。 スキーマが変更された場合、MLTable ファイルを更新するだけで済み、Python のデータ読み込みコードが含まれるさまざまな場所での更新は不要です。

クイックスタート ノートブックをクローンするか、新しいノートブック/スクリプトを作成する

Azure Machine Learning コンピューティング インスタンスを使用する場合は、新しいノートブックを作成します。 IDE を使用する場合は、新しい Python スクリプトを作成する必要があります。

Azure Machine Learning の例が格納されている GitHub リポジトリで、クイックスタート ノートブックを入手することもできます。 次のコードを使用して、ノートブックをクローンしてアクセスします。

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

mltable Python SDK をインストールする

ニューヨーク市のグリーン タクシー データを Azure Machine Learning テーブルに読み込むには、次のコマンドを実行して、mltable Python SDK と pandas を Python 環境にインストールする必要があります。

pip install -U mltable azureml-dataprep[pandas]

MLTable ファイルを作成する

mltable Python SDK を使用して MLTable ファイルを作成し、データ読み込みブループリントを文書化します。 そのために、次のコードをコピーしてノートブック/スクリプトに貼り付け、実行します。

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")

重要

  • collocated == True の場合、データが現在併置されていない場合は MLTable yaml ファイルと同じフォルダーにデータがコピーされ、MLTable yaml では相対パスが使用されます。
  • collocated == False の場合、データは移動されず、クラウド データには絶対パスが使用され、ローカル データには相対パスが使用されます。
  • 次のパラメーターの組み合わせはサポートされていません: データがローカル リソースに格納され、collocated == 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

Note

このパスは、MLTable ファイルを含むフォルダーを指します。

対話型セッションでデータ資産を読み取る

MLTable がクラウドに保存されたので、ユーザーとチーム メンバーは、対話型セッション (ノートブックなど) でフレンドリ名を使用してその MLTable にアクセスできます。

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 ファイルを直接作成する場合は、Azure Machine Learning テーブルのクイック スタートに示されているように、テキスト エディターではなく mltable Python SDK を使用して MLTable ファイルを作成することをお勧めします。 このセクションでは、mltable Python SDK の機能について説明します。

サポートされるファイルの種類

MLTable はさまざまな種類のファイルを使用して作成できます。

ファイルの種類 MLTable Python SDK
区切りテキスト
(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 では、次のパスの種類がサポートされています。

Location
ローカル コンピューター上のパス ./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>

Note

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()

重要

制限事項: mltable は、Delta Lake からデータを読み取る際のパーティション キーの抽出はサポートしていません。 mltable 変換の extract_columns_from_partition_format は、mltable を介して Delta Lake データを読み取る際には機能しません。

重要

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 がクラウドに保存されたので、ユーザーとチーム メンバーは、対話型セッション (ノートブックなど) でフレンドリ名を使用してその MLTable にアクセスできます。

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 がクラウドに保存されたので、ユーザーとチーム メンバーは、対話型セッション (ノートブックなど) でフレンドリ名を使用してそれにアクセスできます。

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()

ジョブにデータを読み込むこともできます。

次のステップ