【无标题】天池机器学习task3

一、介绍
LightGBM是2017年由微软推出的可扩展机器学习系统,是微软旗下DMKT的一个开源项目,由2014年首届阿里巴巴大数据竞赛获胜者之一柯国霖老师带领开发。它是一款基于GBDT(梯度提升决策树)算法的分布式梯度提升框架,为了满足缩短模型计算时间的需求,LightGBM的设计思路主要集中在减小数据对内存与计算性能的使用,以及减少多机器并行计算时的通讯代价。
LightGBM的主要优点:
简单易用。提供了主流的Python\C++\R语言接口,用户可以轻松使用LightGBM建模并获得相当不错的效果。
高效可扩展。在处理大规模数据集时高效迅速、高准确度,对内存等硬件资源要求不高。
鲁棒性强。相较于深度学习模型不需要精细调参便能取得近似的效果。
LightGBM直接支持缺失值与类别特征,无需对数据额外进行特殊处理
LightGBM的主要缺点:
相对于深度学习模型无法对时空位置建模,不能很好地捕获图像、语音、文本等高维数据。
在拥有海量训练数据,并能找到合适的深度学习模型时,深度学习的精度可以遥遥领先LightGBM。
LightGBM的应用:
机器学习和数据挖掘领域,同时,LightGBM还被成功应用在工业界与学术界的各种问题中。例如金融风控、购买行为识别、交通流量预测、环境声音分类、基因分类、生物成分分析等诸多领域。虽然领域相关的数据分析和特性工程在这些解决方案中也发挥了重要作用,但学习者与实践者对LightGBM的一致选择表明了这一软件包的影响力与重要性。
二、实践:
● Step1: 库函数导入● Step2: 数据读取/载入● Step3: 数据信息简单查看● Step4: 可视化描述● Step5: 利用 LightGBM 进行训练与预测● Step6: 利用 LightGBM 进行特征选择● Step7: 通过调整参数获得更好的效果
基本函数库:
numpy (Python进行科学计算的基础软件包)
pandas(pandas是一种快速,强大,灵活且易于使用的开源数据分析和处理工具)
matplotlib和seaborn绘图
数据下载 :
#下载需要用到的数据集
!wget https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/8LightGBM/high_diamond_ranked_10min.csv
● Step1: 库函数导入

基础函数库
import numpy as np
import pandas as pd

绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns

● Step2: 数据读取/载入

我们利用Pandas自带的read_csv函数读取并转化为DataFrame格式
df = pd.read_csv(’./high_diamond_ranked_10min.csv’)
y = df.blueWins

● Step3: 数据信息简单查看

利用.info()查看数据的整体信息
df.info()

进行简单的数据查看,我们可以利用 .head() 头部.tail()尾部
df.head()

df.tail()

标注标签并利用value_counts函数查看训练集标签的数量
y = df.blueWins
y.value_counts()

数据集正负标签数量基本相同,不存在数据不平衡的问题。
标注特征列
drop_cols = [‘gameId’,‘blueWins’]
x = df.drop(drop_cols, axis=1)

对于特征进行一些统计描述
x.describe()

根据上面的描述,我们可以去除一些重复变量,比如只要知道蓝队是否拿到一血,我们就知道红队有没有拿到,可以去除红队的相关冗余数据。
drop_cols = [‘redFirstBlood’,‘redKills’,‘redDeaths’
,‘redGoldDiff’,‘redExperienceDiff’, ‘blueCSPerMin’,
‘blueGoldPerMin’,‘redCSPerMin’,‘redGoldPerMin’]
x.drop(drop_cols, axis=1, inplace=True)

● Step4: 可视化描述
data = x
data_std = (data - data.mean()) / data.std()

data.mean(axis=0) 输出矩阵为一行,求每列的平均值,同理data.mean(axis=1) 输出矩阵为一列,求每行的平均值
data.std(axis=0) 输出矩阵为一列,求每列的标准差,同理data.std(axis=1) 输出矩阵为一列,求每行的标准差
#标准差也成为标准偏差,表示数据的离散程度,和标准差大小成反比
data = pd.concat([y, data_std.iloc[:, 0:9]], axis=1)

