基于GBDT回归模型的案例
#1.读取数据
import numpy as np
import pandas as pd
df=pd.read_excel('信用评分卡模型.xlsx')
print(df.head())
#2.提取特征变量和目标变量
X=df.drop(columns='信用评分')
y=df['信用评分']
#3. 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=123)
#4.模型训练及搭建
from sklearn.ensemble import GradientBoostingRegressor
model=GradientBoostingRegressor()
model.fit(X_train,y_train)
#5.模型预测及评估
y_pred=model.predict(X_test)
#print(y_pred[0:10])
y_pred_new=np.round(y_pred,2)#保留两位有效数字可行
a=pd.DataFrame()
a['预测值']=list(y_pred_new)
a['实际值']=list(y_test)
print(a.head())
总结
在模型预测及评估中,输出的预测值有多位小数点。
转换为两位有效数字重点在于:
y_pred_new=np.round(y_pred,2)
之前试过用
print(round(y_pred[0:10],2))
有点异想天开,单个数字这样是可以的,但对于多维数组而言,是会报错的,如下:
TypeError: type numpy.ndarray doesn't define __round__ method
关键在于,先将列表转化为数组时用round(y_pred,2)取两位有效数字,再将数组转为列表。