【问题标题】:Use Python GridSearchCV to compare imputer methods?使用 Python GridSearchCV 比较 imputer 方法?
【发布时间】:2021-08-24 02:03:24
【问题描述】:

我正在对泰坦尼克号数据集进行预处理,以便通过一些回归运行它。 在这种情况下,训练和测试集中的“年龄”列仅填充了每个集中大约 80% 的行。

我想使用 SimpleImputer(来自 sklearn.impute import SimpleImputer)来填充这些列中的缺失值,而不是仅仅消除没有“年龄”的行。

SimpleImputer 具有用于处理数字数据的“方法”参数的三个选项。这些是平均值、中位数和最频繁(众数)。 (也可以选择使用自定义值,但因为我试图避免“合并”这些值,所以我不想使用此选项。)

在最基本的情况下,我的方法将涉及手动设置所需的数据集。我必须在每个训练和测试数据集上运行每种类型的 imputer (imputer = SimpleImputer(strategy="xxxxxx") where xxxxxx = 'mean', 'median', or 'most Frequent'),然后最终得到六个不同的数据集,然后我必须一次通过我的 RandomForestRegressor 提供一个。

我知道 GridSearchCV 可用于详尽地比较回归器中参数值的各种组合,所以我想知道是否有人知道使用它的方法或类似的方法来运行估算器的各种“方法”选项?

我正在考虑以下伪代码 -

param_grid = [
    {'method': ['mean','median', 'most frequent']},
]

forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid, cv = 5, scoring = 'neg_mean_squared_error')

grid_search.fit(titanic_features[method], titanic_values[method])

有没有一种简洁的方法来比较这样的选项?

有没有比构建所有六个数据集、通过 RF 回归器运行它们并查看结果更好的方法来比较这三个选项?

【问题讨论】:

    标签: python parameters random-forest gridsearchcv


    【解决方案1】:

    Sklearn Pipeline 正是为此而生的。您必须在回归器之前创建一个带有 imputer 组件的管道。然后,您可以使用网格搜索参数 grid 和 __ 来传递组件特定参数。

    示例代码(内嵌文档)

    # Sample/synthetic data shape 1000 X 2
    X = np.random.randn(1000,2)
    y = 1.5*X[:,0]+3.2*X[:, 1]+2.4
    
    # Randomly make 200 data points in each axis as nan's
    X[np.random.randint(0,1000, 200), 0] = np.nan
    X[np.random.randint(0,1000, 200), 1] = np.nan
    
    # Simple pipeline which has an imputer followed by regressor
    pipe = Pipeline(steps=[('impute', SimpleImputer(missing_values=np.nan)),
                           ('regressor', RandomForestRegressor())])
    
    # 3 different imputers and 2 different regressors 
    # a total of 6 different parameter combination will be searched
    param_grid = {
            'impute__strategy': ["mean", "median", "most_frequent"],
            'regressor__max_depth': [2,3]
            }
    
    # Run girdsearch
    search = GridSearchCV(pipe, param_grid)
    search.fit(X, y)
    
    print("Best parameter (CV score=%0.3f):" % search.best_score_)
    print(search.best_params_)
    

    样本输出:

    Best parameter (CV score=0.730):
    {'impute__strategy': 'median', 'regressor__max_depth': 3}
    

    因此,使用GridSearchCV,我们能够发现我们样本数据的最佳插补策略是median,如果max_dept 的组合为3。

    您可以使用其他组件继续扩展管道。

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2018-06-30
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多