Google 在 2017 年 9 月 12 号的博文 Introduction to TensorFlow Datasets and Estimators 中介绍了新引入的两个新特性 Datasets Estimators:这是模型的核心部分,而 Estimators 的核心部分则是一个 model_fn 函数(后面会细讲),你在这个函数中定义你的模型架构,输入是特征和标签,输出是一个定义好的 estimator 我 6 月份的时候也写过一篇博文简单说了下 tf.contrib.learn.DNNRegressor 的使用,实际上这就是 Estimators 内置的一个模型(estimator)。 Note:本篇博文中的模型并不是结果最好的模型,仅仅是为了展示如何将 Estimators 和 Datasets 结合起来使用。 References Introduction to TensorFlow Datasets and Estimators Importing Data | TensorFlow Creating Estimators
This recipe is about creating fake estimators; this isn't the pretty or exciting stuff, but it is worthwhile Fit the various dummy estimators.拟合变量的虚拟估计值 We'll perform these two steps for regression data and classification It's always good to test your models against the simplest models and that's exactly what the dummy estimators
=80, n_estimators=50; total time= 1.9s [CV 1/5] END .................max_depth=80, n_estimators=100 =80, n_estimators=100; total time= 3.8s [CV 1/5] END .................max_depth=80, n_estimators=200 =80, n_estimators=200; total time= 7.6s [CV 1/5] END .................max_depth=80, n_estimators=300 =80, n_estimators=300; total time= 11.4s [CV 1/5] END .................max_depth=80, n_estimators=400 =90, n_estimators=50; total time= 2.0s [CV 1/5] END .................max_depth=90, n_estimators=100
n_estimators : int类型,表示基本学习器的数量。默认是10 max_samples : int类型或者float类型, 默认为1.0. estimators_ : list of estimators The collection of fitted base estimators. estimators_samples_ The subset of drawn samples for each base estimator. If base estimators do not implement a predict_proba method, then it resorts to voting. The method works on simple estimators as well as on nested objects (such
10.3.1 Bagging Regressor 类参数、属性和方法 类 class sklearn.ensemble.BaggingRegressor(base_estimator=None, n_estimators estimators_ list of estimators 拟合子估计量的集合。 estimators_samples_ list of arrays 每个基估计量的抽样子集。 estimators_features_ list of arrays 每个基估计量的特征子集。 oob_score_ float 使用现成的估计值获得的训练数据集的得分。 如果n_estimators很小,则可能在引导过程中从未遗漏数据点。在这种情况下, oob_prediction_可能包含NaN。只有当oob_score为True时,此属性才存在。 y_train,y_test = train_test_split(X, y, random_state=8,test_size=0.3) clf = BaggingRegressor(n_estimators
调参刚开始的时候,一般要先初始化一些值: learning_rate: 0.1 n_estimators: 500 max_depth: 5 min_child_weight: 1 subsample: : {'n_estimators': 600}, mean: 0.94060, std: 0.01223, params: {'n_estimators': 700}, mean: 0.94058, std : 0.01231, params: {'n_estimators': 800}] 参数的最佳取值:{'n_estimators': 600} 最佳模型得分:0.9406056804545407 由输出结果可知最佳迭代次数为 : {'n_estimators': 600}, mean: 0.94060, std: 0.01226, params: {'n_estimators': 650}, mean: 0.94060, std : 0.01224, params: {'n_estimators': 675}] 参数的最佳取值:{'n_estimators': 550} 最佳模型得分:0.9406545392685364 果不其然
X = pd.DataFrame(data, columns=feature_names) 让我们将森林中的树数设置为 100: RandomForestRegressor(n_estimators=100 ) 决策树存储在 模型list 中的 estimators_ 属性中 rf 。 len(estimators_)>>> 100 我们可以从随机森林中绘制第一棵决策树( 0 列表中有索引): plot\_tree(rf.estimators\_\[0\]) 这棵树太大,无法在一个图中将其可视化 第一个决策树的可视化图: plot\_tree(rf.estimators\_\[0\]) 我们可以可视化第一个决策树: viz 概括 我将向您展示如何可视化随机森林中的单个决策树。 可以通过 estimators_ 列表中的整数索引访问树。有时当树太深时,值得用 max_depth 超参数限制树的深度。
X = pd.DataFrame(data, columns=feature_names) 让我们将森林中的树数设置为 100: RandomForestRegressor(n_estimators=100 ) 决策树存储在 模型list 中的 estimators_ 属性中 rf 。 len(estimators_)>>> 100 我们可以从随机森林中绘制第一棵决策树( 0 列表中有索引): plot\_tree(rf.estimators\_\[0\]) 这棵树太大,无法在一个图中将其可视化 第一个决策树的可视化图: plot\_tree(rf.estimators\_\[0\]) 我们可以可视化第一个决策树: viz 概括 我将向您展示如何可视化随机森林中的单个决策树。 可以通过 estimators_ 列表中的整数索引访问树。有时当树太深时,值得用 max_depth 超参数限制树的深度。
AdaBoostClassifier 类参数、属性和方法 类 class sklearn.ensemble.AdaBoostClassifier(base_estimator=None, *, n_estimators estimators_ list of classifiers 拟合子估计量的集合。 classes_ ndarray of shape (n_classes,) 类标签。。 =50,random_state=11),X,y,title) myutil.show_pic(title) clf = AdaBoostClassifier(n_estimators =50,random_state=11),X,y,title) myutil.show_pic(title) clf = AdaBoostClassifier(n_estimators =50,random_state=11),X,y,title) myutil.show_pic(title) clf = AdaBoostClassifier(n_estimators
10.3.1 Bagging Classifier 类参数、属性和方法 类 class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators estimators_ list of estimators 拟合基估计量的集合。 estimators_samples_ list of arrays 每个基估计量的抽样子集。 estimators_features_ list of arrays 每个基估计量的特征子集。 classes_ ndarray of shape (n_classes,) 类标签。 =50,random_state=11),X,y,title) myutil.show_pic(title) clf = AdaBoostClassifier(n_estimators =50,random_state=11),X,y,title) myutil.show_pic(title) clf = AdaBoostClassifier(n_estimators
], # 参数组合使用自然数递增方式 "logisticregression-2__C":[1.0, 100.0], "randomforestclassifier__n_estimators /- 0.01 {'logisticregression-1__C': 1.0, 'logisticregression-2__C': 1.0, 'randomforestclassifier__n_estimators /- 0.01 {'logisticregression-1__C': 1.0, 'logisticregression-2__C': 1.0, 'randomforestclassifier__n_estimators 0.01 {'logisticregression-1__C': 1.0, 'logisticregression-2__C': 100.0, 'randomforestclassifier__n_estimators 0.01 {'logisticregression-1__C': 1.0, 'logisticregression-2__C': 100.0, 'randomforestclassifier__n_estimators
with features [0, 1] has a score of 0.9266666666666666 ExtraTrees with 30 estimators with features [ 0, 1] has a score of 0.9266666666666666 AdaBoost with 30 estimators with features [0, 1] has a score =n_estimators), ExtraTreesClassifier(n_estimators=n_estimators), AdaBoostClassifier (DecisionTreeClassifier(max_depth=3), n_estimators=n_estimators)] for pair _"): model_details += " with {} estimators".format( len(model.estimators_
上课在腾讯会议上进行 AdaBoost Regressor 类参数、属性和方法 类 class sklearn.ensemble.AdaBoostRegressor(base_estimator=None, *, n_estimators estimators_ list of classifiers 拟合子估计量的集合。 estimator_weights_ ndarray of floats 增强集合中每个估计器的权重。 y_train,y_test = train_test_split(X, y, random_state=8,test_size=0.3) clf = AdaBoostRegressor(n_estimators X_train,X_test,y_train,y_test = train_test_split(X, y, random_state=0) clf = AdaBoostRegressor(n_estimators X_train,X_test,y_train,y_test = train_test_split(X, y, random_state=0) clf = AdaBoostRegressor(n_estimators
最大树高 random_state=7) # 随机种子 # 调用validation_curve,返回训练集、测试集得分矩阵 n_estimators = np.arange(50, 550, 50) # 超参数值表 print("n_estimators.shape:", n_estimators.shape) print("n_estimators :", n_estimators) # 通过不同参数,构建多棵决策树,验证其准确性 train_scores1, test_scores1 = ms.validation_curve(model, ', facecolor='lightgray') mp.title('n_estimators', fontsize=20) mp.xlabel('n_estimators', fontsize=14 ) mp.ylabel('F1 Score', fontsize=14) mp.tick_params(labelsize=10) mp.grid(linestyle=':') mp.plot(n_estimators
) params = { 'kneighborsclassifier__n_neighbors': [1, 5], 'randomforestclassifier__n_estimators kneighborsclassifier__n_neighbors': 1, 'meta-logisticregression__C': 0.1, 'randomforestclassifier__n_estimators kneighborsclassifier__n_neighbors': 1, 'meta-logisticregression__C': 0.1, 'randomforestclassifier__n_estimators kneighborsclassifier__n_neighbors': 5, 'meta-logisticregression__C': 0.1, 'randomforestclassifier__n_estimators kneighborsclassifier__n_neighbors': 5, 'meta-logisticregression__C': 0.1, 'randomforestclassifier__n_estimators
不同模型手动调参思路会有差异,如随机森林是一种bagging集成的方法,参数主要有n_estimators(子树的数量)、max_depth(树的最大生长深度)、max_leaf_nodes(最大叶节点数 (此外其他参数不展开说明) 对于n_estimators:通常越大效果越好。参数越大,则参与决策的子树越多,可以消除子树间的随机误差且增加预测的准度,以此降低方差与偏差。 ':int(params['n_estimators']), 'max_leaf_nodes': int(params['max_leaf_nodes']) ': hp.quniform('n_estimators', 2, 50, 1), 'max_leaf_nodes': hp.quniform('max_leaf_nodes', 2, "] = int(best_params["n_estimators"]) return best_params # 搜索最优参数 best_params = bayes_fmin(train_x
集成评估器参数 只需要关注随机森林中树木的数量n_estimators参数即可。通常来说,这个参数对随机森林模型的精确性影响是单调的,n_estimators越大,模型的效果往往越好。 但是相应的,任何模型都有决策边界,n_estimators达到一定的程度之后,随机森林的精确性往往不在上升或开始波动,并且,n_estimators越大,需要的计算量和内存也越大,训练的时间也会越来越长 基于2.1部分的代码,下面研究随机森林中树木的数量n_estimators参数对模型性能的影响。 随机森林分类函数的重要属性 属性 作用 .estimators_ 用来查看随机森林中所有树的列表 oob_score_ 袋外得分。 学习曲线如下所示: 由此,可以确定对于n_estimators的决策边界处于[30 75]之间,在此基础上进而对其他超参数依次进行网格搜索。
[10, 50, 100], 'max_depth': [5, 15, 30, 45, 60]}, 'GradientBoostingRegressor': {'n_estimators ': [10, 50, 100], 'max_depth': [5, 15, 30, 45, 60]}, 'XGBRegressor': {'n_estimators': 通过超参数整定,得到的模型最优参数为: GradientBoostingRegressor max_depth=30 n_estimators=10 lags = 2 Ridge alpha=1 lags = 2 RandomForestRegressor max_depth=5 n_estimators=100 lags = 7 LGBMRegressor max_depth=15 n_estimators =10 lags = 5 XGBRegressor max_depth=5 n_estimators=10 lags = 2 预测 我们现在知道了应用于模型的最佳参数,可以开始训练了。
例如,我们可以定义一个树的数量(n_estimators)和树大小(max_depth)的网格,通过将网格定义为: 1n_estimators = [50, 100, 150, 200] 2max_depth = [2, 4, 6, 8] 3param_grid = dict(max_depth=max_depth, n_estimators=n_estimators) 然后使用 10 倍交叉验证评估每个参数组合 要考虑调整的参数是: 树木的数量和大小( n_estimators 和 max_depth )。 学习率和树木数量( learning_rate 和 n_estimators )。
= "n_estimators" RANDOM_FOREST_REGRESSOR = "random_forest_regressor" RANDOM_STATE = "random_state" 参见 `sample_to_model` 函数 # 与目标函数一起定义以查看此操作 KWARGS: { N_ESTIMATORS: scope.int( : scope.int( hp.quniform(f"{GRADIENT_BOOSTING_REGRESSOR}__{N_ESTIMATORS}", 50, 150, 1) ", title={ "text": "learning_rate vs. n_estimators | max_depth == 3", "xanchor": "center", "yanchor": "top", "x": 0.5, }, ) 该图的一个要点是,我们可能希望尝试增加最大值n_estimators超参数