集成学习方法:
建立几个模型来解决单一的预测问题,它的原理是生成多个estimator,各自独立的学习和做出预测,这些预测最后结合成单测,因此由于任何一个模型
随机森林就是用集成学习的方法建立多个决策树,最后采用VOTE的方式输出最后的结果
随机森林建立多个决策树过程
-
单个树建立:
1 随机在n个样本中选择一个样本,重复n次,样本可能重复
2 随机在M个特征中选择m个特征(M>m) -
建立十颗决策树,样本特征大多不一样
随机森林API:sklearn.ensemble.RandomForestClassifier()
参数:n_estimators=10森林中树的数量,默认10,常用120,200,300,500,800,1200
criterion="gini"默认划分依据是基尼系数
max_depth=None
max_feature每个决策树最大特征数量
代码如下:
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
def rfc():
titannic = pd.read_csv("./titannic.txt")
x = titannic[["pclass", "age", "sex"]]
y = titannic["survived"]
x["age"].fillna(x["age"].mean(), inplace=True)
# 特征工程
dict = DictVectorizer()
x = dict.fit_transform(x.to_dict(orient="records"))
# 数据分割
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
# 建立随机森林实例
randonf = RandomForestClassifier()
# 进行网格搜索
param = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [5, 10, 20, 100]}
gs = GridSearchCV(randonf, param_grid=param, cv=10)
gs.fit(x_train, y_train)
print("交叉验证最好的验证结果是", gs.best_score_)
print("最好的参数模型是", gs.best_estimator_)
#print(dict)
if __name__ == '__main__':
rfc()
运行结果如下:
可以看出随机森林的准确率比单纯的决策树准确率要高。
总结:
- 能有效运用在大数据集上
- 能处理高维特征样本不需要降维
- 能够评估各个特征在分类问题上的重要性
@author :specyue@mail.ustc.edu.cn 欢迎交流