-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_feature_generation.py
325 lines (216 loc) · 9.76 KB
/
state_feature_generation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# This scripts collects soccer logs for one team as expert from Wyscout,
# transforms to SPADL format,
# and exports state features for each action.
import tensorflow as tf
print(tf.__version__)
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
# fix random seed for reproducibility
numpy.random.seed(7)
import numpy
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
# fix random seed for reproducibility
numpy.random.seed(7)
from sklearn.model_selection import train_test_split
from tqdm.notebook import tqdm
!pip install matplotsoccer
!pip install tables==3.6.1
!pip install socceraction
import numpy as np
import pandas as pd # 1.0.3
import matplotsoccer
from ipywidgets import interact_manual, fixed, widgets # 7.5.1
from io import BytesIO
from pathlib import Path
from tqdm.notebook import tqdm
from urllib.parse import urlparse
from urllib.request import urlopen, urlretrieve
from zipfile import ZipFile, is_zipfile
import pandas as pd # version 1.0.3
from sklearn.metrics import brier_score_loss, roc_auc_score # version 0.22.2
from xgboost import XGBClassifier # version 1.0.2
import socceraction.vaep.features as features
import socceraction.vaep.labels as labels
from socceraction.spadl.wyscout import convert_to_spadl
from socceraction.vaep.formula import value
pip install socceraction==0.2.0
#Download Wyscout dataset
data_files = {
'events': 'https://ndownloader.figshare.com/files/14464685', # ZIP file containing one JSON file for each competition
'matches': 'https://ndownloader.figshare.com/files/14464622', # ZIP file containing one JSON file for each competition
'players': 'https://ndownloader.figshare.com/files/15073721', # JSON file
'teams': 'https://ndownloader.figshare.com/files/15073697' # JSON file
}
for url in tqdm(data_files.values()):
url_s3 = urlopen(url).geturl()
path = Path(urlparse(url_s3).path)
file_name = path.name
file_local, _ = urlretrieve(url_s3, file_name)
if is_zipfile(file_local):
with ZipFile(file_local) as zip_file:
zip_file.extractall()
def read_json_file(filename):
with open(filename, 'rb') as json_file:
return BytesIO(json_file.read()).getvalue().decode('unicode_escape')
json_teams = read_json_file('teams.json')
df_teams = pd.read_json(json_teams)
df_teams1= df_teams.to_hdf('wyscout.h5', key='teams', mode='w')
df_teams
df_teams.to_hdf('wyscout.h5', key='teams', mode='w')
json_players = read_json_file('players.json')
df_players = pd.read_json(json_players)
#df_players
df_players.to_hdf('wyscout.h5', key='players', mode='a')
# Remove comments for the interested leagues
competitions = [
# 'England',
# 'France',
'Germany',
# 'Italy',
# 'Spain',
# 'European Championship',
# 'World Cup'
]
dfs_matches = []
for competition in competitions:
competition_name = competition.replace(' ', '_')
file_matches = f'matches_{competition_name}.json'
json_matches = read_json_file(file_matches)
df_matches = pd.read_json(json_matches)
dfs_matches.append(df_matches)
df_matches = pd.concat(dfs_matches)
#df_matches
df_matches.to_hdf('wyscout.h5', key='matches', mode='a')
for competition in competitions:
competition_name = competition.replace(' ', '_')
file_events = f'events_{competition_name}.json'
json_events = read_json_file(file_events)
df_events = pd.read_json(json_events)
df_events_matches = df_events.groupby('matchId', as_index=False)
for match_id, df_events_match in df_events_matches:
df_events_match.to_hdf('wyscout.h5', key=f'events/match_{match_id}', mode='a')
#df_events
df_teams
convert_to_spadl('wyscout.h5', 'spadl.h5')
df_games = pd.read_hdf('spadl.h5', key='games')
df_actiontypes = pd.read_hdf('spadl.h5', key='actiontypes')
df_bodyparts = pd.read_hdf('spadl.h5', key='bodyparts')
df_results = pd.read_hdf('spadl.h5', key='results')
df_teams = pd.read_hdf('spadl.h5', key='teams')
df_players = pd.read_hdf('spadl.h5', key='players')
df_games = pd.read_hdf('spadl.h5', key='games')
team_name_mapping = df_teams.set_index('team_id')['team_name'].to_dict()
df_games['home_team_name'] = df_games['home_team_id'].map(team_name_mapping)
df_games['away_team_name'] = df_games['away_team_id'].map(team_name_mapping)
# imports all Bayern München games:
expert_games= df_games[(df_games['home_team_name'] == 'FC Bayern München') |
(df_games['away_team_name'] == 'FC Bayern München')
]
expert_games.shape
expert_games_ids= list(set(expert_games['game_id']))
len(expert_games_ids)
expert_df_events=[]
for game_id in expert_games_ids:
with pd.HDFStore('spadl.h5') as spadlstore:
df_actions = spadlstore[f'actions/game_{game_id}']
df_actions = (
df_actions.merge(spadlstore['actiontypes'], how='left')
.merge(spadlstore['results'], how='left')
.merge(spadlstore['bodyparts'], how='left')
.merge(spadlstore['players'], how="left")
.merge(spadlstore['teams'], how='left')
.reset_index()
.rename(columns={'index': 'action_id'})
)
expert_df_events.append(df_actions)
expert_actions= pd.concat(expert_df_events)
expert_actions
expert_actions.columns
list(set(expert_actions['short_team_name']))
def nice_time(row):
minute = int((row['period_id']>=2) * 45 + (row['period_id']>=3) * 15 +
(row['period_id']==4) * 15 + row['time_seconds'] // 60)
second = int(row['time_seconds'] % 60)
return f'{minute}m{second}s'
expert_actions['nice_time'] = expert_actions.apply(nice_time,axis=1)
end_first_half = expert_actions[expert_actions.period_id == 1][['game_id','time_seconds']].groupby('game_id', as_index=False).max()
end_first_half
end_second_half = expert_actions[expert_actions.period_id == 2][['game_id','time_seconds']].groupby('game_id', as_index=False).max()
end_second_half
expert_actions[expert_actions.period_id== 2]
expert_actions= pd.merge(expert_actions, end_first_half[['game_id','time_seconds']].rename(columns={'time_seconds':'half_max_second'}), on='game_id')
expert_actions= pd.merge(expert_actions, end_second_half[['game_id','time_seconds']].rename(columns={'time_seconds':'2_half_max_second'}), on='game_id')
expert_actions.columns
# time remaining feature
def time_remaining(row):
if row['period_id']==1:
return int(row['half_max_second']) - int(row['time_seconds'])
if row['period_id']==2:
return int(row['2_half_max_second']) - int(row['time_seconds'])
expert_actions['time_remaining'] = expert_actions.apply(time_remaining,axis=1)
def action_name(row):
return f"{row['action_id']}: {row['nice_time']} - {row['short_name']} {row['type_name']}"
expert_actions['action_name'] = expert_actions.apply(action_name, axis=1)
PITCH_LENGTH = 105
PITCH_WIDTH = 68
for side in ['start', 'end']:
# Normalize the X location
key_x = f'{side}_x'
expert_actions[f'{key_x}_norm'] = expert_actions[key_x] / PITCH_LENGTH
# Normalize the Y location
key_y = f'{side}_y'
expert_actions[f'{key_y}_norm'] = expert_actions[key_y] / PITCH_WIDTH
GOAL_X = PITCH_LENGTH
GOAL_Y = PITCH_WIDTH / 2
for side in ['start', 'end']:
diff_x = GOAL_X - expert_actions[f'{side}_x']
diff_y = abs(GOAL_Y - expert_actions[f'{side}_y'])
expert_actions[f'{side}_distance_to_goal'] = np.sqrt(diff_x ** 2 + diff_y ** 2)
expert_actions[f'{side}_angle_to_goal'] = np.divide(diff_x, diff_y,
out=np.zeros_like(diff_x),
where=(diff_y != 0))
pd.get_dummies(expert_actions['type_name'])
def add_action_type_dummies(df_actions):
return df_actions.merge(pd.get_dummies(df_actions['type_name']), how='left',
left_index=True, right_index=True)
expert_actions = add_action_type_dummies(expert_actions)
def add_distance_features(df_actions):
df_actions['diff_x'] = df_actions['end_x'] - df_actions['start_x']
df_actions['diff_y'] = df_actions['end_y'] - df_actions['start_y']
df_actions['distance_covered'] = np.sqrt((df_actions['end_x'] - df_actions['start_x']) ** 2 +
(df_actions['end_y'] - df_actions['start_y']) ** 2)
def add_time_played(df_actions):
df_actions['time_played'] = (df_actions['time_seconds'] +
(df_actions['period_id'] >= 2) * (45 * 60) +
(df_actions['period_id'] >= 3) * (15 * 60) +
(df_actions['period_id'] == 4) * (15 * 60)
)
add_distance_features(expert_actions)
add_time_played(expert_actions)
expert_actions.shape
expert_actions.to_excel('expert_actions.xlsx')
from google.colab import files
expert_actions.to_excel('expert_actions.xlsx')
#files.download("data.csv")
files.download("expert_actions.xlsx")
expert_actions.columns
# generate state features
df_features=expert_actions[['period_id','bodypart_id','type_id', 'result_id','start_x_norm', 'start_y_norm', 'end_x_norm', 'end_y_norm',
'start_distance_to_goal', 'start_angle_to_goal', 'end_distance_to_goal',
'end_angle_to_goal', 'clearance', 'corner_crossed', 'corner_short', 'cross', 'dribble',
'foul', 'freekick_crossed', 'freekick_short', 'goalkick',
'interception', 'keeper_save', 'pass', 'shot', 'shot_freekick',
'shot_penalty', 'tackle', 'take_on', 'throw_in', 'diff_x', 'diff_y',
'distance_covered', 'time_played', 'time_remaining' ]]
df_features
df_features.to_excel('expert_features.xlsx')
files.download("expert_features.xlsx")