c++ 中的 xgboost 加载模型(python -> c++ 预测分数不匹配)

Lee*_*eor 6 c++ python xgboost

我正在联系所有 SO C++ 天才。

我已经在 python 中训练(并成功测试)了一个 xgboost 模型,如下所示:

dtrain 
=xgb.DMatrix(np.asmatrix(X_train),label=np.asarray(y_train,dtype=np.int), feature_names=feat_names)

optimal_model = xgb.train(plst, dtrain)

dtest = xgb.DMatrix(np.asmatrix(X_test),feature_names=feat_names)

optimal_model.save_model('sigdet.model')
Run Code Online (Sandbox Code Playgroud)

我关注了 XgBoost 上的一篇文章(见链接),它解释了在 C++ 中加载和应用预测的正确方法:

// Load Model
g_learner = std::make_unique<Learner>(Learner::Create({}));
        std::unique_ptr<dmlc::Stream> fi(
            dmlc::Stream::Create(filename, "r"));
        g_learner->Load(fi.get());

// Predict
    DMatrixHandle h_test;
        XGDMatrixCreateFromMat((float *)features, 1, numFeatures , -999.9f, &h_test);
        xgboost::bst_ulong out_len;


        std::vector<float> preds;
        g_learner->Predict((DMatrix*)h_test,true, &preds); 
Run Code Online (Sandbox Code Playgroud)

我的问题 (1):我需要创建一个 DMatrix*,但是我只有一个 DMatrixHandle。如何使用我的数据正确创建 DMatrix?

我的问题(2):当我尝试以下预测方法时:

DMatrixHandle h_test;
XGDMatrixCreateFromMat((float *)features, 1, numFeatures , -999.9f, &h_test);
xgboost::bst_ulong out_len;


int res = XGBoosterPredict(g_modelHandle, h_test, 1, 0, &out_len, (const float**)&scores);
Run Code Online (Sandbox Code Playgroud)

我得到的分数与加载完全相同的模型并将其用于预测(在 python 中)完全不同。

谁帮助我在 c++ 和 python 中获得一致的结果,可能会上天堂。顺便说一句,我需要在 c++ 中为实时应用程序应用预测,否则我会使用不同的语言。

小智 4

要获取 DMatrix,您可以执行以下操作:

g_learner->Predict(static_cast<std::shared_ptr<xgboost::DMatrix>*>(h_test)->get(), true, &pred);
Run Code Online (Sandbox Code Playgroud)

对于问题(2),我没有答案。这实际上和我有同样的问题。我在 python 中有一个 XGBRegression,并且在 C++ 中使用相同的功能获得了不同的结果。