机器学习之随机森林RandomForestRegressor

  • 机器学习之随机森林RandomForestRegressor
# -*- coding: utf-8 -*-
"""
Created on Tue Dec  4 18:29:45 2018

@author: muli
"""

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets,cross_validation,ensemble


def load_data_regression():
    '''
    加载用于回归问题的数据集

    :return: 一个元组,用于回归问题。元组元素依次为:训练样本集、测试样本集、训练样本集对应的值、测试样本集对应的值
    '''
    diabetes = datasets.load_diabetes() #使用 scikit-learn 自带的一个糖尿病病人的数据集
    return cross_validation.train_test_split(diabetes.data,diabetes.target,
    test_size=0.25,random_state=0) # 拆分成训练集和测试集,测试集大小为原始数据集大小的 1/4


def test_RandomForestRegressor(*data):
    '''
    测试 RandomForestRegressor 的用法

    :param data:  可变参数。它是一个元组,这里要求其元素依次为:训练样本集、测试样本集、训练样本的值、测试样本的值
    :return: None
    '''
    X_train,X_test,y_train,y_test=data
    regr=ensemble.RandomForestRegressor()
    regr.fit(X_train,y_train)
    print("Traing Score:%f"%regr.score(X_train,y_train))
    print("Testing Score:%f"%regr.score(X_test,y_test))


def test_RandomForestRegressor_num(*data):
    '''
    测试 RandomForestRegressor 的预测性能随  n_estimators 参数的影响

    :param data: 可变参数。它是一个元组,这里要求其元素依次为:训练样本集、测试样本集、训练样本的值、测试样本的值
    :return: None
    '''
    X_train,X_test,y_train,y_test=data
    nums=np.arange(1,100,step=2)
    fig=plt.figure()
    ax=fig.add_subplot(1,1,1)
    testing_scores=[]
    training_scores=[]
    for num in nums:
        regr=ensemble.RandomForestRegressor(n_estimators=num)
        regr.fit(X_train,y_train)
        training_scores.append(regr.score(X_train,y_train))
        testing_scores.append(regr.score(X_test,y_test))
    ax.plot(nums,training_scores,label="Training Score")
    ax.plot(nums,testing_scores,label="Testing Score")
    ax.set_xlabel("estimator num")
    ax.set_ylabel("score")
    ax.legend(loc="lower right")
    ax.set_ylim(-1,1)
    plt.suptitle("RandomForestRegressor")
    # 设置 X 轴的网格线,风格为 点画线
    plt.grid(axis='x',linestyle='-.')
    plt.show()


def test_RandomForestRegressor_max_depth(*data):
    '''
    测试 RandomForestRegressor 的预测性能随  max_depth 参数的影响

    :param data:  可变参数。它是一个元组,这里要求其元素依次为:训练样本集、测试样本集、训练样本的值、测试样本的值
    :return:  None
    '''
    X_train,X_test,y_train,y_test=data
    maxdepths=range(1,20)
    fig=plt.figure()
    ax=fig.add_subplot(1,1,1)
    testing_scores=[]
    training_scores=[]
    for max_depth in maxdepths:
        regr=ensemble.RandomForestRegressor(max_depth=max_depth)
        regr.fit(X_train,y_train)
        training_scores.append(regr.score(X_train,y_train))
        testing_scores.append(regr.score(X_test,y_test))
    ax.plot(maxdepths,training_scores,label="Training Score")
    ax.plot(maxdepths,testing_scores,label="Testing Score")
    ax.set_xlabel("max_depth")
    ax.set_ylabel("score")
    ax.legend(loc="lower right")
    ax.set_ylim(0,1.05)
    plt.suptitle("RandomForestRegressor")
    # 设置 X 轴的网格线,风格为 点画线
    plt.grid(axis='x',linestyle='-.')
    plt.show()


def test_RandomForestRegressor_max_features(*data):
    '''
   测试 RandomForestRegressor 的预测性能随  max_features 参数的影响

    :param data:  可变参数。它是一个元组,这里要求其元素依次为:训练样本集、测试样本集、训练样本的值、测试样本的值
    :return: None
    '''
    X_train,X_test,y_train,y_test=data
    max_features=np.linspace(0.01,1.0)
    fig=plt.figure()
    ax=fig.add_subplot(1,1,1)
    testing_scores=[]
    training_scores=[]
    for max_feature in max_features:
        regr=ensemble.RandomForestRegressor(max_features=max_feature)
        regr.fit(X_train,y_train)
        training_scores.append(regr.score(X_train,y_train))
        testing_scores.append(regr.score(X_test,y_test))
    ax.plot(max_features,training_scores,label="Training Score")
    ax.plot(max_features,testing_scores,label="Testing Score")
    ax.set_xlabel("max_feature")
    ax.set_ylabel("score")
    ax.legend(loc="lower right")
    ax.set_ylim(0,1.05)
    plt.suptitle("RandomForestRegressor")
    # 设置 X 轴的网格线,风格为 点画线
    plt.grid(axis='x',linestyle='-.')
    plt.show()
 
    
if __name__=='__main__':
    X_train,X_test,y_train,y_test=load_data_regression() # 获取回归数据
#    test_RandomForestRegressor(X_train,X_test,y_train,y_test) # 调用 test_RandomForestRegressor
#    test_RandomForestRegressor_num(X_train,X_test,y_train,y_test) # 调用 test_RandomForestRegressor_num
#    test_RandomForestRegressor_max_depth(X_train,X_test,y_train,y_test) # 调用 test_RandomForestRegressor_max_depth
    test_RandomForestRegressor_max_features(X_train,X_test,y_train,y_test) # 调用 test_RandomForestRegressor_max_features
    
  • 如图:

muli

随机森林是一种集成学习方法,它通过构建多个决策树来提高预测准确性。下面是sklearn中随机森林的一些基本步骤、参数、属性和接口: 1. 基本步骤: 1.1 参数n_estimators:指定森林中树的数量。 1.2 建立森林:使用RandomForestClassifier()函数建立随机森林。 1.3 n_estimators的学习曲线:使用validation_curve()函数绘制n_estimators的学习曲线。 2. 重要的参数、属性、接口: 2.1 random_state:在划分训练集和测试集的类train_test_split、构建决策树的函数、构建随机森林时都可以使用该参数,它可以保证每次运行时得到的结果都是一样的。 2.2 estimators_:查看森林中每棵树的状况。 2.3 bootstrap & oob_score:bootstrap参数控制是否进行有放回的随机抽样,oob_score参数控制是否使用袋外样本来评估模型的准确性。 2.4 fit & score:fit()函数用于拟合模型,score()函数用于评估模型的准确性。 2.5 feature_importances_:查看每个特征的重要性。 2.6 apply:返回每个样本所在的叶子节点的索引。 2.7 predict:对新数据进行预测。 2.8 predict_proba:返回每个类别的概率。 3. 随机森林回归器: 3.1 重要的参数、属性、接口:与分类器类似,但是需要使用RandomForestRegressor()函数来建立随机森林回归器。 4. 机器学习中调参的基本思想: 泛化误差:模型在新数据上的误差。 标签和特征:标签是我们要预测的变量,特征是我们用来预测标签的变量。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值