生產(chǎn)環(huán)境很多時候是需要實時對數(shù)據(jù)進行預測的,即離線訓練好模型后將模型保存為模型文件又活,然后在線服務(wù)將模型加載到內(nèi)存
引入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>
樣例代碼
需要注意的地方
- catboost模型需要同時傳入float特征和category特征值
- 需要將模型的預測值通過sigmod激活函數(shù)來映射為概率值
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激活函數(shù)來轉(zhuǎn)化為概率值
} catch (CatBoostError e) {
e.printStackTrace();
return -1.0;
}