【问题标题】:How to prevent overfitting in Random Forest如何防止随机森林中的过度拟合
【发布时间】:2021-02-22 12:23:50
【问题描述】:

我建立了一个随机森林模型,用于预测 NFL 球队的总得分是否会超过维加斯设定的分数线。我使用的功能是Total - Vegas 认为两支球队将得分的总分,over_percentage - 公开赌注的百分比,以及under_percentage - 公开赌注的百分比。 over 意味着人们打赌两支球队的综合得分将大于 Vegas 的得分,under 意味着总得分将低于 Vegas 的得分。当我运行我的模型时,我得到了一个这样的混淆矩阵

准确度得分为 76%。但是,预测效果并不理想。现在我有它给我分类的概率为 0。我想知道是否有可以调整的参数或解决方案来防止我的模型过度拟合。我的训练数据集中有超过 30,000 款游戏,所以我不认为缺少数据会导致问题。

代码如下:

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

training_data = pd.read_csv(
    '/Users/aus10/NFL/Data/Betting_Data/Training_Data_Betting.csv')
test_data = pd.read_csv(
    '/Users/aus10/NFL/Data/Betting_Data/Test_Data_Betting.csv')

df_model = training_data.dropna()

X = df_model.loc[:, ["Total", "Over_Percentage",
                     "Under_Percentage"]]  # independent columns
y = df_model["Over_Under"]  # target column

results = []

model = RandomForestClassifier(
    random_state=1, n_estimators=500, min_samples_split=2, max_depth=30, min_samples_leaf=1)

n_estimators = [100, 300, 500, 800, 1200]
max_depth = [5, 8, 15, 25, 30]
min_samples_split = [2, 5, 10, 15, 100]
min_samples_leaf = [1, 2, 5, 10]

hyperF = dict(n_estimators=n_estimators, max_depth=max_depth,
              min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf)

gridF = GridSearchCV(model, hyperF, cv=3, verbose=1, n_jobs=-1)

model.fit(X, y)

skf = StratifiedKFold(n_splits=2)

skf.get_n_splits(X, y)

StratifiedKFold(n_splits=2, random_state=None, shuffle=False)

for train_index, test_index in skf.split(X, y):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X, X
    y_train, y_test = y, y

bestF = gridF.fit(X_train, y_train)

print(bestF.best_params_)

y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
print(round(accuracy_score(y_test, y_pred), 2))

index = 0
count = 0

while count < len(test_data):
    team = test_data.loc[index].at['Team']
    total = test_data.loc[index].at['Total']
    over_perc = test_data.loc[index].at['Over_Percentage']
    under_perc = test_data.loc[index].at['Under_Percentage']

    Xnew = [[total, over_perc, under_perc]]
    # make a prediction
    ynew = model.predict_proba(Xnew)
    # show the inputs and predicted outputs
    results.append(
        {
            'Team': team,
            'Over': ynew[0][0]
        })
    index += 1
    count += 1

sorted_results = sorted(results, key=lambda k: k['Over'], reverse=True)

df = pd.DataFrame(sorted_results, columns=[
    'Team', 'Over'])
writer = pd.ExcelWriter('/Users/aus10/NFL/Data/ML_Results/Over_Probability.xlsx',  # pylint: disable=abstract-class-instantiated
                        engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.style.set_properties(**{'text-align': 'center'})
pd.set_option('display.max_colwidth', 100)
pd.set_option('display.width', 1000)
writer.save()

这里是谷歌文档与测试和训练数据的链接。

Test Data

Training Data

【问题讨论】:

    标签: python pandas machine-learning scikit-learn random-forest


    【解决方案1】:

    使用 RandomForests 时有几件事需要注意。首先,您可能想使用cross_validate 来衡量模型的性能。

    此外,随机森林可以通过调整以下参数进行正则化:

    • 递减max_depth:这是一个控制树的最大深度的参数。越大,参数就越多,请记住,当拟合的参数过多时会发生过拟合。
    • 增加min_samples_leaf:除了减少max_depth,我们可以增加叶子节点所需的最小样本数,这也会限制树的生长并防止叶子样本很少(过拟合!)
    • 减少max_features:如前所述,当拟合的参数过多时会发生过度拟合,参数的数量与模型中的特征数量有直接关系,因此限制每棵树中的特征数量将证明有助于控制过度拟合。

    最后,您可能想使用GridSearchCV 尝试不同的值和方法来自动化并尝试不同的组合:

    from sklearn.ensemble import RandomForestClassifier
    from sklearn.grid_search import GridSearchCV
    rf_clf = RandomForestClassifier()
    parameters = {'max_features':np.arange(5,10),'n_estimators':[500,1000,1500],'max_depth':[2,4,8,16]}
    clf = GridSearchCV(rf_clf, parameters, cv = 5)
    clf.fit(X,y)
    

    这将返回一个表格,其中包含所有不同模型的性能(给定超参数的组合),这将使您更容易找到最佳模型。

    【讨论】:

    • nvm 我没有意识到有一个 .best_params_
    【解决方案2】:

    您通过将train_test_split 设置为test_split=0.25 来拆分数据。这样做的缺点是它随机拆分数据并在这样做时完全忽略了类的分布。您的模型将受到采样偏差的影响,即无法在训练和测试数据集中保持数据的正确分布。

    与测试集相比,在您的训练集中,数据可能更倾向于数据的特定实例,反之亦然。

    要克服这个问题,您可以使用StratifiedKFoldCrossValidation,它会相应地维护类的分布。

    为数据框创建 K-Fold

    def kfold_(df):
        df = pd.read_csv(file)
        df["kfold"] = -1
        df = df.sample(frac=1).reset_index(drop=True)
        y= df.target.values
        kf= model_selection.StratifiedKFold(n_splits=5)
    
        for f, (t_, v_) in enumerate(kf.split(X=df, y=y)):
            df.loc[v_, "kfold"] = f
    

    应该为基于前一个函数创建的数据集的每个折叠运行此函数

    def run(fold):
        df = pd.read_csv(file)
        df_train = df[df.kfold != fold].reset_index(drop=True)
        df_valid= df[df.kfold == fold].reset_index(drop=True)
    
        x_train = df_train.drop("label", axis = 1).values
        y_train = df_train.label.values
    
        x_valid = df_valid.drop("label", axis = 1).values
        y_valid = df_valid.label.values
        rf = RandomForestRegressor()
        grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, 
                              cv = 5, n_jobs = -1, verbose = 2)
        grid_search.fit(x_train, y_train)
        y_pred = model.predict(x_valid)
        print(f"Fold: {fold}")
        print(confusion_matrix(y_valid, y_pred))
        print(classification_report(y_valid, y_pred))
        print(round(accuracy_score(y_valid, y_pred), 2))
    

    此外,您应该执行超参数调整以找到最适合您的参数,另一个答案向您展示了如何做到这一点。

    【讨论】:

    • 我更新了代码。这是实现这一点的正确方法吗?
    猜你喜欢
    • 2016-03-01
    • 2020-06-24
    • 2021-03-25
    • 2017-08-11
    • 2021-02-08
    • 2019-04-01
    • 2017-04-28
    • 2018-06-07
    • 2013-12-26
    相关资源
    最近更新 更多