使用sklearn进行预测建模流程

我逐渐从R转向Python来进行一些预测建模。我想知道使用交叉验证进行超参数优化并将训练好的模型应用于新实例的最佳流程是什么。

下面你会看到我使用随机森林的一个快速示例。我想知道这个方法是否可行,以及你会添加或删除什么内容?

#import data setstrain_df = pd.read_csv('../input/train.csv') test_df = pd.read_csv('../input/test.csv')#get the predictors onlyX_train = train_df.drop(["ID", "target"], axis=1) y_train = np.log1p(train_df["target"].values)  X_test = test_df.drop(["ID"], axis=1)#grid to do the random searchfrom sklearn.model_selection import RandomizedSearchCV n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]max_features = ['auto', 'sqrt']max_depth = [int(x) for x in np.linspace(10, 110, num = 11)] max_depth.append(None)min_samples_split = [2, 5, 10]min_samples_leaf = [1, 2, 4]bootstrap = [True, False]  # Create the random gridrandom_grid = {'n_estimators': n_estimators,           'max_features': max_features,           'max_depth': max_depth,           'min_samples_split': min_samples_split,           'min_samples_leaf': min_samples_leaf,           'bootstrap': bootstrap}#Create the model to tunerf = RandomForestRegressor()rf_random= RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 10, verbose=2, random_state=42, n_jobs =10)#fit the random search modelrf_random.fit(X_train, y_train) #get the best estimatorbest_random = rf_random.best_estimator_ # train again with the best parameters on the whole training data?best_random.fit(X_train,y_train)#apply the best predictor to the test setpred_test_rf = np.expm1(best_random.predict(X_test)) 
  1. .best_estimator_是否使用网格搜索中找到的最佳参数来实例化模型?

  2. 如果是的话,我是否需要像上面那样在整个训练数据上重新训练,还是它已经重新训练过了?

  3. 我想知道这种方法是否可行,或者使用sklearn在Python中进行这种操作的最佳实践是什么?


回答:

1) 是的,它是使用rf_random中的best_params_初始化的估计器

2) 不,它已经在整个数据上训练过了,不需要执行best_random.fit(X_train,y_train)

RandomizedSearchCV有一个参数'refit',默认值为True

refit : boolean, or string default=True        Refit an estimator using the best found parameters on the whole dataset.

3) 你的方法看起来不错。这是标准做法。其他事情可能取决于各种因素,如数据类型、数据大小、使用的算法(估计器)、探索可能性的时间等。但这部分内容最适合在https://stats.stackexchange.com上讨论。

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注