scikit-learn中随机森林使用详解

  最近学了一下随机森林,本来想自己总结一下,但是觉得有一篇已经很好的博客,就给大家分享,我主要讲讲scikit-learn中如何使用随机森林算法。

  scikit-learn中和随机森林算法相关的类为RangeForestClassifier,相关官方文档讲解点击这里,这个类的主要参数和方法如下:

类的构造函数为:

RandomForestClassifier(n_estimators=10,criterion=’gini’, max_depth=None,min_samples_split=2,min_samples_leaf=1,
min_weight_fraction_leaf=0.0, max_features=’auto’, max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None,
verbose=0, warm_start=False, class_weight=None)

其中构造函数的参数说明为:

参数(params):
    n_estimators:数值型取值
        森林中决策树的个数,默认是10

    criterion:字符型取值
        采用何种方法度量分裂质量,信息熵或者基尼指数,默认是基尼指数

    max_features:取值为int型, float型, string类型, or None(),默认"auto"
        寻求最佳分割时的考虑的特征数量,即特征数达到多大时进行分割。
        int:max_features等于这个intfloat:max_features是一个百分比,每(max_features * n_features)特征在每个分割出被考虑。
        "auto":max_features等于sqrt(n_features)
        "sqrt":同等于"auto""log2":max_features=log2(n_features)
        None:max_features = n_features

    max_depth:int型取值或者None,默认为None
        树的最大深度

    min_samples_split:int型取值,float型取值,默认为2
        分割内部节点所需的最少样本数量
        int:如果是int值,则就是这个intfloat:如果是float值,则为min_samples_split * n_samples

    min_samples_leaf:int取值,float取值,默认为1
        叶子节点上包含的样本最小值
        int:就是这个intfloat:min_samples_leaf * n_samples

    min_weight_fraction_leaf : float,default=0.
        能成为叶子节点的条件是:该节点对应的实例数和总样本数的比值,至少大于这个min_weight_fraction_leaf值

    max_leaf_nodes:int类型,或者None(默认None)
        最大叶子节点数,以最好的优先方式生成树,最好的节点被定义为杂质相对较少,即纯度较高的叶子节点

    min_impurity_split:float取值 
        树增长停止的阀值。一个节点将会分裂,如果他的杂质度比这个阀值;如果比这个值低,就会成为一个叶子节点。

    min_impurity_decrease:float取值,默认0.
        一个节点将会被分裂,如果分裂之后,杂质度的减少效果高于这个值。

    bootstrap:boolean类型取值,默认True
        是否采用有放回式的抽样方式

    oob_score:boolean类型取值,默认False
        是否使用袋外样本来估计该模型大概的准确率

    n_jobs:int类型取值,默认1
        拟合和预测过程中并行运用的作业数量。如果为-1,则作业数设置为处理器的core数。

    class_weight:dict, list or dicts, "balanced"
        如果没有给定这个值,那么所有类别都应该是权重1
        对于多分类问题,可以按照分类结果y的可能取值的顺序给出一个list或者dict值,用来指明各类的权重.
        "balanced"模式,使用y值自动调整权重,该模式类别权重与输入数据中的类别频率成反比,
即n_samples / (n_classes * np.bincount(y)),分布为第n个类别对应的实例数。
        "balanced_subsample"模式和"balanced"模式类似,只是它计算使用的是有放回式的取样中取得样本数,而不是总样本数

该类主要的属性为:

属性:
    estimators_:决策树列表
        拟合好的字分类器列表,也就是单个决策树

    classes_:array of shape = [n_features]
        类别标签列表

    n_classes_:int or list
        类别数量

    n_features:int
        拟合过程中使用的特征的数量

    n_outputs:int 
        拟合过程中输出的数量

    featrue_importances:特征重要程度列表
        值越大,说明越重要

    oob_score:array of shape = [n_features]
        使用oob数据集测试得到的得分数

    oob_decision_funtion_:array of shape = [n_features, n_classes]
        oob样本预测结果,每一个样本及相应结果对列表

该类主要的方法为:

方法:
    apply(X):用构造好的森林中的树对数据集X进行预测,返回每棵树预测的叶子节点。所以结果应该是二维矩阵,
行为样本第几个样本,列为每棵树预测的叶子节点。 

    decision_path(X):返回森林中的决策路径

    fit(X, y[, sample_weight]):用训练数据集(x, y)来构造森林

    get_params([deep]):获得分类器的参数

    predict(X):预测X的类别

    predict_log_proba(X):预测X的类的对数概率,和predict_proba类似,只是取了对数

    predict_proba(X):预测X的类别的概率。输入样本的预测类别概率被计算为森林中树木的平均预测类别概率。
