以字节为单位读取模型而不在python中保存位置? [英] Read model as bytes without saving in location in python?
问题描述
Python,我已经将模型另存为joblib文件,我以"rb"读取字节打开文件,是否可以直接将其转换为字节而不是保存在文件中,
Python, I have saved my model as joblib file in a location, the I open the file in 'rb' read bytes, is it possible to convert straight to bytes instead of saving in a file,
import joblib
joblib.dump(model, 'model.joblib')
#Read as bytes
model_bytes = open('C:/Models/model.joblib','rb').read()
model_bytes
#This outputs like
b'\x80\x03csklearn.ensemble.forest\nRandomForestClassifier\nq\x00)\x81q\x01}q\x...…..
这里我不想保存在某个位置,所以我尝试使用tempfile,但是我知道这是行不通的,还有其他选择吗?
Here I don't want to save in a location, so I tried with tempfile, but this will not work I knew, is there any other options
import tempfile
bytes_model = tempfile.TemporaryFile()
bytes_model.read(model)
#Also bytes function doesn't work
bytes_model = bytes(model)
我不需要创建文件,因此不必访问它,可以将模型变量读取为字节吗?
I don't need a file to be created, so that I don't have to access it, Is it possible to read the model variable as bytes?
推荐答案
如果 joblib.dump()
不抱怨,您应该可以使用 BytesIO
You should be able to use BytesIO
for this if joblib.dump()
doesn't complain.
类似的事情可能对您有用:
Something like this may work for you:
from io import BytesIO
import joblib
bytes_container = BytesIO()
joblib.dump(model, bytes_container)
bytes_container.seek(0) # update to enable reading
bytes_model = bytes_container.read()
这篇关于以字节为单位读取模型而不在python中保存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!