美文网首页
Catboost-在线预测

Catboost-在线预测

作者: 八刀一闪 | 来源:发表于2022-03-15 12:23 被阅读0次

生产环境很多时候是需要实时对数据进行预测的,即离线训练好模型后将模型保存为模型文件,然后在线服务将模型加载到内存

引入pom.xml

<dependency>
    <groupId>ai.catboost</groupId>
    <artifactId>catboost-common</artifactId>
    <version>0.26</version>
</dependency>

<dependency>
    <groupId>ai.catboost</groupId>
    <artifactId>catboost-prediction</artifactId>
    <version>0.26</version>
</dependency>

样例代码

需要注意的地方

  1. catboost模型需要同时传入float特征和category特征值
  2. 需要将模型的预测值通过sigmod激活函数来映射为概率值
import ai.catboost.CatBoostModel;

List<String> floatFeatures;
List<String> categoryFeatures;
Map<String, String> feature = new HashMap(); // 输入的特征值

try {
    CatBoostModel model = CatBoostModel.loadModel("model.cbm");
    CatBoostModel model = CatBoostModel.loadModel(InputStream is); // 也可以从InputStream加载模型

    float[] floatVector = new float[floatFeatures.size()];
    String[] categoryVector = new String[categoryFeatures.size()];
    for (int i = 0; i < floatFeatures.size(); i++) {
        String f = feature.getOrDefault(floatFeatures.get(i), "-1.0");
        floatVector[i] = Float.parseFloat(f);
    }
    for (int i = 0; i < categoryFeatures.size(); i++) {
        String f = feature.getOrDefault(categoryFeatures.get(i), "NA");
        categoryVector[i] = f;
    }
    CatBoostPredictions prediction = model.predict(floatVector, categoryVector);
    return 1.0 / (1.0 + Math.exp(-prediction.get(0, 0))); // 需要使用sigmod激活函数来转化为概率值
} catch (CatBoostError e) {
    e.printStackTrace();
    return -1.0;
}

原文链接

相关文章

网友评论

      本文标题:Catboost-在线预测

      本文链接:https://www.haomeiwen.com/subject/uadmgqtx.html