单个树的类概率是叶中同一类的样本的比率。因为叶子节点并不是完全纯净的,它也有杂质,
不同种类所占恶比率是不一样的,但肯定有一类纯度很高。返回值是array of shape = [n_samples, n_classes]

    score(X, y[,sample_weight]):返回给定的数据集(数据集指定了类别)的预测准确度

    set_params(**params):设置决策树的参数

   分享一段本人用随机森林算法写的关于kaggle上旧金山犯罪预测的题目,使用的是Python,正确率还未知,代码如下(刚学着用scikit-learn等工具,可能代码比较粗糙,敬请谅解!):

#author = liuwei

import pandas as pd 
import numpy as np 
import joblib
from sklearn.ensemble import RandomForestClassifier


def split_single_date(date_time_):
    '''split dateTime to year, month, day, hour, minute, and nomalize'''

    #split, use space
    tmp_ = date_time_.split(' ')        
    date_, time_ = tmp_[0], tmp_[1]    

    #split date with '-'
    date_tmp_ = date_.split('-')  
    year_, month_, day_ = int(date_tmp_[0]), int(date_tmp_[1]), int(date_tmp_[2])

    #split time with ':'
    hour_tmp_ = time_.split(':')
    hour_ = int(hour_tmp_[0])

    return year_, month_, day_, hour_  


def str_to_int(values):
    '''transform str to int, only simple enumerate, use the position value in values to replace value'''

    #get all possible value
    categorys_ =pd.Categorical(values).codes

    return categorys_




#read data
train_data_ = pd.read_csv('datas/train.csv')



test_data_ = pd.read_csv('datas/test.csv')

#print('train_data:' + str(train_data_[:10]))

#######################train_datas################################

#get weekdays datas,and transform string to int
train_weekday_values_ = train_data_.DayOfWeek.values
train_weekday_ = str_to_int(train_weekday_values_)
train_weekdays_ = pd.Series(train_weekday_, name = 'weekday')

#get district datas,and transform string to int
train_district_values_ = train_data_.PdDistrict.values
train_district_ = str_to_int(train_district_values_)
train_districts_ = pd.Series(train_district_, name = 'district')

train_dates_ = train_data_.Dates.values

#map(function, list):use function  on every element in the list
train_parse_date_ = list(map(split_single_date, train_dates_))

#lambda is a way of simple function
train_years_ = pd.Series(data = map(lambda x : x[0], train_parse_date_), name = 'year')
train_months_ = pd.Series(data = map(lambda x : x[1], train_parse_date_), name = 'month')
train_days_ = pd.Series(data = map(lambda x : x[2], train_parse_date_), name = 'day')
train_hours_ = pd.Series(data = map(lambda x : x[3], train_parse_date_), name = 'hour')

#the crime type
train_categorys_ = train_data_.Category.values

#build the new train_datas, the method pd.concat's param asix is tell how to contract, when 1 is contract by column, 0 is row
train_datas_ = pd.concat([train_years_, train_months_, train_days_, train_hours_, train_weekdays_, train_districts_], axis = 1)


######################test_datas#############################
test_weekday_values_ = test_data_.DayOfWeek.values
test_weekday_ = str_to_int(test_weekday_values_)
test_weekdays_ = pd.Series(test_weekday_, name = 'weekday')

test_district_values_ = test_data_.PdDistrict.values
test_district_ = str_to_int(test_district_values_)
test_districts_ = pd.Series(test_district_, name = 'district')

test_dates_ = test_data_.Dates.values

test_parse_date_ = list(map(split_single_date, test_dates_))

test_years_ = pd.Series(data = map(lambda x : x[0], test_parse_date_), name = 'year')

test_months_ = pd.Series(data = map(lambda x : x[1], test_parse_date_), name = 'month') 

test_days_ = pd.Series(data = map(lambda x : x[2], test_parse_date_), name = 'day')

test_hours_ = pd.Series(data = map(lambda x : x[3], test_parse_date_), name = 'hour')



test_datas_ = pd.concat([test_years_, test_months_, test_days_, test_hours_, test_weekdays_, test_districts_], axis = 1)


#######################RandomForestClassifier###############

#use RandomForestClassifier to be the Classifier
#clf = RandomForestClassifier(n_estimators = 20, min_samples_leaf = 2000, bootstrap = True, oob_score = True, criterion = 'gini')
clf = RandomForestClassifier(bootstrap = True, oob_score = True, criterion = 'gini')

#train the data
print('-------------train start---------------')
clf.fit(train_datas_, train_categorys_)

#save the model,if need load the model, joblib.load(filename)
joblib.dump(clf, 'model/clf.pkl')

#predict test_datas, every class will has a probabilities,the order of the class same to the attribute classes_ 
print('-------------train end---------------')

print('-------------predict start---------------')
result_ = clf.predict_proba(test_datas_)

print('-------------predict end---------------')

#get all classes
classes_ = clf.classes_

#save the predict result to file
res_data_frame_ = pd.DataFrame(data = result_, columns = classes_)
res_data_frame_.to_csv('result.csv', index_label = 'Id')

  因为ubuntu中的sublime text3无法写中文,所以注释写的是英文,但是很简单的英文,稍微看一下应该就能懂了!!!有问题可以一起交流!!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值