足球运动员身价估计

mse:18.27 排名25

目录

一、竞赛概要
二、数据处理
三、特征选择
四、模型融合

一、竞赛概要

本比赛为个人练习赛,主要针对于于数据新人进行自我练习、自我提高,与大家切磋。
练习赛时限:2018-03-05 至 2020-03-05
任务类型:回归
背景介绍:
每个足球运动员在转会市场都有各自的价码。本次数据练习的目的是根据球员的各项信息和能力值来预测该球员的市场价值。
数据来源:
FIFA2018。为了公平起见,数据已经进行脱敏加工处理。

二、数据处理

1.数据样本分类:

在数据集中增加一列是否为门将的特征,以这个特征可以将数据样本分类,然后预测结果。一是对该特征进行独热编码,产生是门将和非门将两个特征,不切分预测;二是根据该特征对数据样本进行分类,将是门将的样本归为一个数据集,非门将的样本归为另一个数据集,然后对这两个数据集进行预测。

# 获得球员年龄
today = pd.to_datetime(date(2018, 4, 15))

train['birth_date'] = pd.to_datetime(train['birth_date'])
train['age'] = (today - train['birth_date']).apply(lambda x: x.days) / 365.

test['birth_date'] = pd.to_datetime(test['birth_date'])
test['age'] = (today - test['birth_date']).apply(lambda x: x.days) / 365.


# 获得球员最擅长位置上的评分
positions = ['rw', 'rb', 'st', 'lw', 'cf', 'cam', 'cm', 'cdm', 'cb', 'lb', 'gk']

train['best_pos'] = train[positions].max(axis=1)
test['best_pos'] = test[positions].max(axis=1)


# 计算球员的身体质量指数(BMI)
train['BMI'] = 10000. * train['weight_kg'] / (train['height_cm'] ** 2)
test['BMI'] = 10000. * test['weight_kg'] / (test['height_cm'] ** 2)


# 判断一个球员是否是守门员
train['is_gk'] = train['gk'] > 0
test['is_gk'] = test['gk'] > 0
#独热编码
colunms_to_enconding=['work_rate_att','work_rate_def','preferred_foot','is_gk']
all_data=pd.get_dummies(all_data,columns=colunms_to_enconding)

#切分数据集
test['pred'] = 0
train=train.drop(train[positions],axis=1)
train=train.drop('id',axis=1)
train1=train.drop(['y','is_gk'],axis=1)
used_feat=train1.columns
train_no_gk=train[train['is_gk'] == False][used_feat].copy()
y_train_no_gk= train[train['is_gk'] == False]['y'].copy()
test_no_gk=test[test['is_gk'] == False][used_feat].copy()
train_is_gk=train[train['is_gk'] == True][used_feat].copy()
y_train_is_gk= train[train['is_gk'] == True]['y'].copy()
test_is_gk=test[test['is_gk'] == True][used_feat].copy()
2.特征选择:

使用遗传算法对特征进行筛选,用遗传算法筛选特征虽然在线下得到非常好的效果,但是在线上提交得出的结果并不理想;使用PCA降维,由于在特征处理中,我将分类特征都进行的独热编码,造成了维度增大,所以考虑用PCA降维,但是效果也不是很好;用lasso去fit数据集,然后根据lasso的系数的绝对值大小作为特征重要性的判断,然后将系数接近0的特征进行剔除;使用手动降维,通过对数据集的判断,来手动删除特征,比如nationality这个特征,个人觉得一个球员的价值跟他的国籍关系并不大,所以对它进行了剔除,在切分是否为门将的数据集中,在非门将的样本数据集中关于门将的特征可以进行剔除。

for col in ('id','lb', 'cb', 'cdm', 'cm','cam','cf','lw','st','rb','rw','birth_date','gk',
            'gk_diving','gk_handling','gk_kicking','gk_positioning','gk_reflexes'
            ,'nationality'):
     all_data=all_data.drop(col,axis=1)

最后对数据集删除空缺值和重复值,得到经过处理后的数据集。本文采用进行独热编码,产生是门将和非门将两个特征,不切分预测的数据集。

四、模型融合

本文将RF、LGB、GBoost、XGboost模型进行集成,其中原理在上一章

#Validation function
n_folds = 5

def rmsle_cv(model):
    kf = KFold(n_folds, shuffle=True, random_state=42).get_n_splits(train.values)
    rmse= np.sqrt(-cross_val_score(model, train.values, y_train, scoring="neg_mean_squared_error", cv = kf))
    return(rmse)
def rmsle(y_train, y_pred):
    return np.sqrt(mean_squared_error(y_train, y_pred))
GBoost = GradientBoostingRegressor(max_depth=45,
                         learning_rate = 0.05,
                         alpha=0.05,                     
                         n_estimators=100,                             
                         verbose = 0)
model_xgb = xgb.XGBRegressor(max_depth=45,
                         learning_rate = 0.1,                         
                         n_estimators=650)
model_lgb = lgb.LGBMRegressor(objective='regression',
                         max_depth=25,
                         learning_rate = 0.1,
                         num_leaves = 25,
                         n_estimators=8000,
                         metric='rmse', 
                         verbose = 0,)
