10、集成学习(一)实战

随机森林API

参数

​ RandomForestClassifier
​ RandomForestRegr
criterion
​ 指定划分标准,默认为gini,不支持其它参数
​ 指定划分标准,可选"mse”和"mae";默认mse
loss
​ 不支持
​ 指定误差的计算方式,可选参数”linear" , “square”,“exponential”,默认为"linear";一般不用改动
n_estimators
​ 最大迭代次数,也就是最多允许的决策树的数目,值过小可能会导致欠拟合,值过大可能会导致过拟合,一
般50~100比较适合,默认10

max_features

​ 给定在进行最佳特征划分的时候,选择多少个特征进行考虑;默认为auto;max_features=sqrt(n_features);一般不建议改动
max_depth
​ 给定树的深度,默认为None,表示一致扩展到叶子节点足够纯或者样本数小于min_samples_split

min_samples_split
给定树构建过程中,叶子节点中最少样本数量,默认为2(样本只有两个的话就不能分裂)
min_samples_leaf
给定一棵树最少叶子数量,默认为1
bootstrap
是否进行有放回的重采样,默认为True

随机森林回归实战

import pandas as pd
import numpy as np
from sklearn.metrics(度量指标) import mean_squared_error, r2_score
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble(集成学习) import RandomForestRegressor(回归树)
import warnings(警告)
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')(忽略警告)
df = pd.DataFrame([
    [1,5.56],
    [2,5.7],
    [3,5.91],
    [4,6.4],
    [5,6.8],
    [6,7.05],
    [7,8.9],
    [8,8.7],
    [9,9],
    [10,9.05]
])
X = df.iloc[:,[0]]
Y = df.iloc[:,-1](切片处理)
RF = RandomForestRegressor()
pg = {'n_estimators': [20, 50, 100, 200, 350], 'max_depth': [1, 2, 3, 4], 
      'min_samples_leaf': [1, 2]}(调整参数的范围)
model = GridSearchCV(RF, param_grid=pg, cv=3)#cv  cross validation(通过交叉验证得到调整的最优参数)
model.fit(X, Y)
print('最优参数{}'.format(model.best_params_))
print('均方误差:{}'.format(mean_squared_error(Y, model.predict(X))))
print('r2数值:{}'.format(model.score(X, Y)))(在查看模型优越性的能力上,还是R方更有说服力)
y_ = model.predict(X)
m = df.shape[0]
plt.rcParams['font.sans-serif']=['SimHei']
plt.plot(np.arange(m), Y, 'r-', label='实际样本')
plt.plot(y_, 'b-', label='预测效果')
plt.legend()
plt.grid()
plt.show()#通过模型看预测和实际的差距

随机森林分类实战

import pandas as pd
import numpy as np
from sklearn.metrics(评估指标比回归的要多) import f1_score, recall_score, precision_score, confusion_matrix
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
import warnings
warnings.filterwarnings('ignore')
df = pd.DataFrame([
    [0,1],
    [1,1],
    [2,1],
    [3,-1],
    [4,-1],
    [5,-1],
    [6,1],
    [7,1],
    [8,1],
    [9,-1]
])
X = df.iloc[:,:-1]
Y = df.iloc[:,-1:]
model = RandomForestClassifier(n_estimators=50)
model.fit(X, Y)
print(f1_score(Y, model.predict(X)))
print(confusion_matrix(Y, model.predict(X)))
print('AUC:', roc_auc_score(Y, model.predict_proba(X)[:, -1:]))
fpr, tpr, th = roc_curve(Y, model.predict_proba(X)[:, -1:])
plt.plot(fpr, tpr)
plt.show()

ROC曲线的参数是实际标签和预测的得分(概率)进行计算的

随机森林运算速度比KNN的运算快,效果也更好

随机森林不需要进行数据预处理操作(比如特征缩放),因为随机森林底层用的都是决策树

随机森林的准确率可以达到1的,所以性能也是非常强的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T o r

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值