从记录到稀疏矩阵的Sagemaker

2024-06-10 07:40:16 发布

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

在为Sagemaker的分解机实现准备数据进行培训时,我成功地使用函数write_spmatrix_to_sparse_tensorsource code)将数据从稀疏矩阵转换为Sagemaker的分解机实现所期望的recordio格式。你知道吗

我将import语句限制为提供的函数的示例:

import os
import io
import boto3
import sagemaker.amazon.common as smac

def write_recordio(array, y, prefix, f):
    # Convert to record protobuf
    buf = io.BytesIO()
    smac.write_spmatrix_to_sparse_tensor(array=array, file=buf, labels=y)
    buf.seek(0)

    fname = os.path.join(prefix, f)
    boto3.Session().resource('s3').Bucket('bucket_name').Object(fname).upload_fileobj(buf)

参数array的一个示例片段,其功能如下:

   (0, 990290)  1.0
   (0, 1266265) 1.0
   (1, 560338)  1.0
   (1, 1266181) 1.0
   (2, 182872)  1.0
   (2, 1266205) 1.0
   ...

作为我的目标的y的示例格式:

[1. 1. 1. ... 3. 1. 5.]

write_spmatrix_to_sparse_tensor与上述函数和输入一起工作。在训练了我的模型之后,我使用Sagemaker的Batch Transform来接收一个.out文件,其中有许多<class 'record_pb2.Record'>类型的输出

示例:

来自write_spmatrix_to_sparse_tensor输出的一条记录:

features {
  key: "values"
  value {
    float32_tensor {
      values: 1.0
      values: 1.0
      keys: 990290
      keys: 1266265
      shape: 1266394
    }
  }
}
label {
  key: "values"
  value {
    float32_tensor {
      values: 1.0
    }
  }
}

批处理转换输出(.out)文件中的一条记录(其中存在许多记录):

label {
  key: "score"
  value {
    float32_tensor {
      values: 1.5246734619140625
    }
  }
}

所以现在我有了一个最初使用write_spmatrix_to_sparse_tensor编写的文件和一个来自transformer.transform的输出,我想从这些文件回到我原来的稀疏矩阵格式。本质上,如果函数write_sparse_tensor_to_spmatrix存在,它会是什么样子?你知道吗


Tags: 文件to函数import示例格式记录array