近期使用了LightGBM進行了訓練模型(計算違約概率),結(jié)果發(fā)現(xiàn)其余XGBoost模型訓練得到的結(jié)果存在較高相關(guān)性。
模型訓練之后,主要通過JAVA進行部署,網(wǎng)上搜集了https://github.com/lyg5623/lightgbm_predict4j 這個開源項目,但是針對最新的LightGBM庫所輸出的模型文件不可用。因此,先用python將模型輸出的JSON文件進行模型讀取的翻譯,然后再將Python腳本翻譯成JAVA代碼。
1、參考資料
以下是在學習LightGBM模型過程中所搜集的一些資料,對于理解模型背后的原理、參數(shù)的作用具有極大的幫助。
1.1 中文文檔
http://lightgbm.apachecn.org/cn/latest/index.html
1.2 如何進行調(diào)參
http://www.itdecent.cn/p/b4ac0596e5ef
1.3 應(yīng)用案例
https://github.com/wanglei5205/Machine_learning
https://blog.csdn.net/qushoushi0594/article/details/80040837
2、模型輸出
在訓練完模型后,使用如下代碼將模型保存為JSON格式。
json_model = gbm.dump_model()
file_name = 'gbm_model.json'
with open(file_name,'w') as file_object:
json.dump(json_model,file_object)
使用 http://jsoneditoronline.org/ 可以查看所輸出的JSON格式文件的具體形式,通過展開分析可以發(fā)現(xiàn),其具體就是將模型樹結(jié)構(gòu)轉(zhuǎn)換為JSON格式輸出。

接下來,使用python將模型輸出的JSON文件進行讀取,并遍歷每一棵樹結(jié)構(gòu),得到在每一顆樹上的得分,然后將分數(shù)求和,計算最終違約概率值。
import json
import numpy as np
import pandas as pd
file = open(r'gbm_model.json', "rb") # 讀取模型json文件
model = json.load(file)
feature_names = model['feature_names'] # 獲取模型中所用的特征變量
# 定義一個函數(shù)判斷每一個leaf是走left還是right
def decison(data,threshold,default_left):
'''
:param data: 特征值
:param threshold: 分割判斷值
:param default_left: 默認分支 default_left= True or False
:return: 返回結(jié)果left_child or right_child
'''
if ((np.isnan(data)) and (default_left is True)):
return 'left_child'
elif data <= threshold:
return 'left_child'
else:
return 'right_child'
# 定義預測函數(shù)
def predict_gbm(data):
score = 0
for i in range(len(model['tree_info'])): # 遍歷每一個節(jié)點
num_leaves = model['tree_info'][i]['num_leaves'] # 獲取每顆樹的節(jié)點數(shù)
tree = model['tree_info'][i]['tree_structure'] # 獲取每一顆樹結(jié)構(gòu)
for i in range(num_leaves): # 遍歷節(jié)點數(shù)
# 到達節(jié)點leaf,進行走向判斷
threshold = tree.get('threshold')
default_left = tree.get('default_left')
split_feature = feature_names[tree['split_feature']] # 獲取葉子節(jié)點的分割特征變量
next_decison = decison(data[split_feature],threshold,default_left)
# 獲取下一個分支leaf
tree = tree[next_decison]
if tree.get('left_child','not found') == 'not found': # 如果到達節(jié)點節(jié)點停止遍歷,返回對應(yīng)值
score = score + tree['leaf_value']
break
return(score)
# 進行測試
predict_df = []
for i in range(len(df)):
predict_data = predict_gbm(df.iloc[i,:]) # 分值
predict_dt = 1 / (np.exp(-predict_data) + 1) # 將預測分值轉(zhuǎn)為p值
predict_df.append(predict_dt)
以上Python是將JSON文件的樹結(jié)構(gòu)模型翻譯成了code,有了這個邏輯,再將其轉(zhuǎn)換為JAVA代碼非常簡單了,有需要者可私信我郵箱。