随机森林(Random Forest)是一种基于决策树的集成学习算法。它的基本思想是将多个决策树进行组合,通过投票或者取平均值等方式来获得最终的结果。在构建每一个决策树的过程中,随机森林采用了自助采样法(bootstrap sampling)和随机选取特征值(feature randomization)的方法,增加了模型的多样性和减小了模型的方差,从而提高了模型的泛化能力。随机森林广泛应用于分类和回归问题中,其优点包括:对于高维稀疏数据和缺失数据具有很好的适应能力,同时能够处理非线性的关系和交互效应,还能对特征的重要性进行排名。
废话不多说
直接上代码
利用随机森林算法进行分类,对比并分析ID3算法与随机森林算法的区别;
from sklearn.datasets import load_iris,load_breast_cancer
data=load_breast_cancer()
dir(data)
x=data.data
y=data.target
print(x.shape,data.feature_names,data.target_names)
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=888)
print(X_train.shape,X_test.shape)
clf=DecisionTreeClassifier(criterion='entropy' ,random_state=888)
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
from sklearn import tree
print(tree.export_text(clf))
import matplotlib.pyplot as plt
fig,ax=plt.subplots(figsize=(10,10))
tree.plot_tree(clf ,feature_names=data.feature_names,class_names=data.target_names,filled=True)
from sklearn.ensemble import RandomForestClassifier
help(RandomForestClassifier)
#加载并利用随机森林进行训练,标准选择为entropy,约两行代码
#模型训练
forest = RandomForestClassifier(criterion='entropy')
forest.fit(X_train,y_train)
#评估模型性能,约一行代码
#模型评估
score = forest.score(X_test,y_test)
print(score) #这里的score代表的acc,精确率
from sklearn.model_selection import GridSearchCV
help(GridSearchCV)
#利用网格搜索实现参数寻优,约两行
new_params = {
"n_estimators": range(30,50),
"max_depth":[7,9,10]
}
forest = RandomForestClassifier(criterion='entropy',random_state=888)
grid_cv = GridSearchCV(forest,new_params)
grid_cv.fit(X_train,y_train)
print('Best params:\n')
print(grid_cv.best_params_, '\n')
#在网格搜索得到的最佳模型上测试当前模型性能
grid_cv.best_estimator_.score(X_test,y_test)
import_level=grid_cv.best_estimator_.feature_importances_
#特征筛选
print(import_level)
import numpy as np
import pandas as pd
#特征筛选排序
# 特征程度的显示
x_columns = np.array(data.feature_names)
print(type(x_columns),type(import_level))
print(import_level,x_columns)
# 利用pandas进行数据特征重要性的排序
feature_import_name=np.concatenate((x_columns.reshape(X_test.shape[1],1),import_level.reshape(X_test.shape[1],1)),axis=1)
print(feature_import_name.shape)
help(np.concatenate)
pd_c=pd.DataFrame(feature_import_name,columns=['name','values'])
print(pd_c.head())
pd_c.sort_values(by = 'values',axis=0,ascending = False)
from sklearn.ensemble import AdaBoostClassifier
adaboost = AdaBoostClassifier(random_state=888)
adaboost = adaboost.fit(X_train,y_train)
score = adaboost.score(X_test,y_test)
print(score)
我在这里用的是Anconda里面的JupyterLab
会出现概率的分析结果