xgboost/tests/cpp/linear/test_linear.cc
Jiaming Yuan 972730cde0
Use matrix for gradient. (#9508)
- Use the `linalg::Matrix` for storing gradients.
- New API for the custom objective.
- Custom objective for multi-class/multi-target is now required to return the correct shape.
- Custom objective for Python can accept arrays with any strides. (row-major, column-major)
2023-08-24 05:29:52 +08:00

72 lines
2.0 KiB
C++

/*!
* Copyright 2018-2019 by Contributors
*/
#include <xgboost/linear_updater.h>
#include <xgboost/gbm.h>
#include "../helpers.h"
#include "test_json_io.h"
#include "../../../src/gbm/gblinear_model.h"
#include "xgboost/base.h"
namespace xgboost {
TEST(Linear, Shotgun) {
size_t constexpr kRows = 10;
size_t constexpr kCols = 10;
auto p_fmat = xgboost::RandomDataGenerator(kRows, kCols, 0).GenerateDMatrix();
auto ctx = MakeCUDACtx(GPUIDX);
LearnerModelParam mparam{MakeMP(kCols, .5, 1)};
{
auto updater =
std::unique_ptr<xgboost::LinearUpdater>(xgboost::LinearUpdater::Create("shotgun", &ctx));
updater->Configure({{"eta", "1."}});
linalg::Matrix<xgboost::GradientPair> gpair{
linalg::Constant(&ctx, xgboost::GradientPair(-5, 1.0), p_fmat->Info().num_row_, 1)};
xgboost::gbm::GBLinearModel model{&mparam};
model.LazyInitModel();
updater->Update(&gpair, p_fmat.get(), &model, gpair.Size());
ASSERT_EQ(model.Bias()[0], 5.0f);
}
{
auto updater = std::unique_ptr<xgboost::LinearUpdater>(
xgboost::LinearUpdater::Create("shotgun", &ctx));
EXPECT_ANY_THROW(updater->Configure({{"feature_selector", "random"}}));
}
}
TEST(Shotgun, JsonIO) {
TestUpdaterJsonIO("shotgun");
}
TEST(Linear, coordinate) {
size_t constexpr kRows = 10;
size_t constexpr kCols = 10;
auto p_fmat = xgboost::RandomDataGenerator(kRows, kCols, 0).GenerateDMatrix();
auto ctx = MakeCUDACtx(GPUIDX);
LearnerModelParam mparam{MakeMP(kCols, .5, 1)};
auto updater = std::unique_ptr<xgboost::LinearUpdater>(
xgboost::LinearUpdater::Create("coord_descent", &ctx));
updater->Configure({{"eta", "1."}});
linalg::Matrix<xgboost::GradientPair> gpair{
linalg::Constant(&ctx, xgboost::GradientPair(-5, 1.0), p_fmat->Info().num_row_, 1)};
xgboost::gbm::GBLinearModel model{&mparam};
model.LazyInitModel();
updater->Update(&gpair, p_fmat.get(), &model, gpair.Size());
ASSERT_EQ(model.Bias()[0], 5.0f);
}
TEST(Coordinate, JsonIO){
TestUpdaterJsonIO("coord_descent");
}
} // namespace xgboost