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

FastAPI应用部署Deta遇sklearn库过大及依赖缺失问题

解决Deta部署时scikit-learn体积过大导致的依赖问题

核心结论

scikit-learn是整体打包发布的库,无法单独安装其tree子模块,必须安装完整包。针对Deta的体积限制,你可以通过以下替代方案解决:

方案1:转换模型为ONNX格式,使用轻量运行时

将训练好的DecisionTreeClassifier转换为ONNX格式,用体积更小的onnxruntime加载运行,避免依赖完整的scikit-learn:

  1. 训练时转换模型:
    from sklearn.tree import DecisionTreeClassifier
    from skl2onnx import convert_sklearn
    from skl2onnx.common.data_types import FloatTensorType
    import numpy as np
    
    # 假设X_train是训练特征数据
    model = DecisionTreeClassifier()
    model.fit(X_train, y_train)
    
    # 定义输入张量类型,转换模型为ONNX
    initial_type = [('float_input', FloatTensorType([None, X_train.shape[1]]))]
    onnx_model = convert_sklearn(model, initial_types=initial_type)
    with open("decision_tree.onnx", "wb") as f:
        f.write(onnx_model.SerializeToString())
    
  2. FastAPI中加载ONNX模型:
    import onnxruntime as rt
    from fastapi import FastAPI
    from pydantic import BaseModel
    import numpy as np
    
    app = FastAPI()
    # 加载ONNX模型
    sess = rt.InferenceSession("decision_tree.onnx")
    input_name = sess.get_inputs()[0].name
    output_name = sess.get_outputs()[0].name
    
    class InputData(BaseModel):
        features: list[float]
    
    @app.post("/predict")
    def predict(data: InputData):
        input_array = np.array([data.features], dtype=np.float32)
        prediction = sess.run([output_name], {input_name: input_array})[0]
        return {"prediction": int(prediction[0])}
    
  3. 更新requirements.txt:
    fastapi
    pydantic
    onnxruntime
    numpy
    

onnxruntime的安装包体积远小于scikit-learn,能适配Deta的部署限制。

方案2:将决策树规则转为纯Python代码

如果你不想引入新依赖,可以把训练好的决策树规则导出为文本,手动转成Python条件判断逻辑,完全摆脱scikit-learn依赖:

  1. 导出决策树规则:
    from sklearn.tree import export_text
    rule_text = export_text(model, feature_names=your_feature_names)
    print(rule_text)
    
  2. 手动实现预测逻辑:
    比如导出的规则类似:
    |--- feature_0 <= 5.0
    |   |--- class: 0
    |--- feature_0 >  5.0
    |   |--- class: 1
    
    则在FastAPI中写:
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    app = FastAPI()
    
    class InputData(BaseModel):
        features: list[float]
    
    @app.post("/predict")
    def predict(data: InputData):
        feature_0 = data.features[0]
        if feature_0 <= 5.0:
            return {"prediction": 0}
        else:
            return {"prediction": 1}
    
    这种方式不需要任何机器学习库,部署体积极小。

方案3:尝试指定scikit-learn旧版本

部分旧版本的scikit-learn体积更小,你可以在requirements.txt中指定具体版本,比如:

fastapi
pydantic
scikit-learn==1.0.2

旧版本的依赖包体积可能低于Deta的限制,可尝试重新部署。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:25:30