concat函数是在pandas底下的方法,可以将数据根据不同的轴作简单的融合;
iloc[]是取几行,例如,iloc[:5],取前5行
loc[]是取到第几行,例如,loc["left],表示按顺序,取到 left 这一行。
data = pd.melt(data, id_vars=‘blueWins’, var_name=‘Features’, value_name=‘Values’)

数据分析的时候经常要把宽数据—>>长数据
fig, ax = plt.subplots(1,2,figsize=(15,5))

ax=plt.subplots(m,n,figsize=(a,b)) 画出mn个字图size为ab,fig为图片变量,ax为m*n的坐标变量(数组),分别指向相应生成字图的坐标
绘制小提琴图
sns.violinplot(x=‘Features’, y=‘Values’, hue=‘blueWins’, data=data, split=True,
inner=‘quart’, ax=ax[0], palette=‘Blues’)
fig.autofmt_xdate(rotation=45)

data = x
data_std = (data - data.mean()) / data.std()
data = pd.concat([y, data_std.iloc[:, 9:18]], axis=1)
data = pd.melt(data, id_vars=‘blueWins’, var_name=‘Features’, value_name=‘Values’)

绘制小提琴图
sns.violinplot(x=‘Features’, y=‘Values’, hue=‘blueWins’,
data=data, split=True, inner=‘quart’, ax=ax[1], palette=‘Blues’)
fig.autofmt_xdate(rotation=45)

plt.show()

‘’’
小提琴图 (Violin Plot)是用来展示多组数据的分布状态以及概率密度。这种图表结合了箱形图和密度图的特征,主要用来显示数据的分布形状。
从图中我们可以看出:
击杀英雄数量越多更容易赢,死亡数量越多越容易输(bluekills与bluedeaths左右的区别)。
助攻数量与击杀英雄数量形成的图形状类似,说明他们对游戏结果的影响差不多。
一血的取得情况与获胜有正相关,但是相关性不如击杀英雄数量明显。
经济差与经验差对于游戏胜负的影响较小。
击杀野怪数量对游戏胜负的影响并不大。
同时我们画出各个特征之间的相关性热力图,颜色越深代表特征之间相关性越强,我们剔除那些相关性较强的冗余特征。
‘’’
##热度图
plt.figure(figsize=(18,14))
sns.heatmap(round(x.corr(),2), cmap=‘Blues’, annot=True)
plt.show()

同时我们画出各个特征之间的相关性热力图,颜色越深代表特征之间相关性越强,我们剔除那些相关性较强的冗余特征
去除冗余特征
drop_cols = [‘redAvgLevel’,‘blueAvgLevel’]
x.drop(drop_cols, axis=1, inplace=True)

sns.set(style=‘whitegrid’, palette=‘muted’)

构造两个新特征
x[‘wardsPlacedDiff’] = x[‘blueWardsPlaced’] - x[‘redWardsPlaced’]
x[‘wardsDestroyedDiff’] = x[‘blueWardsDestroyed’] - x[‘redWardsDestroyed’]

data = x[[‘blueWardsPlaced’,‘blueWardsDestroyed’,‘wardsPlacedDiff’,‘wardsDestroyedDiff’]].sample(1000)
data_std = (data - data.mean()) / data.std()
data = pd.concat([y, data_std], axis=1) #concat函数是在pandas底下的方法,可以将数据根据不同的轴作简单的融合
data = pd.melt(data, id_vars=‘blueWins’, var_name=‘Features’, value_name=‘Values’) #使用pandas.melt 进行行转列

plt.figure(figsize=(10,6))
sns.swarmplot(x=‘Features’, y=‘Values’, hue=‘blueWins’, data=data)

分簇散点图,简单说就是数据点不重叠的分类散点图。该函数类似于stripplot(),但该函数可以对点进行一些调整,使得数据点不重叠。
swarmplot()可以自己实现对数据分类的展现,也可以作为箱形图或小提琴图的一种补充,用来显示所有结果以及基本分布情况。
plt.xticks(rotation=45)
plt.show()

去除和眼位相关的特征
drop_cols = [‘blueWardsPlaced’,‘blueWardsDestroyed’,‘wardsPlacedDiff’,
‘wardsDestroyedDiff’,‘redWardsPlaced’,‘redWardsDestroyed’]
x.drop(drop_cols, axis=1, inplace=True)

x[‘killsDiff’] = x[‘blueKills’] - x[‘blueDeaths’]
x[‘assistsDiff’] = x[‘blueAssists’] - x[‘redAssists’]

x[[‘blueKills’,‘blueDeaths’,‘blueAssists’,‘killsDiff’,‘assistsDiff’,‘redAssists’]].hist(figsize=(12,10), bins=20)
plt.show()

data = x[[‘blueKills’,‘blueDeaths’,‘blueAssists’,‘killsDiff’,‘assistsDiff’,‘redAssists’]].sample(1000)
data_std = (data - data.mean()) / data.std()
data = pd.concat([y, data_std], axis=1)
data = pd.melt(data, id_vars=‘blueWins’, var_name=‘Features’, value_name=‘Values’)

plt.figure(figsize=(10,6))
sns.swarmplot(x=‘Features’, y=‘Values’, hue=‘blueWins’, data=data)
plt.xticks(rotation=45)

xticks就类似覆盖吧,而且覆盖的数组长度要和原来横轴的坐标长度一致
plt.show()

data = pd.concat([y, x], axis=1).sample(500)

sns.pairplot(data, vars=[‘blueKills’,‘blueDeaths’,‘blueAssists’,‘killsDiff’,‘assistsDiff’,‘redAssists’],
hue=‘blueWins’)

pairplot主要展现的是变量两两之间的关系(线性或非线性,有无较为明显的相关关系)
plt.show()

x[‘dragonsDiff’] = x[‘blueDragons’] - x[‘redDragons’]
x[‘heraldsDiff’] = x[‘blueHeralds’] - x[‘redHeralds’]
x[‘eliteDiff’] = x[‘blueEliteMonsters’] - x[‘redEliteMonsters’]

data = pd.concat([y, x], axis=1)

eliteGroup = data.groupby([‘eliteDiff’])[‘blueWins’].mean()
dragonGroup = data.groupby([‘dragonsDiff’])[‘blueWins’].mean()
heraldGroup = data.groupby([‘heraldsDiff’])[‘blueWins’].mean()

groupby分组函数:返回值:返回重构格式的DataFrame,特别注意,groupby里面的字段内的数据重构后都会变成索引
fig, ax = plt.subplots(1,3, figsize=(15,4))

eliteGroup.plot(kind=‘bar’, ax=ax[0])
dragonGroup.plot(kind=‘bar’, ax=ax[1])
heraldGroup.plot(kind=‘bar’, ax=ax[2])

print(eliteGroup)
print(dragonGroup)
print(heraldGroup)

plt.show()

x[‘towerDiff’] = x[‘blueTowersDestroyed’] - x[‘redTowersDestroyed’]

data = pd.concat([y, x], axis=1)

towerGroup = data.groupby([‘towerDiff’])[‘blueWins’]
print(towerGroup.count())
print(towerGroup.mean())

fig, ax = plt.subplots(1,2,figsize=(15,5))

towerGroup.mean().plot(kind=‘line’, ax=ax[0])
ax[0].set_title(‘Proportion of Blue Wins’)
ax[0].set_ylabel(‘Proportion’)

towerGroup.count().plot(kind=‘line’, ax=ax[1])
ax[1].set_title(‘Count of Towers Destroyed’)
ax[1].set_ylabel(‘Count’)

● Step5: 利用 LightGBM 进行训练与预测

为了正确评估模型性能,将数据划分为训练集和测试集,并在训练集上训练模型,在测试集上验证模型性能。
from sklearn.model_selection import train_test_split

选择其类别为0和1的样本 (不包括类别为2的样本)
data_target_part = y
data_features_part = x

测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size = 0.2, random_state = 2020)

