simple_example.py 1.42 KB
Newer Older
wxchan's avatar
wxchan committed
1
# coding: utf-8
2
3
from pathlib import Path

wxchan's avatar
wxchan committed
4
5
6
import pandas as pd
from sklearn.metrics import mean_squared_error

7
8
import lightgbm as lgb

9
print("Loading data...")
wxchan's avatar
wxchan committed
10
# load or create your dataset
11
12
13
regression_example_dir = Path(__file__).absolute().parents[1] / "regression"
df_train = pd.read_csv(str(regression_example_dir / "regression.train"), header=None, sep="\t")
df_test = pd.read_csv(str(regression_example_dir / "regression.test"), header=None, sep="\t")
wxchan's avatar
wxchan committed
14

15
16
17
18
y_train = df_train[0]
y_test = df_test[0]
X_train = df_train.drop(0, axis=1)
X_test = df_test.drop(0, axis=1)
wxchan's avatar
wxchan committed
19
20
21
22

# create dataset for lightgbm
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
Guolin Ke's avatar
Guolin Ke committed
23

wxchan's avatar
wxchan committed
24
25
# specify your configurations as a dict
params = {
26
27
28
29
30
31
32
33
34
    "boosting_type": "gbdt",
    "objective": "regression",
    "metric": {"l2", "l1"},
    "num_leaves": 31,
    "learning_rate": 0.05,
    "feature_fraction": 0.9,
    "bagging_fraction": 0.8,
    "bagging_freq": 5,
    "verbose": 0,
wxchan's avatar
wxchan committed
35
36
}

37
print("Starting training...")
wxchan's avatar
wxchan committed
38
# train
39
40
41
gbm = lgb.train(
    params, lgb_train, num_boost_round=20, valid_sets=lgb_eval, callbacks=[lgb.early_stopping(stopping_rounds=5)]
)
wxchan's avatar
wxchan committed
42

43
print("Saving model...")
wxchan's avatar
wxchan committed
44
# save model to file
45
gbm.save_model("model.txt")
wxchan's avatar
wxchan committed
46

47
print("Starting predicting...")
wxchan's avatar
wxchan committed
48
49
50
# predict
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
# eval
51
rmse_test = mean_squared_error(y_test, y_pred) ** 0.5
52
print(f"The RMSE of prediction is: {rmse_test}")