reg_ngk = RandomForestRegressor( max_depth=75,
                         min_samples_split = 2,                       
                         min_samples_leaf = 2,
                         n_estimators=450, 
                         verbose = 0)
lasso = make_pipeline(RobustScaler(), Lasso(alpha =0.0005, random_state=1))
class StackingAveragedModels(BaseEstimator, RegressorMixin, TransformerMixin):
    def __init__(self, base_models, meta_model, n_folds=5):
        self.base_models = base_models
        self.meta_model = meta_model
        self.n_folds = n_folds
   
    # We again fit the data on clones of the original models
    def fit(self, X, y):
        self.base_models_ = [list() for x in self.base_models]
        self.meta_model_ = clone(self.meta_model)
        kfold = KFold(n_splits=self.n_folds, shuffle=True, random_state=156)
        
        # Train cloned base models then create out-of-fold predictions
        # that are needed to train the cloned meta-model
        out_of_fold_predictions = np.zeros((X.shape[0], len(self.base_models)))
        for i, model in enumerate(self.base_models):
            for train_index, holdout_index in kfold.split(X, y):
                instance = clone(model)
                self.base_models_[i].append(instance)
                instance.fit(X[train_index], y[train_index])
                y_pred = instance.predict(X[holdout_index])
                out_of_fold_predictions[holdout_index, i] = y_pred
                
        # Now train the cloned  meta-model using the out-of-fold predictions as new feature
        self.meta_model_.fit(out_of_fold_predictions, y)
        return self
   
    #Do the predictions of all base models on the test data and use the averaged predictions as 
    #meta-features for the final prediction which is done by the meta-model
    def predict(self, X):
        meta_features = np.column_stack([
            np.column_stack([model.predict(X) for model in base_models]).mean(axis=1)
            for base_models in self.base_models_ ])
        return self.meta_model_.predict(meta_features)
stacked_averaged_models = StackingAveragedModels(base_models = (reg_ngk, GBoost, model_lgb, model_xgb),
                                                 meta_model = lasso)
score = rmsle_cv(stacked_averaged_models)
print("Stacking Averaged models score: {:.4f} ({:.4f})".format(score.mean(), score.std()))
stacked_averaged_models.fit(train.values, y_train)
stacked_train_pred = stacked_averaged_models.predict(train.values)
stacked_pred = stacked_averaged_models.predict(test.values)
print(rmsle(y_train, stacked_train_pred))


model_xgb.fit(train.values, y_train)
xgb_train_pred = model_xgb.predict(train.values)
xgb_pred = model_xgb.predict(test.values)
print(rmsle(y_train, xgb_train_pred))



model_lgb.fit(train.values, y_train)
lgb_train_pred = model_lgb.predict(train.values)
lgb_pred = model_lgb.predict(test.values)
print(rmsle(y_train, lgb_train_pred))



'''RMSE on the entire Train data when averaging'''

print('RMSLE score on train data:')
print(rmsle(y_train,stacked_train_pred*0.70 +xgb_train_pred*0.15 + lgb_train_pred*0.15 ))

train_new=pd.DataFrame(index=train.index)
for i in range(3):
    if i ==0:
        train_new.loc[:,i]=stacked_train_pred
    elif i==1:
        train_new.loc[:,i]=xgb_train_pred
    else:
        train_new.loc[:,i]=lgb_train_pred
test_new=pd.DataFrame(index=test.index)
for i in range(3):
    if i ==0:
        test_new.loc[:,i]=stacked_pred
    elif i==1:
        test_new.loc[:,i]=xgb_pred
    else:
        test_new.loc[:,i]=lgb_pred
from sklearn.linear_model import Lasso
Lasso = Lasso()
Lasso.fit(train_new, y_train.astype('int'))
y_pred=Lasso.predict(test_new)
rmsle(y_train,Lasso.predict(train_new))
ensemble = stacked_pred
submit.loc[:, 'y'] = ensemble
submit.to_csv('stacking.csv', index=False)

结果

关于提升的想法:
1.首先最重要的就是数据的处理,在特征的筛选上一开始我是用遗传算法和PCA进行特征筛选,但是结果都不好,然后lasso去fit数据集,然后根据lasso的系数的绝对值大小作为特征重要性的判断,然后将系数接近0的特征进行剔除,相比于前面两种方法进步颇大,但是还没到预想到的结果,最后我是根据自己判断,尝试着剔除特征,效果进步明显,由于手动筛选特征耗时,而且你不知道你这特征你剔除后,线上提交的结果是否有改善,结果两个小时更新一次,所以非常耗时间,但是特征筛选这是关键的一步,后续会更加深入研究关于数据的处理方面。
2.在模型融合的结果,其实就是根据几个模型的预测结果,给与不同的权重,组合成一个最优的结果,那么如何确定这个权重也是至关重要,这里采用的是用lasso去拟合,还尝试了用遗传算法去计算这个权重,遗传算法的好处就是在线下它可以根据这个已有的结果去迭代不同参数,达到结果最优,过拟合情况非常严重,迭代5000次,最后在训练集上误差接近0。
3.尝试在模型融合中加入神经网络RNN。

代码

你可能感兴趣的:(足球运动员身价估计)