首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何防止随机森林中的过拟合

如何防止随机森林中的过拟合
EN

Stack Overflow用户
提问于 2020-11-10 22:37:59
回答 2查看 279关注 0票数 0

我建立了一个随机森林模型来预测NFL球队是否会获得比拉斯维加斯设定的线更多的总分。我使用的特征是Total -拉斯维加斯认为两支球队都会得分的总积分,over_percentage -公众对over的下注百分比,以及under_percentage -公众对under的下注百分比。超过意味着人们打赌两支球队的总分将大于拉斯维加斯设置的数字,低于意味着总分将低于拉斯维加斯的数字。当我运行我的模型时,我得到了一个这样的confusion_matrix

accuracy_score为76%。然而,这些预测并没有很好地发挥作用。现在我有了它,它给了我分类为0的概率。我想知道是否有可以调整的参数或解决方案来防止我的模型过度拟合。我在训练数据集中有超过30K个游戏,所以我不认为缺乏数据会导致这个问题。

代码如下:

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

发布于 2020-11-10 23:03:19

在使用RandomForests时需要注意几件事。首先,您可能希望使用cross_validate来测量模型的性能。

此外,通过调整以下参数可以使RandomForests正则化:

  • Decreasing max_depth:这是一个控制树的最大深度的参数。它越大,就会有更多的参数,记住,当有过多的参数是fitted.
  • Increasing min_samples_leaf时,就会发生过拟合:我们可以增加叶节点所需的最小样本数,而不是减少max_depth,这也会限制树的生长,并防止具有非常少样本的叶子(Overfitting!)
  • Decreasing max_features:如前所述,当有大量的参数被拟合时,就会发生过拟合,参数的数量与模型中的特征数量有直接关系,因此,限制每个树中的要素数量将有助于控制overfitting.

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

代码语言:javascript
复制
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)

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

票数 1
EN

Stack Overflow用户

发布于 2020-11-10 23:26:50

通过将其设置为test_split=0.25,您可以使用train_test_split拆分数据。这样做的缺点是它随机拆分数据,并在这样做时完全忽略类的分布。您的模型将受到采样偏差的影响,即不能跨训练和测试数据集维护数据的正确分布。

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

要克服这一点,您可以使用StratifiedKFoldCrossValidation,它相应地维护类的分布。

为数据帧创建K折

代码语言:javascript
复制
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

对于基于上一个函数创建的数据集的每个文件夹,应运行此函数

代码语言:javascript
复制
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))

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64771024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档