python分类分析--随机森林原理及案例

随机森林

1、什么是集成学习方法

集成学习通过建立几个板型组合的来解决单一预测问题,它的工作原理是生成多个分类器/模型,各独立地学习和作出预测。这些预测最后结合成组合预测,因此优于任何一个单分类的做出预测。决策树过度拟合可以用剪枝或者集成学习方法的随机森林实现。

2、什么是随机森林

在机器学习中,随机森林是一个包含多个决策树的分类器,并且其输出的类别是由多个决策树输出的类别的众数而定。例如,如果你训练了5个树,其中有4个树的结果是True,1个树的结果是False,那么最终投票结果就是True。
随机:
森林:包含多个决策树的分类器

3、随机森林的原理过程

随机:特值随机,训练集随机
随机森林算法根据下列算法而建造每棵树:
·用N来表示训练用例(样本)的个数,M表示特征数目。
    。1、一次随机选出一个样本,重红N次。《随机有放回的抽取,有可能出现重复的样本)
    。2、随机去选出m个特征,m << M,建立决策制,每棵树有m个特征。
·采取bootstrap抽样 《随机有放回的抽样》   

4、为什么采取bootstrap抽样

为什么要随机推样训练?

  • 如果不进行随机抽样,每棵树的训练集都一样,那么最终训练出的树分类结果也一样

为什么要有放回地抽样?

  • 如果不是有放回的抽样,那么每棵树的训练样本都是不同的,都是没有交集的,也就是说每棵树训练出来都是有很大的差异的;而随机森林最后分类取决于多棵树(弱分类器》的投票表决。

5、python实现随机森林的接口

· class sklearn.ensemble.RandomForestClassifier(n_estimators=10,criterion='gini',max_depth=None,bootstrap=True,random_state=None,min_samples_split=2)

随机森林分类器参数解释:

。n_estimators:integer,optional(default=10)森林里的树木数量100,150,300,...
。criteria:string,可选(default="gini")分割特征的测量方法"entropy"、"gini"
。max_depth:integer或None,可选(默认=无)树的最大深度5,8,15,25,30
。max_features="auto”,每个决策树的量大特征数量
    ·If"auto",then max_features=sqrt(n_features).
    ·If"sqrt",then max_features=sqrt(n features)(same as"auto").
    ·If"log2",then max_features=log2(n_features).
    ·If None,then max_features = n_features.
。bootstrap:boolean,optional(default=True)是否在构建树时使用放回抽样\
。min_samples_split:节点划分最少样本数
。min_samples_leaf:叶子节点的最小样本数

·其中超参数有:n_estimator,max_depth,min_samples_split,min_samples_leaf

6、应用总结

在当前所有分类算法中,具有极好的准确率

能够有效地运行在大数据集上,处理具有高维特征的输入样本,而且不需要降维

能够评估各个特征在分类问题上的重要性

7、案例:随机森林对泰坦尼克号乘客的生存进行预测

import pandas as pd

'''1 获取数据'''
path = "http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt"
titanic = pd.read_csv(path)
row.names pclass survived name age embarked home.dest room ticket boat sex
0 1 1st 1 Allen, Miss Elisabeth Walton 29.0000 Southampton St Louis, MO B-5 24160 L221 2 female
1 2 1st 0 Allison, Miss Helen Loraine 2.0000 Southampton Montreal, PQ / Chesterville, ON C26 NaN NaN female
2 3 1st 0 Allison, Mr Hudson Joshua Creighton 30.0000 Southampton Montreal, PQ / Chesterville, ON C26 NaN (135) male
3 4 1st 0 Allison, Mrs Hudson J.C. (Bessie Waldo Daniels) 25.0000 Southampton Montreal, PQ / Chesterville, ON C26 NaN NaN female
4 5 1st 1 Allison, Master Hudson Trevor 0.9167 Southampton Montreal, PQ / Chesterville, ON C22 NaN 11 male
display(titanic.head(3))
# 解释数据
#字段: row.names  	pclass  	survived	name	age	embarked	home.dest	room	ticket	boat	sex
#解释:人员编号    人员等级划分  是否幸存    名字  年龄  上传地点  家庭地址  所在船舱  船票 boat(我也不知道怎么解释)  性别

# 筛选特征值和目标值
x = titanic[["pclass", "age", "sex","embarked","home.dest","room"]]
y = titanic["survived"]
row.names pclass survived name age embarked home.dest room ticket boat sex
0 1 1st 1 Allen, Miss Elisabeth Walton 29.0 Southampton St Louis, MO B-5 24160 L221 2 female
1 2 1st 0 Allison, Miss Helen Loraine 2.0 Southampton Montreal, PQ / Chesterville, ON C26 NaN NaN female
2 3 1st 0 Allison, Mr Hudson Joshua Creighton 30.0 Southampton Montreal, PQ / Chesterville, ON C26 NaN (135) male
'''2 数据预处理'''
x.info() #发现缺失值,
#root变量缺失值太多,不具备解释性,删除。
x = x.drop("room", inplace=False, axis=1)   #删除room列
#age变量缺失值,用均值代替
x["age"] = x["age"].fillna(x["age"].mean(), inplace=False)
#embarked 、home.dest 缺失,使用上一个人的向下填充
x = x.fillna(method="ffill",inplace=False)
#home.dest 缺失值用向上填充
display(x.head(3))


RangeIndex: 1313 entries, 0 to 1312
Data columns (total 6 columns):
pclass 1313 non-null object
age 633 non-null float64
sex 1313 non-null object
embarked 821 non-null object
home.dest 754 non-null object
room 77 non-null object
dtypes: float64(1), object(5)
memory usage: 61.6+ KB

pclass age sex embarked home.dest
0 1st 29.0 female Southampton St Louis, MO
1 1st 2.0 female Southampton Montreal, PQ / Chesterville, ON
2 1st 30.0 male Southampton Montreal, PQ / Chesterville, ON
x.info() #发现缺失值


RangeIndex: 1313 entries, 0 to 1312
Data columns (total 5 columns):
pclass 1313 non-null object
age 1313 non-null float64
sex 1313 non-null object
embarked 1313 non-null object
home.dest 1313 non-null object
dtypes: float64(1), object(4)
memory usage: 51.4+ KB

'''3 特征工程'''
# 1) 转换成字典
x = x.to_dict(orient="records")
# print(x)

# 2、数据集划分
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=11)
# display(x_train)

