LightGBM uses a Dataset object to store data. It supports various input formats including LibSVM/TSV/CSV text files, NumPy arrays, SciPy sparse matrices, pandas/polars DataFrames, pyarrow Tables, and LightGBM binary files.
Key features for Dataset construction:
- Categorical Features: You can pass
categorical_feature names directly. LightGBM handles them without one-hot encoding, providing a significant speed-up. Note: You must convert categorical features to int type before constructing the Dataset. - Weights: Use the
weight parameter or Dataset.set_weight() to assign weights to samples. - Feature Names: Use the
feature_name parameter to specify names. - Memory Efficiency: To save memory, set
free_raw_data=True (default) or explicitly set raw_data=None after construction.
import numpy as np
import lightgbm as lgb
# From NumPy arrays
rng = np.random.default_rng()
data = rng.uniform(size=(500, 10))
label = rng.integers(low=0, high=2, size=(500, ))
train_data = lgb.Dataset(data, label=label, feature_name=['c1', 'c2', 'c3'], categorical_feature=['c3'])
# From LibSVM/Binary files
train_data = lgb.Dataset('train.svm.bin')
# From SciPy sparse matrix
import scipy
csr = scipy.sparse.csr_matrix((dat, (row, col)))
train_data = lgb.Dataset(csr)