sklearn_example.py 1.42 KB
Newer Older
wxchan's avatar
wxchan committed
1
2
3
4
5
# coding: utf-8
# pylint: disable = invalid-name, C0111
import lightgbm as lgb
import pandas as pd
from sklearn.metrics import mean_squared_error
6
from sklearn.model_selection import GridSearchCV
wxchan's avatar
wxchan committed
7
8

# load or create your dataset
9
print('Load data...')
wxchan's avatar
wxchan committed
10
11
12
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
13
14
15
16
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
17

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

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

# feature importances
36
print('Feature importances:', list(gbm.feature_importances_))
37

38
# other scikit-learn modules
39
40
41
42
43
44
45
46
47
48
49
50
estimator = lgb.LGBMRegressor(num_leaves=31)

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

gbm = GridSearchCV(estimator, param_grid)

gbm.fit(X_train, y_train)

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