【问题标题】:Loading a FastText Model from s3 without Saving Locally从 s3 加载 FastText 模型而不在本地保存
【发布时间】:2021-10-05 16:49:48
【问题描述】:

我希望在 ML 管道中使用 FastText 模型,我在 s3 上创建并保存为 .bin 文件。我希望将这一切都保存在基于云的管道中,所以我不想要本地文件。我觉得我真的很亲密,但我不知道如何制作一个临时的.bin 文件。我也不确定我是否以最有效的方式保存和阅读 FastText 模型。下面的代码有效,但它在本地保存了我想避免的文件。

import smart_open
file = smart_open.smart_open(s3 location of .bin model)
listed = b''.join([i for i in file])
with open("ml_model.bin", "wb") as binary_file:
    binary_file.write(listed)
model = fasttext.load_model("ml_model.bin")

【问题讨论】:

  • 如果fasttext.load_model() 支持类似文件的对象而不是文件路径,您可以使用io.BytesIO(listed)...
  • 好主意,可惜没成功,得到了TypeError: loadModel(): incompatible function arguments.

标签: python machine-learning amazon-s3 fasttext


【解决方案1】:

如果您想为官方 Facebook FastText 代码使用 fasttext 包装器,您可能需要创建一个本地临时副本 - 您的麻烦使该代码看起来依赖于打开本地文件路径。

您还可以尝试 Gensim 包的单独 FastText 支持,它应该通过其 load_facebook_model() 函数接受 S3 路径:

https://radimrehurek.com/gensim/models/fasttext.html#gensim.models.fasttext.load_facebook_model

(但请注意,Gensim 不支持所有 FastText 功能,例如 supervised 模式。)

【讨论】:

  • 谢谢你,它确实为我指明了正确的方向!该问题与需要 Path 对象有关。我不知道 Gensim 直接实现这个包。
【解决方案2】:

正如上述回复部分回答的那样,需要一个临时文件。但最重要的是,临时文件需要作为字符串对象传递,这有点奇怪。工作代码如下:

import tempfile
import fasttext
import smart_open
from pathlib import Path

file = smart_open.smart_open(f's3://{bucket_name}/{key}')
listed = b''.join([i for i in file])
with tempfile.TemporaryDirectory() as tdir:
    tfile = Path(tdir).joinpath('tempfile.bin')
    tfile.write_bytes(listed)
    model = fasttext.load_model(str(tfile))

【讨论】:

  • 最后,这仍然是在磁盘上写入文件。在这种情况下,您可以使用shutil.copyfileobj() 来提高效率。 str(tfile)这里只是返回文件名...
猜你喜欢
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多