导入LightGBM模型
from lightgbm.sklearn import LGBMClassifier

定义 LightGBM 模型
clf = LGBMClassifier()

在训练集上训练LightGBM模型
clf.fit(x_train, y_train)

在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics

利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print(‘The accuracy of the Logistic Regression is:’,metrics.accuracy_score(y_train,train_predict))
print(‘The accuracy of the Logistic Regression is:’,metrics.accuracy_score(y_test,test_predict))

查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print(‘The confusion matrix result:\n’,confusion_matrix_result)

利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap=‘Blues’)
plt.xlabel(‘Predicted labels’)
plt.ylabel(‘True labels’)
plt.show()

● Step6: 利用 LightGBM 进行特征选择

LightGBM的特征选择属于特征选择中的嵌入式方法,在LightGBM中可以用属性feature_importances_去查看特征的重要度。
sns.barplot(y=data_features_part.columns, x=clf.feature_importances_)

还可以使用LightGBM中的下列重要属性来评估特征的重要性。
gain:当利用特征做划分的时候的评价基尼指数
split:是以特征用到的次数来评价
from sklearn.metrics import accuracy_score
from lightgbm import plot_importance
def estimate(model,data):

#sns.barplot(data.columns,model.feature_importances_)
ax1=plot_importance(model,importance_type="gain")
ax1.set_title('gain')
ax2=plot_importance(model, importance_type="split")
ax2.set_title('split')
plt.show()

def classes(data,label,test):
model=LGBMClassifier()
model.fit(data,label)
ans=model.predict(test)
estimate(model, data)
return ans

