sklearn_example.py 2.08 KB
Newer Older
wxchan's avatar
wxchan committed
1
2
# coding: utf-8
# pylint: disable = invalid-name, C0111
3
import numpy as np
wxchan's avatar
wxchan committed
4
import pandas as pd
5
6
import lightgbm as lgb

wxchan's avatar
wxchan committed
7
from sklearn.metrics import mean_squared_error
8
from sklearn.model_selection import GridSearchCV
wxchan's avatar
wxchan committed
9
10

# load or create your dataset
11
print('Load data...')
wxchan's avatar
wxchan committed
12
13
14
df_train = pd.read_csv('../regression/regression.train', header=None, sep='\t')
df_test = pd.read_csv('../regression/regression.test', header=None, sep='\t')

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

20
print('Start training...')
wxchan's avatar
wxchan committed
21
22
23
24
# train
gbm = lgb.LGBMRegressor(objective='regression',
                        num_leaves=31,
                        learning_rate=0.05,
25
                        n_estimators=20)
wxchan's avatar
wxchan committed
26
27
gbm.fit(X_train, y_train,
        eval_set=[(X_test, y_test)],
28
29
        eval_metric='l1',
        early_stopping_rounds=5)
wxchan's avatar
wxchan committed
30

31
print('Start predicting...')
wxchan's avatar
wxchan committed
32
# predict
33
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration_)
wxchan's avatar
wxchan committed
34
35
# eval
print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)
36
37

# feature importances
38
print('Feature importances:', list(gbm.feature_importances_))
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

# self-defined eval metric
# f(y_true: array, y_pred: array) -> name: string, eval_result: float, is_higher_better: bool
# Root Mean Squared Logarithmic Error (RMSLE)
def rmsle(y_true, y_pred):
    return 'RMSLE', np.sqrt(np.mean(np.power(np.log1p(y_pred) - np.log1p(y_true), 2))), False


print('Start training with custom eval function...')
# train
gbm.fit(X_train, y_train,
        eval_set=[(X_test, y_test)],
        eval_metric=rmsle,
        early_stopping_rounds=5)

print('Start predicting...')
# predict
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration_)
# eval
print('The rmsle of prediction is:', rmsle(y_test, y_pred)[1])

61
# other scikit-learn modules
62
63
64
65
66
67
68
estimator = lgb.LGBMRegressor(num_leaves=31)

param_grid = {
    'learning_rate': [0.01, 0.1, 1],
    'n_estimators': [20, 40]
}

69
gbm = GridSearchCV(estimator, param_grid, cv=3)
70
71
72
73

gbm.fit(X_train, y_train)

print('Best parameters found by grid search are:', gbm.best_params_)