XGBoost学习笔记(2)

1. 分类回归树
Classification And Regression Tree(CART),一个用于监督学习的非参数模型。
二分递归分割:将当前样本集合划分为两个子样本集合,使得生成的每个非叶子结点都有两个分支。
树模型很容易过拟合,所以很多策略都是防止过拟合的,如提前终止、剪枝、Bagging…
1.1 CART算法只要分为两个步骤:
(1)将样本递归划分进行建树
令节点的样本集合为D,对候选分裂θ=(j, tm),选择特征j,分裂阈值为tm,将样本分裂为两个分支:
在这里插入图片描述
分裂原则:分裂后的两个分支样本越纯净越好
在这里插入图片描述
对于回归问题:
集合D的不纯净性为集合中样本的y值的差异在这里插入图片描述
其中,在这里插入图片描述
集合中样本的y值越接近越纯净,相当于损失函数取L2损失,选择最小L2损失的分裂在这里插入图片描述
对于分类问题:
分布的估计值取在这里插入图片描述
在这里插入图片描述
建树停止条件
在这里插入图片描述
(2)用验证数据进行剪枝
在这里插入图片描述
1.2 scikit-learn实现
分类树:DecisionTreeClassifier
回归树:DecisionTreeRegressor
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
2. 随机森林
回归树算法的缺点之一是高方差,降低算法方差的方式是平均多个模型的预测:Bagging(Bootstrap aggregating)
在这里插入图片描述
在这里插入图片描述
练习
蘑菇数据集,直接采用Kaggle竞赛中22维特征
代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import cross_val_score
from sklearn import metrics
from sklearn.metrics import accuracy_score

dpath = './data/'
data = pd.read_csv(dpath + 'mushrooms.csv')

# 将文本内容量化成数字
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
for col in data.columns:
    data[col] = labelencoder.fit_transform(data[col])

X = data.iloc[:, 1:23]#除label外的所有特征
y = data.iloc[:, 0]#label
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=4)
#逻辑回归
from sklearn.linear_model import LogisticRegression
model_LR = LogisticRegression()
model_LR.fit(X_train,y_train)
#测试
y_prob = model_LR.predict_proba(X_test)[:,1]
y_pred = np.where(y_prob > 0.5, 1, 0)#大于0.51,小于0.50
model_LR.score(X_test, y_pred)
auc_roc = metrics.roc_auc_score(y_test, y_pred)

from sklearn.model_selection import GridSearchCV
LR_model = LogisticRegression()
tuned_parameters = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000] ,
                    'penalty':['l1','l2']
                   }
LR = GridSearchCV(LR_model, tuned_parameters, cv=10)
LR.fit(X_train,y_train)

# 决策树模型
from sklearn.tree import DecisionTreeClassifier
model_DD = DecisionTreeClassifier()
tuned_parameters = {
'max_features':['auto', 'sqrt', 'log2'], 'min_samples_leaf':range(1,100,1), 'max_depth':range(1,50,1)    
}
#If “auto”, then max_features=sqrt(n_features).
DD = GridSearchCV(model_DD, tuned_parameters,cv=10)
DD.fit(X_train, y_train)

#随机森林
from sklearn.ensemble import RandomForestClassifier
model_RR = RandomForestClassifier()
tuned_parameters = {
    'min_samples_leaf':range(10,100,10), 'n_estimators':range(10,100,10), 'max_features':['auto', 'sqrt', 'log2']
}
RR = GridSearchCV(model_RR, tuned_parameters,cv=10)
RR.fit(X_train,y_train)
#XGBoost
from xgboost import XGBClassifier
model_XGB = XGBClassifier()
model_XGB.fit(X_train, y_train)
#在XGBoost中特征重要性已经自动算好,存放在featureimportances中
print(model_XGB.feture_importances_)
#在XGBoost中特征重要性已经自动算好,存放在featureimportances中
print(model_XGB.feature_importances_)
# 按特征顺序打印重要性
import matplotlib.pyplot as plt
plt.bar(range(len(model_XGB.feature_importances_)), model_XGB.feature_importances_)
plt.show()
# 使用XGBoost内嵌的函数,按特征重要性排序
from xgboost import plot_importance
plot_importance(model_XGB)
plt.show()

# 根据特征重要性进行特征选择
from numpy import sort
from sklearn.feature_selection import SelectFromModel
thresholds = sort(model_XGB.feature_importances_)
for thresh in thresholds:
    selection = SelectFromModel(model_XGB, threshold=thresh, prefit=True)
    select_X_train = selection.transform(X_train)
    selection_model = XGBClassifier()
    selection_model.fit(select_X_train, y_train)
    select_X_test = selection.transform(X_test)
    y_pred = selection_model.predict(select_X_test)
    predictions = [round(value) for value in y_pred]
    accuracy = accuracy_score(y_test, predictions)
    print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (thresh, select_X_train.shape[1], accuracy*100.0))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言是一种广泛使用的编程语言,它具有高效、灵活、可移植性强等特点,被广泛应用于操作系统、嵌入式系统、数据库、编译器等领域的开发。C语言的基本语法包括变量、数据类型、运算符、控制结构(如if语句、循环语句等)、函数、指针等。在编写C程序时,需要注意变量的声明和定义、指针的使用、内存的分配与释放等问题。C语言中常用的数据结构包括: 1. 数组:一种存储同类型数据的结构,可以进行索引访问和修改。 2. 链表:一种存储不同类型数据的结构,每个节点包含数据和指向下一个节点的指针。 3. 栈:一种后进先出(LIFO)的数据结构,可以通过压入(push)和弹出(pop)操作进行数据的存储和取出。 4. 队列:一种先进先出(FIFO)的数据结构,可以通过入队(enqueue)和出队(dequeue)操作进行数据的存储和取出。 5. 树:一种存储具有父子关系的数据结构,可以通过中序遍历、前序遍历和后序遍历等方式进行数据的访问和修改。 6. 图:一种存储具有节点和边关系的数据结构,可以通过广度优先搜索、深度优先搜索等方式进行数据的访问和修改。 这些数据结构在C语言中都有相应的实现方式,可以应用于各种不同的场景。C语言中的各种数据结构都有其优缺点,下面列举一些常见的数据结构的优缺点: 数组: 优点:访问和修改元素的速度非常快,适用于需要频繁读取和修改数据的场合。 缺点:数组的长度是固定的,不适合存储大小不固定的动态数据,另外数组在内存中是连续分配的,当数组较大时可能会导致内存碎片化。 链表: 优点:可以方便地插入和删除元素,适用于需要频繁插入和删除数据的场合。 缺点:访问和修改元素的速度相对较慢,因为需要遍历链表找到指定的节点。 栈: 优点:后进先出(LIFO)的特性使得栈在处理递归和括号匹配等问题时非常方便。 缺点:栈的空间有限,当数据量较大时可能会导致栈溢出。 队列: 优点:先进先出(FIFO)的特性使得

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值