LGB+XGB+CNN一般写法
现在的比赛,想要拿到一个好的名次,就一定要进行模型融合,这里总结一下三种基础的模型:
- lightgbm:由于现在的比赛数据越来越大,想要获得一个比较高的预测精度,同时又要减少内存占用以及提升训练速度,lightgbm是一个非常不错的选择,其可达到与xgboost相似的预测效果。
- xgboost:在lightgbm出来之前,是打比赛的不二之选,现在由于需要做模型融合以提高预测精度,所以也需要使用到xgboost。
- ANN:得益于现在的计算机技术的高度发展,以及GPU性能的提高,还有Keras,tensorflow,pytorch等多重工具的使用,人工神经网络也可以作为最后模型融合的子模型之一,可以有效地提升最终的预测结果。
下面附上使用三个函数的Python代码,可以直接运行。(参考:https://blog.csdn.net/meyh0x5vdtk48p2/article/details/78816334)
LGB
def LGB_predict(train_x,train_y,test_x,res,index):
print("LGB test")
clf = lgb.LGBMClassifier(
boosting_type='gbdt', num_leaves=31, reg_alpha=0.0, reg_lambda=1,
max_depth=-1, n_estimators=5000, objective='binary',
subsample=0.7, colsample_bytree=0.7, subsample_freq=1,
learning_rate=0.05, min_child_weight=50, random_state=2018, n_jobs=-1
)
clf.fit(train_x, train_y, eval_set=[(train_x, train_y)], eval_metric='auc',early_stopping_rounds=100)
res['score'+str(index)] = clf.predict_proba(test_x)[:,1]
res['score'+str(index)] = res['score'+str(index)].apply(lambda x: float('%.6f' % x))
print(str(index)+' predict finish!')
gc.collect()
res=res.reset_index(drop=True)
return res['score'+str(index)]
XGB
def XGB_predict(train_x,train_y,val_X,val_Y,test_x,res):
print("XGB test")
# create dataset for lightgbm xgb_val = xgb.DMatrix(val_X, label=val_Y)
xgb_train = xgb.DMatrix(X_train, label=y_train)
xgb_test = xgb.DMatrix(test_x)
# specify your configurations as a dict
params = {
'booster': 'gbtree',
# 'objective': 'multi:softmax', # 多分类的问题、
# 'objective': 'multi:softprob', # 多分类概率
'objective': 'binary:logistic',
'eval_metric': 'auc',
# 'num_class': 9, # 类别数,与 multisoftmax 并用
'gamma': 0.1, # 用于控制是否后剪枝的参数,越大越保守,一般0.1、0.2这样子。
'max_depth': 8, # 构建树的深度,越大越容易过拟合
'alpha': 0, # L1正则化系数
'lambda': 10, # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
'subsample': 0.7, # 随机采样训练样本
'colsample_bytree': 0.5, # 生成树时进行的列采样
'min_child_weight': 3,
# 这个参数默认是 1,是每个叶子里面 h 的和至少是多少,对正负样本不均衡时的 0-1 分类而言
# ,假设 h 在 0.01 附近,min_child_weight 为 1 意味着叶子节点中最少需要包含 100 个样本。
# 这个参数非常影响结果,控制叶子节点中二阶导的和的最小值,该参数值越小,越容易 overfitting。
'silent': 0, # 设置成1则没有运行信息输出,最好是设置为0.
'eta': 0.03, # 如同学习率
'seed': 1000,
'nthread': -1, # cpu 线程数
'missing': 1,
'scale_pos_weight': (np.sum(y==0)/np.sum(y==1)) # 用来处理正负样本不均衡的问题,通常取:sum(negative cases) / sum(positive cases)
# 'eval_metric': 'auc'
} plst = list(params.items())
num_rounds = 5000 # 迭代次数
watchlist = [(xgb_train, 'train'), (xgb_val, 'val')]
# 交叉验证
# result = xgb.cv(plst, xgb_train, num_boost_round=200, nfold=4, early_stopping_rounds=200, verbose_eval=True, folds=StratifiedKFold(n_splits=4).split(X, y))
# 训练模型并保存
# early_stopping_rounds 当设置的迭代次数较大时,early_stopping_rounds 可在一定的迭代次数内准确率没有提升就停止训练
model = xgb.train(plst, xgb_train, num_rounds, watchlist, early_stopping_rounds=200)
res['score'] = model.predict(xgb_test)
res['score'] = res['score'].apply(lambda x: float('%.6f' % x))
return res
CNN
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
X_train = imp.fit_transform(X_train)
sc = StandardScaler(with_mean=False)
sc.fit(X_train)
X_train = sc.transform(X_train)
val_X = sc.transform(val_X)
X_test = sc.transform(X_test) ann_scale = 1 from keras.layers import Embedding model = Sequential() model.add(Embedding(X_train.shape[1] + 1,
EMBEDDING_DIM,
input_length=MAX_SEQUENCE_LENGTH))
#model.add(Dense(int(256 / ann_scale), input_shape=(X_train.shape[1],)))
model.add(Dense(int(256 / ann_scale)))
model.add(Activation('tanh'))
model.add(Dropout(0.3))
model.add(Dense(int(512 / ann_scale)))
model.add(Activation('relu'))
model.add(Dropout(0.3))
model.add(Dense(int(512 / ann_scale)))
model.add(Activation('tanh'))
model.add(Dropout(0.3))
model.add(Dense(int(256 / ann_scale)))
model.add(Activation('linear'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
# For a multi-class classification problem
model.summary() class_weight1 = class_weight.compute_class_weight('balanced',
np.unique(y),
y) #-----------------------------------------------------------------------------------------------------------------------------------------------------
# AUC for a binary classifier
def auc(y_true, y_pred):
ptas = tf.stack([binary_PTA(y_true,y_pred,k) for k in np.linspace(0, 1, 1000)],axis=0)
pfas = tf.stack([binary_PFA(y_true,y_pred,k) for k in np.linspace(0, 1, 1000)],axis=0)
pfas = tf.concat([tf.ones((1,)) ,pfas],axis=0)
binSizes = -(pfas[1:]-pfas[:-1])
s = ptas*binSizes
return K.sum(s, axis=0) # PFA, prob false alert for binary classifier
def binary_PFA(y_true, y_pred, threshold=K.variable(value=0.5)):
y_pred = K.cast(y_pred >= threshold, 'float32')
# N = total number of negative labels
N = K.sum(1 - y_true)
# FP = total number of false alerts, alerts from the negative class labels
FP = K.sum(y_pred - y_pred * y_true)
return FP/N # P_TA prob true alerts for binary classifier
def binary_PTA(y_true, y_pred, threshold=K.variable(value=0.5)):
y_pred = K.cast(y_pred >= threshold, 'float32')
# P = total number of positive labels
P = K.sum(y_true)
# TP = total number of correct alerts, alerts from the positive class labels
TP = K.sum(y_pred * y_true)
return TP/P
#----------------------------------------------------------------------------------------------------------------------------------------------------- model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
# metrics=['accuracy'],
metrics=[auc])
epochs = 100
model.fit(X_train, y, epochs=epochs, batch_size=2000,
validation_data=(val_X, val_y), shuffle=True,
class_weight = class_weight1)
LGB+XGB+CNN一般写法的更多相关文章
- XAI/MLI 可解释机器学习系列1- 开源&paper汇总
一直在关注可解释机器学习领域,因为确实在工作中有许多应用 模型检查,特征重要性是否符合预期和AUC一样重要 模型解释,比起虚无缥缈的模型指标,解释模型学到的规律更能说服业务方 样本解释,为什么这些用户 ...
- xgb, lgb, Keras, LR(二分类、多分类代码)
preprocess # 通用的预处理框架 import pandas as pd import numpy as np import scipy as sp # 文件读取 def read_csv_ ...
- 网站SEO优化之Robots.txt文件写法。
作为网站开发者或网站管理员一定知道网站对搜索引擎的优化有多重要,好的网站不仅要有漂亮的界面,良好的用户体验,还要有较高的更新频率.要被百度.google这样的搜索引擎大量收录,才能增加网站展示量,访问 ...
- 卷积神经网络CNN全面解析
卷积神经网络(CNN)概述 从多层感知器(MLP)说起 感知器 多层感知器 输入层-隐层 隐层-输出层 Back Propagation 存在的问题 从MLP到CNN CNN的前世今生 CNN的预测过 ...
- qwe框架- CNN 实现
CNN实现 概述 我在qwe中有两种,第一种是按照Ng课程中的写法,多层循环嵌套得到每次的"小方格",然后WX+b,这样的做法是最简单,直观.但是效率极其慢.基本跑个10张以内图片 ...
- 详解卷积神经网络(CNN)
详解卷积神经网络(CNN) 详解卷积神经网络CNN 概揽 Layers used to build ConvNets 卷积层Convolutional layer 池化层Pooling Layer 全 ...
- 使用CNN做数字识别和人脸识别
上次写的一层神经网络也都贴这里了. 我有点困,我先睡觉,完了我再修改 这个代码写法不太符合工业代码的规范,仅仅是用来学习的的.还望各位见谅 import sys,ossys.path.append(o ...
- paper 162:卷积神经网络(CNN)解析
卷积神经网络(CNN)解析: 卷积神经网络CNN解析 概揽 Layers used to build ConvNets 卷积层Convolutional layer 池化层Pooling Layer ...
- obj.style.z-index的正确写法
obj.style.z-index的正确写法 今天发现obj.style.z-index在js里面报错,后来才知道在js里应该把含"-"的字符写成驼峰式,例如obj.style.z ...
随机推荐
- StringUtils.isBlank(str)和StringUtils.isEmpty(str)的区别
1.StringUtils.isEmpty(CharSequence cs)实现源码 public static boolean isEmpty(CharSequence cs) { return c ...
- python-字符串操作分类小结
切片 str[start:end:step] # 包括头,不包括尾巴.step为步长,意思是每隔step-1个元素,取一个字符 [::-1] #反向取字符串,实现字符串的反转 "abcde& ...
- 利用纯代码写出一个秒表表盘的方法 —— #DF
@interface ViewController () @property (nonatomic, strong) CALayer *secLayer; // 秒针layer @property ( ...
- 简单实现Tabbar的隐藏显示动画 By H罗
简单实现Tabbar的隐藏显示动画 Hide Tabbar Controller with Animation - (void)setTabBarVisible:(BOOL)visible anima ...
- Mac搭建Git服务器—开启SSH
SSH开启 在osx中开启ssh访问非常简单,只需要打开"系统偏好设置"并且点击"共享"图标即可. 选中下图中的check box即允许远程登陆.server处 ...
- 今天带大家了解一下ICMP协议及基本使用
ICMP协议的介绍及基本使用 1.IP数据包头的格式 2.ICMP协议的功能介绍 3.ICMP的基本使用方法 1.在讲解ICMP协议之前,我们先来简单了解一下IP数据包格式如图所示: 2.好现在切入正 ...
- MXNet学习-第一个例子:训练MNIST数据集
一个门外汉写的MXNET跑MNIST的例子,三层全连接层最后验证率是97%左右,毕竟是第一个例子,主要就是用来理解MXNet怎么使用. #导入需要的模块 import numpy as np #num ...
- GIL解释器锁 & 进程池与线程池
今日内容 GIL 全局解释器锁(重要理论) 验证 GIL 的存在及功能 验证 python 多线程是否有用 死锁现象 进程池与线程池(使用频率高) IO模型 详细参考: https://www.bil ...
- k8s集群节点ping不通其他主机的ip
文章目录 排查过程 本地宿主机网络检查 pod网络检查 tcpdump检查网络 检查flannel网卡 检查宿主机网卡 iptables检查 解决方法 测试环境服务出现问题,服务一直报错认证超时,检查 ...
- ASP.NET Core 6框架揭秘实例演示[06]:依赖注入框架设计细节
由于依赖注入具有举足轻重的作用,所以<ASP.NET Core 6框架揭秘>的绝大部分章节都会涉及这一主题.本书第3章对.NET原生的依赖注入框架的设计和实现进行了系统的介绍,其中设计一些 ...