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

7
print('Loading data...')
wxchan's avatar
wxchan committed
8
9
10
11
# load or create your dataset
df_train = pd.read_csv('../regression/regression.train', header=None, sep='\t')
df_test = pd.read_csv('../regression/regression.test', header=None, sep='\t')

12
13
14
15
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
16
17
18
19

# 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
20

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

34
print('Starting training...')
wxchan's avatar
wxchan committed
35
36
37
# train
gbm = lgb.train(params,
                lgb_train,
38
                num_boost_round=20,
Guolin Ke's avatar
Guolin Ke committed
39
                valid_sets=lgb_eval,
40
                early_stopping_rounds=5)
wxchan's avatar
wxchan committed
41

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

46
print('Starting predicting...')
wxchan's avatar
wxchan committed
47
48
49
50
# predict
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
# eval
print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)