随机森林

随机森林定义

随机森林(Random Forest,简称RF),是在以决策树为基础学习器构建Bagging集成的基础上引入了随机属性选择。即由许多决策树随机构成,其中每棵决策树之间没有关联。当新样本输入时,由森林中的每个决策树进行分析判断,最后该样本属于选择最多的那一类。

随机森林的优点

1、随机森林简单,容易实现,计算开销小。

2、随机森林在数据集上表现良好。

3、随机森林的随机性,使得随机森林不容易陷入过拟合,具有很好的抗噪声能力。

4、随机森林能够处理高维度的数据,且不用进行特征选择。

5、既能处理离散型数据,也能处理连续型数据。

随机森林算法

随机森林算法是Bagging算法的进化版。随机森林基于决策树通过随机选择结点上的部分特征,从中选择一个最优的特征来做决策树的左右划分。

       输入为样本集D={(x,y1),(x2,y2),…(xm,ym)}D={(x,y1),(x2,y2),…(xm,ym)},弱分类器迭代次数T。

       输出为最终的强分类器f(x)

实例操作

本部分主要介绍了随机森林在python语言中的实现过程。本次实验采用了坦泰尼克号乘客是否存活数据集, 目的通过数据集中给出的一些基本特性,应用到模型中,看看模型的准确性如何。

案例主要涉及以下六个小部分:

随机森林 python代码 入门 随机森林案例python_随机森林 数据集介绍

随机森林 python代码 入门 随机森林案例python_随机森林 导入数据

随机森林 python代码 入门 随机森林案例python_随机森林 数据探索与预处理

随机森林 python代码 入门 随机森林案例python_随机森林 随机森林建模

数据集介绍

      泰坦尼克号的沉没是历史上最臭名昭著的沉船之一。1912年4月15日,泰坦尼克号在首航时撞上冰山沉没,2224名乘客和船员中1502人遇难。这一耸人听闻的悲剧震惊了国际社会,并导致了对船舶更好的安全规定。这次沉船事故造成如此多人死亡的原因之一是船上没有足够的救生艇运载乘客和船员。虽然在沉船中幸存有一些运气因素,但一些群体的人比其他人更有可能幸存,比如妇女、儿童和上层阶级。我们需要的是运用机器学习的工具来预测哪些乘客在灾难中幸存下来。

变量名称

变量解释

PassengerId

乘客ID

Survived

获救情况(1为获救,0为未获救)

Pclass

乘客等级(1/2/3等舱位)

Name

乘客姓名

Sex

性别

Age

年龄

SibSp

堂兄弟/妹个数

Parch

父母与小孩个数

Ticket

船票信息

Fare

票价

Cabin

客舱

Embarked

登船港口

数据导入

训练数据集有12列891行

测试集有11列418行

# 导入模块
import pandas as pd
# 读入数据
train = pd.read_csv("F:/data/kaggle titanic/train.csv")
test = pd.read_csv("F:/data/kaggle titanic/test.csv")

数据探索与预处理

# 统计各类信息的缺失的总体情况
print(train.info(),test.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
PassengerId    891 non-null int64
Survived       891 non-null int64
Pclass         891 non-null int64
Name           891 non-null object
Sex            891 non-null object
Age            714 non-null float64
SibSp          891 non-null int64
Parch          891 non-null int64
Ticket         891 non-null object
Fare           891 non-null float64
Cabin          204 non-null object
Embarked       889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.6+ KB
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 418 entries, 0 to 417
Data columns (total 11 columns):
PassengerId    418 non-null int64
Pclass         418 non-null int64
Name           418 non-null object
Sex            418 non-null object
Age            332 non-null float64
SibSp          418 non-null int64
Parch          418 non-null int64
Ticket         418 non-null object
Fare           417 non-null float64
Cabin          91 non-null object
Embarked       418 non-null object
dtypes: float64(2), int64(4), object(5)
memory usage: 36.0+ KB
None None

其中不难看出Age,Cabin,Fare和Embarked存在缺失值。我们可以对存在缺失值的数据进行处理。

# 缺失值处理,删除无关变量
train = train.fillna(method = "bfill")
test = test.fillna(method = "pad")
train.drop(['PassengerId','Name','Ticket','Cabin'],axis=1,inplace=True)
test.drop(['PassengerId','Name','Ticket','Cabin'],axis=1,inplace=True)
# 再次统计数据
print(train.info(),test.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 8 columns):
Survived    891 non-null int64
Pclass      891 non-null int64
Sex         891 non-null object
Age         891 non-null float64
SibSp       891 non-null int64
Parch       891 non-null int64
Fare        891 non-null float64
Embarked    891 non-null object
dtypes: float64(2), int64(4), object(2)
memory usage: 55.8+ KB
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 418 entries, 0 to 417
Data columns (total 7 columns):
Pclass      418 non-null int64
Sex         418 non-null object
Age         418 non-null float64
SibSp       418 non-null int64
Parch       418 non-null int64
Fare        418 non-null float64
Embarked    418 non-null object
dtypes: float64(2), int64(3), object(2)
memory usage: 22.9+ KB
None None
# 哑变量处理
train = pd.get_dummies(train)                 
test = pd.get_dummies(test)                   

train.drop("Sex_male",axis=1,inplace=True)
test.drop("Sex_male",axis=1,inplace=True)
# 用随机森林进行分类
from sklearn.ensemble import RandomForestClassifier
x,y = train.ix[:,1:10],train.ix[:,0]
rf = RandomForestClassifier(n_estimators=22, max_depth=4)
rf.fit(x,y)
y_predict = rf.predict(test)
result = pd.DataFrame(y_predict)
result.head()



0

0

0

1

0

2

0

3

0

4

0