-
Notifications
You must be signed in to change notification settings - Fork 0
/
AI_hackathon_fifa_2018_prediction.py
425 lines (257 loc) · 10.3 KB
/
AI_hackathon_fifa_2018_prediction.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# coding: utf-8
# In[160]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker as ticker
import matplotlib.ticker as plticker
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# In[161]:
#load data
world_cup = pd.read_csv('datasets/World Cup 2018 Dataset.csv')
results = pd.read_csv('datasets/results.csv')
# In[162]:
results.head()
# In[163]:
results.head()
# In[164]:
#Adding goal difference and establishing who is the winner
winner_team = []
for i in range (len(results['home_team'])):
if results ['home_score'][i] > results['away_score'][i]:
winner_team.append(results['home_team'][i])
elif results['home_score'][i] < results ['away_score'][i]:
winner_team.append(results['away_team'][i])
else:
winner_team.append('Draw')
results['winning_team'] = winner_team
#adding goal difference column
results['goal_difference'] = np.absolute(results['home_score'] - results['away_score'])
results.head()
# In[165]:
#narrowing to team patcipating in the world cup
worldcup_teams = ['Australia', ' Iran', 'Japan', 'Korea Republic',
'Saudi Arabia', 'Egypt', 'Morocco', 'Nigeria',
'Senegal', 'Tunisia', 'Costa Rica', 'Mexico',
'Panama', 'Argentina', 'Brazil', 'Colombia',
'Peru', 'Uruguay', 'Belgium', 'Croatia',
'Denmark', 'England', 'France', 'Germany',
'Iceland', 'Poland', 'Portugal', 'Russia',
'Serbia', 'Spain', 'Sweden', 'Switzerland']
df_teams_home = results[results['home_team'].isin(worldcup_teams)]
df_teams_away = results[results['away_team'].isin(worldcup_teams)]
df_teams = pd.concat((df_teams_home, df_teams_away))
df_teams.drop_duplicates()
df_teams.count()
# In[166]:
df_teams.head()
# In[167]:
#create an year column to drop games before 1930
year = []
for row in df_teams['date']:
year.append(int(row[:4]))
df_teams['match_year'] = year
df_teams.head()
# In[168]:
#dropping columns that wll not affect matchoutcomes
df_teams_req_cols = df_teams.drop(['date', 'home_score', 'away_score', 'tournament', 'city', 'country', 'goal_difference', 'match_year'], axis=1)
df_teams_req_cols.head()
# In[169]:
#Building the model
#categorize wining team to numerical category if home team wins : 2, draw : 1, away team wins : 0
df_teams_req_cols = df_teams_req_cols.reset_index(drop=True)
df_teams_req_cols.loc[df_teams_req_cols.winning_team == df_teams_req_cols.home_team,'winning_team']=2
df_teams_req_cols.loc[df_teams_req_cols.winning_team == 'Draw', 'winning_team']=1
df_teams_req_cols.loc[df_teams_req_cols.winning_team == df_teams_req_cols.away_team, 'winning_team']=0
df_teams_req_cols.head()
# In[170]:
#convert teams from categorical variables to continous inputs
final = pd.get_dummies(df_teams_req_cols, prefix=['home_team', 'away_team'], columns=['home_team', 'away_team'])
# Separate X and y sets
X = final.drop(['winning_team'], axis=1)
y = final["winning_team"]
y = y.astype('int')
# Separate train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=50)
# In[171]:
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
score = logreg.score(X_train, y_train)
score2 = logreg.score(X_test, y_test)
print("Training set accuracy: ", '%.3f'%(score))
print("Test set accuracy: ", '%.3f'%(score2))
# In[172]:
#if any of team is having higher fifa ranking will be considered as home team, else away team
# Loading new datasets
fifa_rankings = pd.read_csv('datasets/fifa_rankings.csv')
fixtures = pd.read_csv('datasets/fixtures.csv')
pred_set = []
# In[173]:
# Creating ranking column for each team
fixtures.insert(1, 'first_ranking', fixtures['Home Team'].map(fifa_rankings.set_index('Team')['Position']))
fixtures.insert(2, 'second_ranking', fixtures['Away Team'].map(fifa_rankings.set_index('Team')['Position']))
fixtures.head()
# In[174]:
#based on ranking of each team, mark it as home team and away team
for index, row in fixtures.iterrows():
if row['first_ranking'] < row['second_ranking']:
pred_set.append({'home_team': row['Home Team'], 'away_team': row['Away Team'], 'winning_team': None})
else:
pred_set.append({'home_team': row['Away Team'], 'away_team': row['Home Team'], 'winning_team': None})
pred_set = pd.DataFrame(pred_set)
duplicate_pred_set = pred_set
pred_set.head()
# In[175]:
# convert home and away team to continous variable
pred_set = pd.get_dummies(pred_set, prefix=['home_team', 'away_team'], columns=['home_team', 'away_team'])
# Add missing columns compared to the model's training dataset
missing_cols = set(final.columns) - set(pred_set.columns)
for c in missing_cols:
pred_set[c] = 0
pred_set = pred_set[final.columns]
# dropping winning team column
pred_set = pred_set.drop(['winning_team'], axis=1)
pred_set.head()
# In[176]:
#group matches
predictions = logreg.predict(pred_set)
for i in range(fixtures.shape[0]):
print(duplicate_pred_set.iloc[i, 1] + " and " + duplicate_pred_set.iloc[i, 0])
if predictions[i] == 2:
print("Winner: " + duplicate_pred_set.iloc[i, 1])
elif predictions[i] == 1:
print("Draw")
elif predictions[i] == 0:
print("Winner: " + duplicate_pred_set.iloc[i, 0])
print('Probability of ' + duplicate_pred_set.iloc[i, 1] + ' winning: ', '%.3f'%(logreg.predict_proba(pred_set)[i][2]))
print('Probability of Draw: ', '%.3f'%(logreg.predict_proba(pred_set)[i][1]))
print('Probability of ' + duplicate_pred_set.iloc[i, 0] + ' winning: ', '%.3f'%(logreg.predict_proba(pred_set)[i][0]))
print("")
# In[177]:
# List of tuples before
teams_16 = [('Uruguay', 'Portugal'),
('France', 'Croatia'),
('Brazil', 'Mexico'),
('England', 'Colombia'),
('Spain', 'Russia'),
('Argentina', 'Peru'),
('Germany', 'Switzerland'),
('Poland', 'Belgium')]
# In[178]:
def clean_and_predict (matches, ranking, final, logreg):
# Initialization of auxiliary list for data cleaning
positions = []
# Loop to retrieve each team's position according to FIFA ranking
for match in matches:
positions.append(ranking.loc[ranking['Team'] == match[0],'Position'].iloc[0])
positions.append(ranking.loc[ranking['Team'] == match[1],'Position'].iloc[0])
# Creating the DataFrame for prediction
pred_set = []
# Initializing iterators for while loop
i = 0
j = 0
# 'i' will be the iterator for the 'positions' list, and 'j' for the list of matches (list of tuples)
while i < len(positions):
dict1 = {}
# If position of first team is better, he will be the 'home' team, and vice-versa
if positions[i] < positions[i + 1]:
dict1.update({'home_team': matches[j][0], 'away_team': matches[j][1]})
else:
dict1.update({'home_team': matches[j][1], 'away_team': matches[j][0]})
# Append updated dictionary to the list, that will later be converted into a DataFrame
pred_set.append(dict1)
i += 2
j += 1
# Convert list into DataFrame
pred_set = pd.DataFrame(pred_set)
backup_pred_set = pred_set
# Get dummy variables and drop winning_team column
pred_set = pd.get_dummies(pred_set, prefix=['home_team', 'away_team'], columns=['home_team', 'away_team'])
# Add missing columns compared to the model's training dataset
missing_cols2 = set(final.columns) - set(pred_set.columns)
for c in missing_cols2:
pred_set[c] = 0
pred_set = pred_set[final.columns]
# Remove winning team column
pred_set = pred_set.drop(['winning_team'], axis=1)
# Predict!
predictions = logreg.predict(pred_set)
for i in range(len(pred_set)):
print(backup_pred_set.iloc[i, 1] + " and " + backup_pred_set.iloc[i, 0])
if predictions[i] == 2:
print("Winner: " + backup_pred_set.iloc[i, 1])
elif predictions[i] == 1:
print("Draw")
elif predictions[i] == 0:
print("Winner: " + backup_pred_set.iloc[i, 0])
print('Probability of ' + backup_pred_set.iloc[i, 1] + ' winning: ' , '%.3f'%(logreg.predict_proba(pred_set)[i][2]))
print('Probability of Draw: ', '%.3f'%(logreg.predict_proba(pred_set)[i][1]))
print('Probability of ' + backup_pred_set.iloc[i, 0] + ' winning: ', '%.3f'%(logreg.predict_proba(pred_set)[i][0]))
print("")
# In[179]:
clean_and_predict(teams_16, fifa_rankings, final, logreg)
# In[180]:
# List of matches
quarters = [('Portugal', 'France'),
('Spain', 'Argentina'),
('Brazil', 'England'),
('Germany', 'Belgium')]
# In[181]:
clean_and_predict (quarters, fifa_rankings, final, logreg)
# In[182]:
# List of matches
semi = [('Portugal', 'Brazil'),
('Argentina', 'Germany')]
# In[183]:
clean_and_predict (semi, fifa_rankings, final, logreg)
# In[184]:
# Finals# Finals
finals = [('Brazil', 'Germany')]
# In[185]:
clean_and_predict(finals, fifa_rankings, final, logreg)
# In[186]:
top_16 = []
top_16_players = pd.DataFrame()
for team in teams_16:
top_16.append(team[0])
top_16.append(team[1])
top_16_players['16 players'] = top_16
top_16_players.head()
# In[187]:
top_quarters = []
top_quarters_players = pd.DataFrame()
for team in quarters:
top_quarters.append(team[0])
top_quarters.append(team[1])
top_quarters_players['quarterfinal'] = top_quarters
top_quarters_players.head()
# In[188]:
top_semi = []
top_semi_players = pd.DataFrame()
for team in semi:
top_semi.append(team[0])
top_semi.append(team[1])
top_semi_players['semifinal'] = top_semi
top_semi_players.head()
# In[189]:
top_finals = []
top_finals_players = pd.DataFrame()
for team in finals:
top_finals.append(team[0])
top_finals.append(team[1])
top_finals_players['final'] = top_finals
top_finals_players.head()
# In[190]:
winner_team=['Brazil']
winner_df = pd.DataFrame()
winner_df['winner'] = winner_team
winner_df.head(10)
# In[191]:
del fifa_result
fifa_result=pd.DataFrame()
fifa_result = pd.concat([top_16_players,top_quarters_players,top_semi_players,top_finals_players,winner_df],axis = 1)
fifa_result.head(16)
# In[193]:
fifa_result.to_csv('Football_cup_submission.csv.', sep=',',na_rep='',index=False)