You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Django模型的FileField加载XGBoost模型失败求助

解决Django FileField加载XGBoost模型的TypeError问题

看起来你碰到的问题是XGBoost的load_model()方法无法直接处理Django FileField返回的FieldFile对象,才会抛出TypeError: memoryview: a bytes-like object is required这类错误——毕竟你直接传本地文件路径的时候是正常的对吧?

问题根源

xgb.Booster.load_model()接受的参数类型是这几种:

  • 本地文件路径的字符串
  • 以二进制模式打开的文件对象
  • 字节流(bytes)

但Django的FieldFile是框架封装的文件对象,直接传进去会触发类型不匹配的错误。

几种可行的解决方案

方案1:直接使用文件的本地路径

这是最贴近你原有可行代码的方式,用FieldFile的path属性获取文件在服务器上的实际路径字符串:

def do(execution):
    dataFile = execution.dataFile
    np = genfromtxt(dataFile, delimiter=',')
    import xgboost as xgb
    bst = xgb.Booster({'nthread': 4}) # init model
    # 改用path属性获取本地路径
    bst.load_model(execution.modelFile.path)
    data = xgb.DMatrix(np)
    preds = bst.predict(data)
    print(preds)

方案2:以二进制模式打开文件对象

利用Django FieldFile的open()方法打开文件,以二进制模式传入load_model:

def do(execution):
    dataFile = execution.dataFile
    np = genfromtxt(dataFile, delimiter=',')
    import xgboost as xgb
    bst = xgb.Booster({'nthread': 4}) # init model
    # 二进制模式打开文件
    with execution.modelFile.open('rb') as model_file:
        bst.load_model(model_file)
    data = xgb.DMatrix(np)
    preds = bst.predict(data)
    print(preds)

方案3:读取文件字节流传入

如果不想操作文件对象,也可以直接读取文件的字节内容传给load_model:

def do(execution):
    dataFile = execution.dataFile
    np = genfromtxt(dataFile, delimiter=',')
    import xgboost as xgb
    bst = xgb.Booster({'nthread': 4}) # init model
    # 读取文件字节数据
    model_bytes = execution.modelFile.read()
    bst.load_model(model_bytes)
    data = xgb.DMatrix(np)
    preds = bst.predict(data)
    print(preds)

额外注意事项

  • 确保execution.modelFile已经成功上传,不是空的字段,否则会出现文件不存在的错误
  • 检查服务器上的文件权限,确保Django运行的进程有读取该文件的权限
  • 如果生产环境用了云存储后端(比如S3),方案2和3通常依然有效,因为Django的FileField接口是统一的

内容的提问来源于stack exchange,提问作者Andrea deCandia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:36:04