当前位置:网站首页>决策树与随机森林学习笔记(1)
决策树与随机森林学习笔记(1)
2022-07-28 02:20:00 【羊咩咩咩咩咩】
一,决策树
决策树是用于解决回归或者分类功能的一个机器学习模型,决策树也是随机森林的一个重要组成部分。决策树有三种算法:ID3,C4.5,CART算法,对于ID3来说,决定其判断的是信息增益,C4.5的判断条件是信息增益比,而CART是通过判断基尼系数来进行构建决策树。
在决策树中还存在剪枝问题,这个问题的主要目的是解决模型过拟合而产生的。第一种是决策树一般的剪枝,他是通过计算每一个节点得经验熵,然后通过比较叶子结点的损失函数与去除叶子节点后其父节点的损失函数,如果损失函数减小,则剪枝,否则保留。第二种是CART剪枝,他是通过计算只有一个根节点时的损失函数与完全的树时候的损失函数,由于都存在惩罚项a,所以在这两s式相等时,可以求出一个最优解a,然后通过计算各节点的损失函数值,若比其大,则减去,比起小,则保留。
构建决策树,决策树来自sklearn.tree.DecisionTreeClassifier,通过鸢尾花的数据集进行测试
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris =load_iris()
X =iris.data[:,2:]
y = iris.target
tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X,y)可以通过以下代码进行决策树可视化。
from sklearn.tree import export_graphviz
export_graphviz(tree_clf,
out_file=os.path.join(IMAGES_PATH, "iris_tree.dot"),
feature_names=iris.feature_names[2:],
class_names =iris.target_names,
rounded=True,
filled=True)可以通过accuracy_score来判断正确率,也可以通过计算mse值查看损失函数大小。
from sklearn.metrics import accuracy_score
y_pred = tree_clf.predict(x_test)
accuracy_score(y_pred,y_test)
from sklearn.metrics import mean_squared_error
mean_squared_error(y_test,y_pred)也可以通过predict_proba来计算可能性
tree_clf.predict_proba([[5,1.5]])![]()
实例1:为卫星数据训练集训练并微调一个决策树模型
##读取数据
from sklearn.datasets import make_moons
data =make_moons(n_samples=10000,noise=0.4)
##区分训练集与测试集
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(data[0],data[1],random_state=42,test_size=0.3)
##通过网格化搜索优化参数
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
model =DecisionTreeClassifier()
params = {'max_leaf_nodes':[2,3,4,5,6,7,8,9]}
gridsearchcv = GridSearchCV(model,params,cv=3)
gridsearchcv.fit(x_train,y_train).best_params_
##判断决策树模型的正确率
from sklearn.metrics import accuracy_score
y_pred = gridsearchcv.predict(x_test)
accuracy_score(y_pred,y_test)二,随机森林与集成学习
集成学习是通过聚合一组预测器的预测,得到的预测结果优于当个预测器的结果。
我们可以通过建立一个投票器来进行证明,首先,投票分为硬投票与软投票,硬投票是指多数服从少数,软投票是指通每一个预测器的可能性进行求平均,比较后判断。
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
log_clf = LogisticRegression()
rnd_clf = RandomForestClassifier()
svm_clf = SVC()
voting_clf = VotingClassifier(estimators=[('log_clf',log_clf),('rnd_clf',rnd_clf),('svm_clf',svm_clf)],voting='hard')
voting_clf.fit(x_train,y_train)
from sklearn.metrics import accuracy_score
for clf in (log_clf,rnd_clf,svm_clf,voting_clf):
clf.fit(x_train,y_train)
y_pred = clf.predict(x_test)
print(clf.__class__.__name__,accuracy_score(y_test,y_pred))
可以看出集成学习基本上优于单个预测器。
集成学习分为bagging算法与pasting算法,两者区别是前者是取样放回,而后者为取样不放回。
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
bag_clf = BaggingClassifier(DecisionTreeClassifier(),n_estimators=500,max_samples=100,bootstrap=True,n_jobs=-1)
bag_clf.fit(x_train,y_train)
y_pred = bag_clf.predict(x_test)
accuracy_score(y_pred,y_test)当bootstrap=False时,是pasting算法。
这里我们可以发现一个问题:当我们在取样放回时,我们在训练模型过程中一定会遗漏一些数据,我们将这些数据称之为外包(oob),我们可以通过oob_score_来用未参与训练的数据进行实例预测,并得到一个评估分数。最后可以通过oob_decision_function_来显示实例可能性。
bag_clf = BaggingClassifier(
DecisionTreeClassifier(),n_estimators=500,max_samples=100,oob_score=True,n_jobs=-1,bootstrap=True)
bag_clf.fit(x_train,y_train)
bag_clf.oob_score_##使用未被采用的数据来进行评估模型
from sklearn.metrics import accuracy_score
y_pred = bag_clf.predict(x_test)
accuracy_score(y_test,y_pred)
bag_clf.oob_decision_function_随机森林是集成学习的一种,它本质上是决策树的集成。可以通过bagging来模拟,也可以用RandomForestClassifier来建立。
from sklearn.ensemble import RandomForestClassifier
rnd_clf = RandomForestClassifier(n_estimators=500,max_leaf_nodes=16,n_jobs=-1)
rnd_clf.fit(x_train,y_train)
y_pred_rf = rnd_clf.predict(x_test)
accuracy_score(y_pred_rf,y_test)
bag_clf =BaggingClassifier(DecisionTreeClassifier(splitter='random',max_leaf_nodes=16),
n_estimators=500,max_samples=1.0,bootstrap=True,n_jobs=-1)
bag_clf.fit(x_train,y_train)
y_pred_bag = bag_clf.predict(x_test)
accuracy_score(y_pred_rf,y_test)随机森林的另一个重要的用处,可以计算特征的重要性。可以通过feature_importance_计算每一个特征的重要性。
from sklearn.datasets import load_iris
iris = load_iris()
rnd_clf =RandomForestClassifier(n_estimators=500,n_jobs=-1)
rnd_clf.fit(iris['data'],iris['target'])
for name,score in zip(iris['feature_names'],rnd_clf.feature_importances_):
print(name,score)
从上图可以发现,sepal的length与width重要性不是那么大。
边栏推荐
- Superparameter adjustment and experiment - training depth neural network | pytorch series (26)
- els 定时器
- MySQL index learning
- There is no way to predict the rise and fall of tomorrow
- Qt官方示例:Fridge Magnets Example(冰箱贴)
- els 键盘信息
- How to authenticate Youxuan database client
- 意外收获史诗级分布式资源,从基础到进阶都干货满满,大佬就是强!
- Selenium+pytest+allure comprehensive exercise
- 嵌入式分享合集22
猜你喜欢

