Pandas 通过定时数据和交叉验证避免数据泄漏

Pandas 通过定时数据和交叉验证避免数据泄漏,pandas,machine-learning,scikit-learn,cross-validation,k-fold,Pandas,Machine Learning,Scikit Learn,Cross Validation,K Fold,我在用电话。 我希望使用knn回归器预测拍摄标志。 我试图通过按季节、年和月对数据进行分组来避免数据泄漏。 季节是预先存在的列,年和月是我添加的列,如下所示: kobe_data_encoded['year'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('(\d{4})').findall(x)[0])) kobe_data_encoded['month'] = kobe_data_encoded['ga


我在用电话。
我希望使用
knn回归器
预测拍摄标志。
我试图通过按
季节
对数据进行分组来避免数据泄漏。
季节
是预先存在的列,
是我添加的列,如下所示:

kobe_data_encoded['year'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('(\d{4})').findall(x)[0]))
kobe_data_encoded['month'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('-(\d+)-').findall(x)[0]))
以下是我的功能预处理代码的完整代码:

import re
# drop unnecesarry columns
kobe_data_encoded = kobe_data.drop(columns=['game_event_id', 'game_id', 'lat', 'lon', 'team_id', 'team_name', 'matchup', 'shot_id'])

# use HotEncoding for action_type, combined_shot_type, shot_zone_area, shot_zone_basic, opponent
kobe_data_encoded = pd.get_dummies(kobe_data_encoded, prefix_sep="_", columns=['action_type'])
kobe_data_encoded = pd.get_dummies(kobe_data_encoded, prefix_sep="_", columns=['combined_shot_type'])
kobe_data_encoded = pd.get_dummies(kobe_data_encoded, prefix_sep="_", columns=['shot_zone_area'])
kobe_data_encoded = pd.get_dummies(kobe_data_encoded, prefix_sep="_", columns=['shot_zone_basic'])
kobe_data_encoded = pd.get_dummies(kobe_data_encoded, prefix_sep="_", columns=['opponent'])

# covert season to years
kobe_data_encoded['season'] = kobe_data_encoded['season'].apply(lambda x: int(re.compile('(\d+)-').findall(x)[0]))

# covert shot_type to numeric representation
kobe_data_encoded['shot_type'] = kobe_data_encoded['shot_type'].apply(lambda x: int(re.compile('(\d)PT').findall(x)[0]))

# add year and month using game_date
kobe_data_encoded['year'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('(\d{4})').findall(x)[0]))
kobe_data_encoded['month'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('-(\d+)-').findall(x)[0]))
kobe_data_encoded = kobe_data_encoded.drop(columns=['game_date'])

# covert shot_type to numeric representation
kobe_data_encoded.loc[kobe_data_encoded['shot_zone_range'] == 'Back Court Shot', 'shot_zone_range'] = 4
kobe_data_encoded.loc[kobe_data_encoded['shot_zone_range'] == '24+ ft.', 'shot_zone_range'] = 3
kobe_data_encoded.loc[kobe_data_encoded['shot_zone_range'] == '16-24 ft.', 'shot_zone_range'] = 2
kobe_data_encoded.loc[kobe_data_encoded['shot_zone_range'] == '8-16 ft.', 'shot_zone_range'] = 1
kobe_data_encoded.loc[kobe_data_encoded['shot_zone_range'] == 'Less Than 8 ft.', 'shot_zone_range'] = 0

# transform game_date to date time object
# kobe_data_encoded['game_date'] = pd.to_numeric(kobe_data_encoded['game_date'].str.replace('-',''))

kobe_data_encoded.head()
然后我使用
MinMaxScaler
缩放了数据:

# scaling
min_max_scaler = preprocessing.MinMaxScaler()
scaled_features_df = kobe_data_encoded.copy()
column_names = ['loc_x', 'loc_y', 'minutes_remaining', 'period',
                'seconds_remaining', 'shot_distance', 'shot_type', 'shot_zone_range']
scaled_features = min_max_scaler.fit_transform(scaled_features_df[column_names])
scaled_features_df[column_names] = scaled_features
并按
季节
年份
月份
进行分组,如上所述:

seasons_date = scaled_features_df.groupby(['season', 'year', 'month'])
我的任务是使用
KFold
使用
roc_auc
得分来找到最佳的K。
以下是我的实现:

neighbors = [x for x in range(1,50) if x % 2 != 0]
cv_scores = []
for k in neighbors:
    print('k: ', k)
    knn = KNeighborsClassifier(n_neighbors=k, n_jobs=-1)
    scores = []
    accumelated_X = pd.DataFrame()
    accumelated_y = pd.Series()
    for group_name, group in seasons_date:
        print(group_name)
        group = group.drop(columns=['season', 'year', 'month'])
        not_classified_df = group[group['shot_made_flag'].isnull()]
        classified_df = group[group['shot_made_flag'].notnull()]

        X = classified_df.drop(columns=['shot_made_flag'])
        y = classified_df['shot_made_flag']
        accumelated_X = pd.concat([accumelated_X, X])
        accumelated_y = pd.concat([accumelated_y, y])
        cv = StratifiedKFold(n_splits=10, shuffle=True)
        scores.append(cross_val_score(knn, accumelated_X, accumelated_y, cv=cv, scoring='roc_auc'))
    cv_scores.append(scores.mean())

#graphical view
#misclassification error
MSE = [1-x for x in cv_scores]
#optimal K
optimal_k_index = MSE.index(min(MSE))
optimal_k = neighbors[optimal_k_index]
print(optimal_k)
# plot misclassification error vs k
plt.plot(neighbors, MSE)
plt.xlabel('Number of Neighbors K')
plt.ylabel('Misclassification Error')
plt.show()
我不确定在这种情况下是否正确处理了数据泄漏问题 因为如果我积累上一季的数据,然后将其传递给
cross_val_score
我可能会出现数据泄漏,因为cv可以以一种方式分割数据,即它所拟合的新季数据和测试上一季数据,我就在这里吗? 如果是这样的话,我想知道如何处理这种情况,即我想使用
K-Fold
找到最佳
K
,使用此定时数据而不发生数据泄漏。
使用
K-Fold
分割数据,而不是按游戏日期分割以避免数据泄漏是否明智?

简而言之,由于您想处理类似于时间序列的事情,您不能使用标准的K-Fold交叉验证

你会使用一些来自未来的数据来预测过去,这是被禁止的

您可以在这里找到一个很好的方法:

其中数字按数据时间的时间顺序排列

fold 1 : training [1], test [2]
fold 2 : training [1 2], test [3]
fold 3 : training [1 2 3], test [4]
fold 4 : training [1 2 3 4], test [5]
fold 5 : training [1 2 3 4 5], test [6]