将TFRecord从Python输出到Google云存储

2024-04-19 01:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道tf.python_io.TFRecordWriter有GCS的概念,但它似乎没有写入它的权限。

如果我执行以下操作:

output_path = 'gs://my-bucket-name/{}/{}.tfrecord'.format(object_name, record_name)
writer = tf.python_io.TFRecordWriter(output_path)
# write to writer
writer.close()

然后我收到401说“匿名来电者没有存储.objects.create访问我的存储桶名称。“

但是,在同一台机器上,如果我gsutil rsync -d r gs://my-bucket-name bucket-backup,它会正确地同步它,所以我已经使用gcloud正确地进行了身份验证。

如何授予TFRecordWriter写入GCS的权限?我现在只打算使用Google的GCP python API,但我确信有一种方法可以单独使用TF来实现这一点。


Tags: pathnameiogsformat概念权限output
2条回答

在系统上设置凭据的常见策略是使用应用程序默认凭据(ADC)。ADC是一种定位Google云服务帐户凭证的策略。在

如果设置了环境变量GOOGLE_APPLICATION_CREDENTIALS,ADC将使用变量指向的文件名作为服务帐户凭据。此文件是Json格式的Google云服务帐户凭据文件。以前的P12(PFX)证书已弃用。在

如果未设置环境变量,则默认服务帐户将用于凭据(如果应用程序运行在计算引擎、应用程序引擎、Kubernetes引擎或云函数上)。在

如果前两个步骤找不到有效的凭据,ADC将失败,并发生错误。在

对于此问题,ADC找不到凭据,TensorFlow写入GCS失败。在

解决方案是将环境变量GOOGLE_APPLICATION_CREDENTIALS设置为指向服务帐户Json文件。在

对于Linux:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

对于Windows

^{pr2}$

我写了一篇关于ADC的文章。在

Google Cloud Application Default Credentials

当您使用gsutil命令时,您使用的是在cloudsdk中配置的GCP用户(执行:gcloud config list查看)。 您的python脚本似乎没有在GCP中进行身份验证。在

我相信有更好的方法来解决这个问题(抱歉,我对TensorFlow没有太多的了解),但是我可以看到两个解决方法来解决这个问题:

第一个选项使用Cloud Fuse将云存储存储桶作为文件系统装载

第二个选项—本地写入并稍后移动。在这种方法中,您可以使用以下代码:

# Service Account file
JSON_FILE_NAME = '<Service account json file>'


# Imports the Google Cloud client library
from google.cloud import storage

# Instantiates a client
storage_client = storage.Client.from_service_account_json(JSON_FILE_NAME)

#Example file (using the service account)
source_file_path = 'your file path'
destination_blob_name = 'name of file in gcs'
# The name for the new bucket
bucket_name = '<bucket_name>'


bucket = storage_client.get_bucket(bucket_name)

blob = bucket.blob(destination_blob_name)

blob.upload_from_filename(source_file_path)

print('File {} uploaded to {}.'.format(
    source_file_path,
    destination_blob_name))

相关问题 更多 >