Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[R] Allow predictions on lgb.Dataset objects #1939

Closed
vspinu opened this issue Jan 10, 2019 · 7 comments
Closed

[R] Allow predictions on lgb.Dataset objects #1939

vspinu opened this issue Jan 10, 2019 · 7 comments

Comments

@vspinu
Copy link

vspinu commented Jan 10, 2019

Surprisingly one has to pass an lgb.Dataset for lgb.train evaluation but cannot use predict method on it.

For instance I would expect something along the following to work:

> dtest <- lgb.Dataset(..)
> fit <- lgb.train(...,  valids = list(tst = dtest))
> fit$predict(dtest)
Error in predictor$predict(data, num_iteration, rawscore, predleaf, predcontrib,  : 
  predict: cannot predict on data of classlgb.Dataset’‘R6

─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R Under development (unstable) (2018-12-01 r75733)
 os       Ubuntu 18.04.1 LTS
 system   x86_64, linux-gnu
 ui       X11
 language
 collate  en_GB.UTF-8
 ctype    en_GB.UTF-8
 tz       Europe/Amsterdam
 date     2019-01-11

─ Packages ───────────────────────────────────────────────────────────────────
 package     * version    date       lib source
 assertthat    0.2.0      2017-04-11 [1] CRAN (R 3.5.0)
 backports     1.1.2      2017-12-13 [1] CRAN (R 3.5.0)
 callr         3.0.0.9002 2018-12-03 [1] Github (r-lib/callr@1cbce9d)
 cli           1.0.1      2018-09-25 [1] CRAN (R 3.6.0)
 crayon        1.3.4      2017-09-16 [1] CRAN (R 3.5.0)
 desc          1.2.0      2018-05-01 [1] CRAN (R 3.6.0)
 devtools      2.0.1.9000 2018-12-03 [1] Github (r-lib/devtools@a6bbe87)
 digest        0.6.18     2018-10-10 [1] CRAN (R 3.6.0)
 fs            1.2.6      2018-08-23 [1] CRAN (R 3.6.0)
 glue          1.3.0      2018-07-17 [1] CRAN (R 3.6.0)
 magrittr      1.5        2014-11-22 [1] CRAN (R 3.5.0)
 memoise       1.1.0      2017-04-21 [1] CRAN (R 3.5.0)
 pkgbuild      1.0.2.9000 2018-12-03 [1] Github (r-lib/pkgbuild@6e4ebdf)
 pkgload       1.0.1.9000 2018-12-03 [1] Github (r-lib/pkgload@0ef4f58)
 prettyunits   1.0.2      2015-07-13 [1] CRAN (R 3.5.0)
 processx      3.2.0.9001 2018-12-03 [1] Github (r-lib/processx@366475b)
 ps            1.2.1      2018-11-06 [1] CRAN (R 3.6.0)
 R6            2.3.0      2018-10-04 [1] CRAN (R 3.6.0)
 Rcpp          1.0.0      2018-11-07 [1] CRAN (R 3.6.0)
 remotes       2.0.2.9000 2018-12-03 [1] Github (r-lib/remotes@2e3bf35)
 rlang         0.3.0.9001 2018-12-18 [1] Github (r-lib/rlang@327740f)
 rprojroot     1.3-2      2018-01-03 [1] CRAN (R 3.5.0)
 sessioninfo   1.1.1      2018-11-05 [1] CRAN (R 3.6.0)
 testthat      2.0.0      2017-12-13 [1] CRAN (R 3.5.0)
 usethis       1.4.0      2018-08-14 [1] CRAN (R 3.6.0)
 withr         2.1.2.9000 2018-10-23 [1] Github (jimhester/withr@be57595)

[1] /home/vspinu/.lib/3.6.0
[2] /home/vspinu/bin/R-latest/library
@Laurae2
Copy link
Contributor

Laurae2 commented Jan 11, 2019

Using lgb.Dataset to predict would not work because it is not the original unbinned data. The lgb.Dataset is a binary dataset optimized only for training.

@vspinu
Copy link
Author

vspinu commented Jan 11, 2019

I see. How come that you can do evaluation on that dataset while traning. Don't you need to predict first?

@Laurae2
Copy link
Contributor

Laurae2 commented Jan 13, 2019

If I remember, during the model training, the model is still using the bins and not the exact values, therefore the prediction uses the bins directly.

ping @guolinke for clarification

@Laurae2
Copy link
Contributor

Laurae2 commented Jan 27, 2019

@vspinu Predictions during training are done using binned data. That's why while training you do not need the "out of LightGBM" predict.

However, for real predictions, passing LightGBM binary data to predict is not correct: LightGBM binary datasets hold the bins, not the exact values of each observation/feature combination. Therefore, reverse engineering the original values to predict from binary data is not possible (as one bin might fall in two splits at the same time).

@Laurae2 Laurae2 closed this as completed Jan 27, 2019
@vspinu
Copy link
Author

vspinu commented Jan 27, 2019

Thanks @Laurae2. Do you mean 'bins" like in histogram bins?

I am now worried about the following scenario:

dtrain <- lgb.Dataset(...)
dtest <- lgb.Dataset(...)
fit <- lgb.train(dtrain,  valids = list(tst = dtest))

If binary contains only bins, does this mean that the dtrain and dtest binary datasets can have different "bins" assignments? If so, then validation on the dtest dataset has no sense just like prediction on dtest.

@Laurae2
Copy link
Contributor

Laurae2 commented Jan 27, 2019

Your interpretation should be correct: lgb.Dataset.create.valid should be used instead for the validation.

Bins do refer to histogram bins constructed by lgb.Dataset.

@guolinke How do you pass free_raw_data = FALSE to lgb.Dataset.create.valid, or should it not be used in conjunction with lgb.Dataset.create.valid?

Example:

require(lightgbm)
require(methods)

# We load in the agaricus dataset
# In this example, we are aiming to predict whether a mushroom is edible
data(agaricus.train, package = "lightgbm")
data(agaricus.test, package = "lightgbm")
train <- agaricus.train
test <- agaricus.test

dtrain <- lgb.Dataset(data = train$data, label = train$label, free_raw_data = FALSE)
dtest <- lgb.Dataset.create.valid(dtrain, data = test$data, label = test$label, free_raw_data = FALSE)

valids <- list(train = dtrain, test = dtest)

print("Train lightgbm using lgb.train with valids")
bst <- lgb.train(data = dtrain,
                 num_leaves = 4,
                 learning_rate = 1,
                 nrounds = 2,
                 valids = valids,
                 nthread = 2,
                 objective = "binary")

Leads to fatal error:

[LightGBM] [Warning] Starting from the 2.1.2 version, default value for the "boost_from_average" parameter in "binary" objective is true.
This may cause significantly different results comparing to the previous versions of LightGBM.
Try to set boost_from_average=false, if your old models produce bad results
[LightGBM] [Info] Number of positive: 3140, number of negative: 3373
[LightGBM] [Info] Total Bins 128
[LightGBM] [Info] Number of data: 6513, number of used features: 107
[LightGBM] [Fatal] [Used indices of subset]: does not tolerate element [#0 = -1] outside [0, 6512]
[LightGBM] [Fatal] Length of label is not same with #data
[LightGBM] [Info] [binary:BoostFromScore]: pavg=0.482113 -> initscore=-0.071580
[LightGBM] [Info] Start training from score -0.071580
[1]:	train's binary_logloss:0.198597	test's binary_logloss:0.198597 
[2]:	train's binary_logloss:0.111535	test's binary_logloss:0.111535 

@StrikerRUS
Copy link
Collaborator

@Laurae2 Can this be closed since demos were fixed?

@Laurae2 Laurae2 closed this as completed Feb 12, 2019
alisterw pushed a commit to G-Research/LightGBM that referenced this issue Feb 13, 2019
#2)

* [ci] removed temp brew hotfix and deprecated sudo option (microsoft#1951)

* removed brew hotfix and deprecated sudo option on Travis

* removed brew hotfix on Azure

* updated Boost docs (microsoft#1955)

* removed warnings about types in comparison ([-Wsign-compare]) (microsoft#1953)

* removed comparison warning

* fixed spacing

* [docs] ask to provide LightGBM version for issue (microsoft#1958)

* [R] Fix multiclass demo (microsoft#1940)

* Fix multiclass custom objective demo

* Use option not to boost from average instead of setting init score explicitly

* Reference microsoft#1846 when turning off boost_from_average

* Add trailing whitespace

* [R] Correcting lgb.prepare output comment (microsoft#1831)

* Correcting lgb.prepare output comment

* updated Roxygen files

* [docs] bump xcode version in docs (microsoft#1952)

* fix typo

* [docs] Added the links to the libraries used (microsoft#1962)

* Added links to the libraries used.

* Fixing the header

* Fixes

* ot -> to

* [docs] fixed minor typos in documentation (microsoft#1959)

* fixed minor typos in documentation

* fixed typo in gpu_tree_learner.cpp

* Update .gitignore

* support to override some parameters in Dataset (microsoft#1876)

* add warnings for override parameters of Dataset

* fix pep8

* add feature_penalty

* refactor

* add R's code

* Update basic.py

* Update basic.py

* fix parameter bug

* Update lgb.Dataset.R

* fix a bug

* Fix build on macOS Mojave (microsoft#1923)

* Fix build on macOS Mojave

Fixed microsoft#1898

- https://iscinumpy.gitlab.io/post/omp-on-high-sierra/
- https://cliutils.gitlab.io/modern-cmake/chapters/packages/OpenMP.html
- Homebrew/homebrew-core#20589

* update setup.py

* update docs

* fix setup.py

* update docs

* update docs

* update setup.py

* update docs

* [tests][python] added tests for metrics' behavior and fixed case for multiclass task with custom objective (microsoft#1954)

* added metrics test for standard interface

* simplified code

* less trees

* less trees

* use dummy custom objective and metric

* added tests for multiclass metrics aliases

* fixed bug in case of custom obj and num_class > 1

* added metric test for sklearn wrapper

* [python][R][docs] added possibility to install with Visual Studio 2019 Preview (microsoft#1956)

* Found error from microsoft#1939 (microsoft#1974)

* fix more edge cases in mape (microsoft#1977)

* fix R's overflow (microsoft#1960)

* [tests][python] added test for huge string model (microsoft#1964)

* added test for huge string model

* fixed tree sizes field

* simplified model structure

* fixed test and added try/except

* fix nan in eval results (microsoft#1973)

* always save the score of the first round in early stopping

fix microsoft#1971

* avoid using std::log on non-positive numbers

* remove unnecessary changes

* add tests

* Update test_sklearn.py

* enhanced tests

* fix microsoft#1981

* [python] added OpenMP options for python-package installation (microsoft#1975)

* added OpenMP options for python-package installation

* fixed grammar typo

* improved model loading routines (microsoft#1979)

* [ci] refined command status check  (microsoft#1980)

* refined command status check

* refined Appveyor

* redirect all warnings to stdout

* cpplint whitespaces and new lines (microsoft#1986)

* fix microsoft#1994

* [docs] Fixed OpenCL Debian package name typo (microsoft#1995)

[docs] Fixed OpenCL Debian package name typo

* [python] convert datatable to numpy directly (microsoft#1970)

* convert datatable to numpy directly

* fix according to comments

* updated more docstrings

* simplified isinstance check

* Update compat.py

* [R-package] Fix demos not using lgb.Dataset.create.valid (microsoft#1993)

* Hand edit broken commit

* Hand edit broken commit

* Hand edit broken commit

* Hand edit broken commit

* 2.2.3 release (microsoft#1987)

* Update DESCRIPTION

* Update DESCRIPTION

* update version number at master branch (microsoft#1996)

* Update VERSION.txt

* Update .appveyor.yml

* Update DESCRIPTION

* Initial attempt to implement appending features in-memory to another data set

The intent is for this to enable munging files together easily, without needing to round-trip via numpy or write multiple copies to disk.
In turn, that enables working more efficiently with data sets that were written separately.

* Implement Dataset.dump_text, and fix small bug in appending of group bin boundaries.

Dumping to text enables us to compare results, without having to worry about issues like features being reordered.

* Add basic tests for validation logic for add_features_from.

* Remove various internal mapping items from dataset text dumps

These are too sensitive to the exact feature order chosen, which is not visible to the user.
Including them in tests appears unnecessary, as the data dumping code should provide enough coverage.

* Add test that add_features_from results in identical data sets according to dump_text.

* Add test that booster behaviour after using add_features_from matches that of training on the full data

This checks:
- That training after add_features_from works at all
- That add_features_from does not cause training to misbehave

* Expose feature_penalty and monotone_types/constraints via get_field

These getters allow us to check that add_features_from does the right thing with these vectors.

* Add tests that add_features correctly handles feature_penalty and monotone_constraints.

* Ensure add_features_from properly frees the added dataset and add unit test for this

Since add_features_from moves the feature group pointers from the added dataset to the dataset being added to, the added dataset is invalid after the call.
We must ensure we do not try and access this handle.

* Remove some obsolete TODOs

* Tidy up DumpTextFile by using a single iterator for each feature

This iterators were also passed around as raw pointers without being freed, which is now fixed.

* Factor out offsetting logic in AddFeaturesFrom

* Remove obsolete TODO

* Remove another TODO

This one is debatable, test code can be a bit messy and duplicate-heavy, factoring it out tends to end badly.
Leaving this for now, will revisit if adding more tests later on becomes a mess.

* Add documentation for newly-added methods.

* Initial work towards add_data_from

This currently only merges the feature groups and updates num_data_.
It does not deal with Metadata or non-dense bins yet.

* Fix bug where dense bin copy of num_data_ wasn't updated

* Small bug fix in dense_bin.hpp, initial implementation of Merge for 4-bits bin.

* Add unit test for dense bin case of add_data_from, and refactor tests slightly.

* Initial implementation of Merge for sparse bins and unit tests for it.

* Ensure we test merging sparse data sets after loading them from binary

This seems silly, but push_buffers_ aren't populated if the data was loaded from a binary file.
This forces us to reconstruct the index,value form of the data in the target bin before merging.
Adding this test ensures that code is covered.

* Add labels to text dumps.

* Add weights to text dumps.

* Ensure add_data_from properly merges labels.

* Ensure metadata appends weights correctly, and unit test for it.

* Implement metadata merging for query bits

This is currently not covered by unit tests.

* Check datasets are aligned before merging.

This catches the majority of obvious errors, e.g. not having the same number of features or having different bin mappings.

* Add test that booster behaviour is preserved by add_data_from.

* Add configuration parameters for CEGB.

* Add skeleton CEGB tree learner

Like the original CEGB version, this inherits from SerialTreeLearner.
Currently, it changes nothing from the original.

* Track features used in CEGB tree learner.

* Pull CEGB tradeoff and coupled feature penalty from config.

* Implement finding best splits for CEGB

This is heavily based on the serial version, but just adds using the coupled penalties.

* Set proper defaults for cegb parameters.

* Ensure sanity checks don't switch off CEGB.

* Implement per-data-point feature penalties in CEGB.

* Implement split penalty and remove unused parameters.

* Merge changes from CEGB tree learner into serial tree learner

* Represent features_used_in_data by a bitset, to reduce the memory overhead of CEGB, and add sanity checks for the lengths of the penalty vectors.
@lock lock bot locked as resolved and limited conversation to collaborators Mar 11, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants