Extract make metric name from ranking metric. (#8768)

- Extract the metric parsing routine from ranking.
- Add a test.
- Accept null for string view.
This commit is contained in:
Jiaming Yuan
2023-02-09 18:30:21 +08:00
committed by GitHub
parent 4ead65a28c
commit 5f76edd296
9 changed files with 142 additions and 34 deletions

View File

@@ -0,0 +1,34 @@
/**
* Copyright 2023 by XGBoost contributors
*/
#include "ranking_utils.h"
#include <cstdint> // std::uint32_t
#include <sstream> // std::ostringstream
#include <string> // std::string,std::sscanf
#include "xgboost/string_view.h" // StringView
namespace xgboost {
namespace ltr {
std::string MakeMetricName(StringView name, StringView param, std::uint32_t* topn, bool* minus) {
std::string out_name;
if (!param.empty()) {
std::ostringstream os;
if (std::sscanf(param.c_str(), "%u[-]?", topn) == 1) {
os << name << '@' << param;
out_name = os.str();
} else {
os << name << param;
out_name = os.str();
}
if (*param.crbegin() == '-') {
*minus = true;
}
} else {
out_name = name.c_str();
}
return out_name;
}
} // namespace ltr
} // namespace xgboost

View File

@@ -0,0 +1,29 @@
/**
* Copyright 2023 by XGBoost contributors
*/
#ifndef XGBOOST_COMMON_RANKING_UTILS_H_
#define XGBOOST_COMMON_RANKING_UTILS_H_
#include <cstddef> // std::size_t
#include <cstdint> // std::uint32_t
#include <string> // std::string
#include "xgboost/string_view.h" // StringView
namespace xgboost {
namespace ltr {
/**
* \brief Construct name for ranking metric given parameters.
*
* \param [in] name Null terminated string for metric name
* \param [in] param Null terminated string for parameter like the `3-` in `ndcg@3-`.
* \param [out] topn Top n documents parsed from param. Unchanged if it's not specified.
* \param [out] minus Whether we should turn the score into loss. Unchanged if it's not
* specified.
*
* \return The name of the metric.
*/
std::string MakeMetricName(StringView name, StringView param, std::uint32_t* topn, bool* minus);
} // namespace ltr
} // namespace xgboost
#endif // XGBOOST_COMMON_RANKING_UTILS_H_