ans=classes(x_train,y_train,x_test)
pre=accuracy_score(y_test, ans)
print(‘acc=’,accuracy_score(y_test,ans))

● Step7: 通过调整参数获得更好的效果
“”"
LightGBM中包括但不限于下列对模型影响较大的参数:
learning_rate: 有时也叫作eta,系统默认值为0.3。每一步迭代的步长,很重要。太大了运行准确率不高,太小了运行速度慢。
num_leaves:系统默认为32。这个参数控制每棵树中最大叶子节点数量。
feature_fraction:系统默认值为1。我们一般设置成0.8左右。用来控制每棵随机采样的列数的占比(每一列是一个特征)。
max_depth: 系统默认值为6,我们常用3-10之间的数字。这个值为树的最大深度。这个值是用来控制过拟合的。max_depth越大,模型学习的更加具体。
调节模型参数的方法有贪心算法、网格调参、贝叶斯调参等。这里我们采用网格调参,它的基本思想是穷举搜索:在所有候选的参数选择中,通过循环遍历,尝试每一种可能性,表现最好的参数就是最终的结果
“”"

从sklearn库中导入网格调参函数
from sklearn.model_selection import GridSearchCV

定义参数取值范围
learning_rate = [0.1, 0.3, 0.6]
feature_fraction = [0.5, 0.8, 1]
num_leaves = [16, 32, 64]
max_depth = [-1,3,5,8]

parameters = { ‘learning_rate’: learning_rate,
‘feature_fraction’:feature_fraction,
‘num_leaves’: num_leaves,
‘max_depth’: max_depth}
model = LGBMClassifier(n_estimators = 50)

进行网格搜索
clf = GridSearchCV(model, parameters, cv=3, scoring=‘accuracy’,verbose=3, n_jobs=-1)
clf = clf.fit(x_train, y_train)

clf.best_params_

在训练集和测试集上分布利用最好的模型参数进行预测
定义带参数的 LightGBM模型
clf = LGBMClassifier(feature_fraction = 0.8,
learning_rate = 0.1,
max_depth= 3,
num_leaves = 16)

在训练集上训练LightGBM模型
clf.fit(x_train, y_train)

train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print(‘The accuracy of the Logistic Regression is:’,metrics.accuracy_score(y_train,train_predict))
print(‘The accuracy of the Logistic Regression is:’,metrics.accuracy_score(y_test,test_predict))

查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print(‘The confusion matrix result:\n’,confusion_matrix_result)

利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap=‘Blues’)
plt.xlabel(‘Predicted labels’)
plt.ylabel(‘True labels’)
plt.show()

原本有306 + 245个错误,现在有 287 + 230个错误,带来了明显的正确率提升。
2.4 重要知识点
2.4.1 LightGBM的重要参数
2.4.1.1 基本参数调整
num_leaves参数 这是控制树模型复杂度的主要参数,一般的我们会使num_leaves小于(2的max_depth次方),以防止过拟合。由于LightGBM是leaf-wise建树与XGBoost的depth-wise建树方法不同,num_leaves比depth有更大的作用。、
min_data_in_leaf 这是处理过拟合问题中一个非常重要的参数. 它的值取决于训练数据的样本个树和 num_leaves参数. 将其设置的较大可以避免生成一个过深的树, 但有可能导致欠拟合. 实际应用中, 对于大数据集, 设置其为几百或几千就足够了.
max_depth 树的深度,depth 的概念在 leaf-wise 树中并没有多大作用, 因为并不存在一个从 leaves 到 depth 的合理映射。
2.4.1.2 针对训练速度的参数调整
通过设置 bagging_fraction 和 bagging_freq 参数来使用 bagging 方法。
通过设置 feature_fraction 参数来使用特征的子抽样。
选择较小的 max_bin 参数。
使用 save_binary 在未来的学习过程对数据加载进行加速。
2.4.1.3 针对准确率的参数调整
使用较大的 max_bin (学习速度可能变慢)
使用较小的 learning_rate 和较大的 num_iterations
使用较大的 num_leaves (可能导致过拟合)
使用更大的训练数据
尝试 dart 模式

2.4.1.4 针对过拟合的参数调整
使用较小的 max_bin
使用较小的 num_leaves
使用 min_data_in_leaf 和 min_sum_hessian_in_leaf
通过设置 bagging_fraction 和 bagging_freq 来使用 bagging
通过设置 feature_fraction 来使用特征子抽样
使用更大的训练数据
使用 lambda_l1, lambda_l2 和 min_gain_to_split 来使用正则
尝试 max_depth 来避免生成过深的树

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值