"...git@developer.sourcefind.cn:tianlh/lightgbm-dcu.git" did not exist on "8ab35255a5cb192a7e2b78e4eaa7b2b3483d3c1b"
plot_example.py 1.93 KB
Newer Older
1
# coding: utf-8
2
3
from pathlib import Path

4
5
import pandas as pd

6
7
import lightgbm as lgb

8
if lgb.compat.MATPLOTLIB_INSTALLED:
9
    import matplotlib.pyplot as plt
10
else:
11
    raise ImportError("You need to install matplotlib and restart your session for plot_example.py.")
12

13
print("Loading data...")
14
# load or create your dataset
15
16
17
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")
18

19
20
21
22
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)
23
24

# create dataset for lightgbm
25
26
27
28
29
30
lgb_train = lgb.Dataset(
    X_train,
    y_train,
    feature_name=[f"f{i + 1}" for i in range(X_train.shape[-1])],
    categorical_feature=[21],
)
31
lgb_test = lgb.Dataset(X_test, y_test, reference=lgb_train)
32
33

# specify your configurations as a dict
34
params = {"num_leaves": 5, "metric": ("l1", "l2"), "verbose": 0}
35

36
37
evals_result = {}  # to record eval results for plotting

38
print("Starting training...")
39
# train
40
41
42
43
44
gbm = lgb.train(
    params,
    lgb_train,
    num_boost_round=100,
    valid_sets=[lgb_train, lgb_test],
45
    callbacks=[lgb.log_evaluation(10), lgb.record_evaluation(evals_result)],
46
)
47

48
49
print("Plotting metrics recorded during training...")
ax = lgb.plot_metric(evals_result, metric="l1")
50
plt.show()
51

52
print("Plotting feature importances...")
53
54
ax = lgb.plot_importance(gbm, max_num_features=10)
plt.show()
wxchan's avatar
wxchan committed
55

56
57
print("Plotting split value histogram...")
ax = lgb.plot_split_value_histogram(gbm, feature="f26", bins="auto")
58
59
plt.show()

60
61
print("Plotting 54th tree...")  # one tree use categorical feature to split
ax = lgb.plot_tree(gbm, tree_index=53, figsize=(15, 15), show_info=["split_gain"])
wxchan's avatar
wxchan committed
62
plt.show()
63

64
65
print("Plotting 54th tree with graphviz...")
graph = lgb.create_tree_digraph(gbm, tree_index=53, name="Tree54")
66
graph.render(view=True)