如何解决如何防止随机森林过度拟合 为数据框创建K形折叠
我建立了一个随机森林模型来预测NFL球队的综合得分是否会超过维加斯设定的分界线。我使用的功能是over_percentage
-维加斯认为两支球队都将得分的总分; under_percentage
-公开投注的百分比; 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,100]
min_samples_leaf = [1,2,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()
-公开的百分比下注。大于表示人们押注两支球队的总得分将大于维加斯设定的数字,而小于则意味着总得分将低于维加斯数字。当我运行模型时,我会遇到这样的confusion_matrix
,准确性得分为76%。但是,预测效果不佳。现在,我可以得到分类为0的可能性。我想知道是否可以调整参数或解决方案以防止模型过度拟合。我的训练数据集中有超过3万场比赛,所以我认为没有数据会引起问题。
代码如下:
make dist
这是google文档与测试和培训数据的链接。
解决方法
使用RandomForests时需要注意两点。首先,您可能想使用cross_validate
来衡量模型的性能。
此外,可以通过调整以下参数来对RandomForests进行正则化:
- 减小
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)
这将返回一张表,其中包含所有不同模型的性能(考虑到超参数的组合),使您可以轻松找到最佳模型。
,您正在通过将train_test_split
设置为test_split=0.25
来拆分数据。这样做的缺点是它会随机拆分数据,并在这样做时完全忽略类的分布。您的模型会遭受抽样偏差的困扰,无法在训练和测试数据集中保持正确的数据分布。
在训练集中,与测试集相比,数据可能更倾向于特定的数据实例,反之亦然。
要解决此问题,您可以使用StratifiedKFoldCrossValidation
来相应地维护类的分布。
为数据框创建K形折叠
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))
此外,您应该执行超参数调整,以找到最适合您的参数,另一个答案显示了如何做到这一点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。