# coding: utf-8
# pylint: disable = invalid-name, C0111
import json
import lightgbm as lgb
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
iris = load_iris()
data=iris.data
target = iris.target
X_train,X_test,y_train,y_test =train_test_split(data,target,test_size=0.2)
# 加載你的數據
# print('Load data...')
# df_train = pd.read_csv('../regression/regression.train', header=None, sep='\t')
# df_test = pd.read_csv('../regression/regression.test', header=None, sep='\t')
#
# 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
# 創(chuàng)建成lgb特征的數據集格式
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
# 將參數寫成字典下形式
params = {
'task': 'train',
'boosting_type': 'gbdt', # 設置提升類型
'objective': 'regression', # 目標函數
'metric': {'l2', 'auc'}, # 評估函數
'num_leaves': 31, # 葉子節(jié)點數
'learning_rate': 0.05, # 學習速率
'feature_fraction': 0.9, # 建樹的特征選擇比例
'bagging_fraction': 0.8, # 建樹的樣本采樣比例
'bagging_freq': 5, # k 意味著每 k 次迭代執(zhí)行bagging
'verbose': 1 # <0 顯示致命的, =0 顯示錯誤 (警告), >0 顯示信息
}
print('Start training...')
# 訓練 cv and train
gbm = lgb.train(params,lgb_train,num_boost_round=20,valid_sets=lgb_eval,early_stopping_rounds=5)
print('Save model...')
# 保存模型到文件
gbm.save_model('model.txt')
print('Start predicting...')
# 預測數據集
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
# 評估模型
print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)
快把你的結果在評論區(qū)里亮出來吧!
聯系客服