Qt官方示例:Fridge Magnets Example(冰箱贴)

43.js -- scope chain

数据湖:海量日志采集引擎Flume

四、固态硬盘存储技术的分析(论文)

Day 19 of leetcode

Which of the four solutions of distributed session do you think is the best?

The test post changes jobs repeatedly, jumping and jumping, and then it disappears

蓝桥杯原题

42.js -- precompiled

CNN training cycle reconstruction - hyperparametric test | pytorch series (XXVIII)
随机推荐
Intelligent industrial design software company Tianfu C round financing of hundreds of millions of yuan
阿憨的故事
mysql 随笔
[QNX Hypervisor 2.2用户手册]9.10 pass
Consolidate the data foundation in the data center
Data Lake: each module component
Opengauss source code, what ide tools are used to manage, edit and debug?
Is it you who are not suitable for learning programming?
Is it safe to buy funds on Alipay? I want to make a fixed investment in the fund
意外收获史诗级分布式资源,从基础到进阶都干货满满,大佬就是强!
Which of the four solutions of distributed session do you think is the best?
一次跨域问题的记录
"29 years old, general function test, how do I get five offers in a week?"
ROS的调试经验
写英文IEEE论文的技巧
树莓派开发继电器控制灯
基于c8t6芯片开发RC522模块实现呼吸灯
[stream] basic knowledge of stream
Qt官方示例:Fridge Magnets Example(冰箱贴)
MySQL essay