将 S3 数据加载到 AWS SageMaker Notebook

Load S3 Data into AWS SageMaker Notebook

我刚开始试验 AWS SageMaker,想将数据从 S3 存储桶加载到我的 SageMaker python jupyter notebook 中的 pandas 数据帧中进行分析。

我可以使用 boto 从 S3 获取数据,但我想知道是否有更优雅的方法作为 SageMaker 框架的一部分在我的 python 代码中执行此操作?

提前感谢您的任何建议。

如果您在文档中查看 here it seems you can specify this in the InputDataConfig. Search for "S3DataSource" (ref)。第 25/26 页的 Python 中甚至出现了第一个命中。

请确保 Amazon SageMaker 角色附加了策略以访问 S3。它可以在 IAM 中完成。

import boto3
import pandas as pd
from sagemaker import get_execution_role

role = get_execution_role()
bucket='my-bucket'
data_key = 'train.csv'
data_location = 's3://{}/{}'.format(bucket, data_key)

pd.read_csv(data_location)

在最简单的情况下,您不需要 boto3,因为您只是 阅读 资源。
那么就更简单了:

import pandas as pd

bucket='my-bucket'
data_key = 'train.csv'
data_location = 's3://{}/{}'.format(bucket, data_key)

pd.read_csv(data_location)

但正如 Prateek 所说,请确保配置您的 SageMaker 笔记本实例以访问 s3。这是在权限 > IAM 角色

中的配置步骤中完成的

您还可以使用 s3fs

访问存储桶作为文件系统
import s3fs
fs = s3fs.S3FileSystem()

# To List 5 files in your accessible bucket
fs.ls('s3://bucket-name/data/')[:5]

# open it directly
with fs.open(f's3://bucket-name/data/image.png') as f:
    display(Image.open(f))

您还可以使用 AWS Data Wrangler https://github.com/awslabs/aws-data-wrangler:

import awswrangler as wr

df = wr.s3.read_csv(path="s3://...")

此代码示例用于从 S3 导入 csv 文件,已在 SageMaker notebook 上测试。

使用pip或conda安装s3fs。 !pip install s3fs

import pandas as pd

my_bucket = '' #declare bucket name
my_file = 'aa/bb.csv' #declare file path

import boto3 # AWS Python SDK
from sagemaker import get_execution_role
role = get_execution_role()

data_location = 's3://{}/{}'.format(my_bucket,my_file)
data=pd.read_csv(data_location)
data.head(2)

f-string 相似的答案。

import pandas as pd
bucket = 'your-bucket-name'
file = 'file.csv'
df = pd.read_csv(f"s3://{bucket}/{file}")
len(df) # print row counts