# 3、字典特征抽取
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier, export_graphviz
transfer = DictVectorizer(sparse=False)
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# print(transfer.get_feature_names()) #返回类别名称
# print(x_train)
'''4 模型预估器'''
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
estimator = RandomForestClassifier()
# 加入网格搜索与交叉验证
# 参数准备
param_dict = {"n_estimators": [100,120,200,300,500,800], "max_depth": [3,5,8,10,15], "max_features":["auto","log2"]}
estimator = GridSearchCV(estimator, param_grid=param_dict, cv=3)
estimator.fit(x_train, y_train)

GridSearchCV(cv=3, error_score=‘raise’,
estimator=RandomForestClassifier(bootstrap=True, class_weight=None, criterion=‘gini’,
max_depth=None, max_features=‘auto’, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False),
fit_params=None, iid=True, n_jobs=1,
param_grid={‘n_estimators’: [100, 120, 200, 300, 500, 800], ‘max_depth’: [3, 5, 8, 10, 15], ‘max_features’: [‘auto’, ‘log2’]},
pre_dispatch=‘2*n_jobs’, refit=True, return_train_score=‘warn’,
scoring=None, verbose=0)

'''5 模型评估'''
# 方法1:直接比对真实值和预测值
y_predict = estimator.predict(x_test)
print("y_predict:\n", y_predict)
#print("直接比对真实值和预测值:\n", y_test == y_predict)

# 方法2:计算准确率
score = estimator.score(x_test, y_test)
print("准确率为:\n", score)

# 最佳参数:best_params_
print("最佳参数:\n", estimator.best_params_)
# 最佳结果:best_score_
print("最佳结果:\n", estimator.best_score_)
# 最佳估计器:best_estimator_
print("最佳估计器:\n", estimator.best_estimator_)
# 交叉验证结果:cv_results_
#print("交叉验证结果:\n", estimator.cv_results_)    transfer.get_feature_names()

y_predict:
[0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0
1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 1 0 1 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 1 1 0 0 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 0 0 1 0 1 1 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1
1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0]
准确率为:
0.8206686930091185
最佳参数:
{‘max_depth’: 15, ‘max_features’: ‘auto’, ‘n_estimators’: 200}
最佳结果:
0.8262195121951219
最佳估计器:
RandomForestClassifier(bootstrap=True, class_weight=None, criterion=‘gini’,
max_depth=15, max_features=‘auto’, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)

你可能感兴趣的:(python机器学习)