-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredictiveModelFinal.py
More file actions
342 lines (249 loc) · 10.8 KB
/
predictiveModelFinal.py
File metadata and controls
342 lines (249 loc) · 10.8 KB
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
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
import matplotlib.pyplot as plt
import math
import statsmodels.api as sm
from statsmodels.stats import diagnostic as diag
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
#Return home and away score from a single cell
def splitScore(score):
index = 0
for ele in score:
if ele == "-":
break
else:
index+=1
home = int(score[:index])
away = int(score[index+1:])
return (home,away)
#Used to get the current 20 teams in a particular season
#3 teams are relegated at the end so the three new teams
# are included each season
def teamsx(df):
teams = []
for index, row in df.iterrows():
homeT =row["HomeTeam"].replace(" ", "")
AwayT = row["AwayTeam"].replace(" ", "")
if ( homeT not in teams):
teams.append(homeT)
if(AwayT not in teams):
teams.append(AwayT)
if len(teams) == 20:
break
return teams
#check to see if a team is in a given row of a data frame
def teamInRow(team,row):
if team == row["HomeTeam"].replace(" ", ""):
return True
if team == row["AwayTeam"].replace(" ", ""):
return True
else:
return False
# check to see if a team is home team
def isHomeTeam(team,row):
if team == row["HomeTeam"].replace(" ", ""):
return True
else:
return False
#check to see if a team is an away team
def isAwayTeam(team,row):
if team == row["AwayTeam"].replace(" ", ""):
return True
else:
return False
#check to see if a team has one a game
# in the current row of the data frame
def isWin(team,row):
#print(row["FTR"].replace(" ", ""))
if isAwayTeam(team,row) and row["FTR"].replace(" ", "")== "A":
return True
if isHomeTeam(team,row) and row["FTR"].replace(" ", "")== "H":
return True
else:
return False
#check to see if a team has lost
# the current game(r0w) in the data frame
def isLost(team, row):
if isAwayTeam(team,row) and row["FTR"].replace(" ", "")== "H":
return True
if isHomeTeam(team,row) and row["FTR"].replace(" ", "")== "A":
return True
else:
return False
#check if a game is a draw
def isDraw(team,row):
return (not isLost(team,row)) and (not isWin(team,row))
# Returns a list of data frame for each team
# each data frame contains a particular teams stat of:
#wins losses draws away-victories tophalfvictories
#and bottom half victories
def progressionTables(teams,df,topHalf,bottomHalf):
tables = []
indexCount = 0
for team in teams:
index = []
data = ({'Points':[],
'AwayVictories':[],
'TopHalfVictories':[],
"BottomHalfVictories":[],
"Wins":[],
"Loss":[],
"Draws":[]},
index)
pts, aw, thv, bhv, wins, loss, draws = 0,0,0,0,0,0,0
for index, row in df.iterrows():
if teamInRow(team,row):
data[1].append(indexCount)
indexCount+=1
if isWin(team,row):
pts+=3
wins+=1
data[0]["Points"].append(pts)
data[0]["Wins"].append(wins)
else:
data[0]["Wins"].append(wins)
if isDraw(team,row):
pts+=1
draws+=1
data[0]["Points"].append(pts)
data[0]["Draws"].append(draws)
else:
data[0]["Draws"].append(draws)
if isLost(team,row):
pts+=0
loss+=1
data[0]["Points"].append(pts)
data[0]["Loss"].append(loss)
else:
data[0]["Loss"].append(loss)
if isAwayTeam(team,row) and isWin(team,row):
aw+=1
data[0]["AwayVictories"].append(aw)
else:
data[0]["AwayVictories"].append(aw)
if isWin(team,row) and isAwayTeam(team,row) and row["HomeTeam"].replace(" ", "") in topHalf :
thv+=1
data[0]["TopHalfVictories"].append(thv)
elif isWin(team,row) and isHomeTeam(team,row) and row["AwayTeam"].replace(" ", "") in topHalf :
thv+=1
data[0]["TopHalfVictories"].append(thv)
else:
data[0]["TopHalfVictories"].append(thv)
if isWin(team,row) and isAwayTeam(team,row) and row["HomeTeam"].replace(" ", "") in bottomHalf :
bhv+=1
data[0]["BottomHalfVictories"].append(bhv)
elif isWin(team,row) and isHomeTeam(team,row) and row["AwayTeam"].replace(" ", "") in bottomHalf :
bhv+=1
data[0]["BottomHalfVictories"].append(bhv)
else:
data[0]["BottomHalfVictories"].append(bhv)
tables.append(pd.DataFrame(data=data[0],index=data[1]))
#tables.append(data)
#pd.DataFrame(data=data)
return tables
def main():
#Teams of the current season broken up into top and bottom half based on
#their historical positon between 1-10 and 11-20
topHalf1 = ['ManUnited', 'Leicester', 'Bournemouth',
'Chelsea', 'Tottenham',
'Wolves', 'Everton', 'Arsenal', 'ManCity', 'Liverpool']
bottomHalf1 = [ 'Cardiff', 'Fulham','CrystalPalace',
'Huddersfield', 'Newcastle', 'Watford',
'Brighton', 'WestHam','Southampton', 'Burnley']
#--------------------------------------------------------------------------
#Teams of the current season broken up into top and bottom half based on
#their historical positon between 1-10 and 11-20
topHalf2 = ['Arsenal', 'Leicester', 'ManCity',
'Chelsea', 'CrystalPalace', 'Everton',
'Liverpool', 'Bournemouth', 'ManUnited',
'Tottenham']
bottomHalf2 = ['Brighton', 'Burnley', 'CrystalPalace', 'Huddersfield',
'Stoke', 'Southampton', 'Swansea', 'Watford', 'WestBrom',
'WestHam', 'Newcastle', ]
#--------------------------------------------------------------------------
#Teams of the current season broken up into top and bottom half based on
#their historical positon between 1-10 and 11-20
topHalf3 = ['Everton', 'Tottenham', 'Leicester', 'ManCity',
'Southampton', 'Arsenal', 'Liverpool', 'ManUnited',
'Chelsea', 'WestHam']
bottomHalf3 = ['Burnley', 'Swansea', 'CrystalPalace', 'WestBrom',
'Hull', 'Sunderland', 'Middlesbrough', 'Stoke',
'Watford', 'Bournemouth',]
#--------------------------------------------------------------------------
#Teams of the current season broken up into top and bottom half based on
#their historical positon between 1-10 and 11-20
topHalf4 = [ 'Chelsea', 'Swansea', 'ManUnited', 'Tottenham',
'CrystalPalace', 'Arsenal', 'Southampton', 'Stoke',
'Liverpool', 'ManCity']
bottomHalf4 = ['Bournemouth', 'AstonVilla', 'Everton', 'Watford',
'Leicester', 'Sunderland', 'Norwich', 'WestHam',
'Newcastle', 'WestBrom']
#loading csv files into pandas data frame
seasonResultDF = pd.read_csv("season-1819_csv.csv")
seasonResultDF2 = pd.read_csv("season-1718_csv.csv")
seasonResultDF3 = pd.read_csv("season-1617_csv.csv")
seasonResultDF4 = pd.read_csv("season-1516_csv.csv")
#Retrieving the teams for each season
teams = teamsx(seasonResultDF)
teams2 = teamsx(seasonResultDF2)
teams3 = teamsx(seasonResultDF3)
teams4 = teamsx(seasonResultDF4)
# Loading the various derived stats from the first pandas data from
#into another data frame
dfs1819 = progressionTables(teams,seasonResultDF,topHalf1,bottomHalf1)
dfs1718 = progressionTables(teams2,seasonResultDF2,topHalf2,bottomHalf2)
dfs1617 = progressionTables(teams3,seasonResultDF3,topHalf3,bottomHalf3)
dfs1516 = progressionTables(teams4,seasonResultDF4,topHalf4,bottomHalf4)
#The above were list of pandas data frame
#concatenating them into one large data frame
#for each season
allData1819 = pd.concat(dfs1819)
allData1718 = pd.concat(dfs1718)
allData1617 = pd.concat(dfs1617)
allData1516 = pd.concat(dfs1516)
#creating the training data from all seasons except for 18/19
trainingData = allData1516
trainingData = trainingData.append(allData1617,ignore_index=True)
trainingData = trainingData.append(allData1718,ignore_index=True)
#test data. In a dictionary form as each team has the own data frame
#for their own performance for the 18/19 season
Season1819TestX = {k:v.drop("Points", axis = 1) for (k,v) in zip(teams, dfs1819)}
Season1819TestY = {k:v[["Points"]] for (k,v) in zip(teams, dfs1819)}
#--------------------------------------------------------------------------
#Season1819TestY = {k:v[["Points"]] for (k,v) in zip(teams, dfs1819)}
#dropping the unecessary column so only my independent columns of
# away victory, topHalf victories and bottom half victories remain
newXTrain = trainingData.drop(["Points","Wins","Loss","Draws"], axis = 1)
newXTest = allData1819.drop(["Points","Wins","Loss","Draws"], axis = 1)
YTrain = trainingData[["Points"]]
#creating regression model
regressionModel = LinearRegression()
#fit model
regressionModel.fit(newXTrain,YTrain)
#Printing each teams predicted performance for the 18/19
#season using 19/18 x values
for k in Season1819TestX:
print("The current team is: " + k)
#print(Season1819TestX[k])
y_Predict = regressionModel.predict(Season1819TestX[k].drop(["Wins","Loss","Draws"], axis = 1))
print(y_Predict[37:38], "is the predicted final points after the last match of the season")
print()
# calculate the mean squared error
model_mse = mean_squared_error(Season1819TestY[k], y_Predict)
# calculate the mean absolute error
model_mae = mean_absolute_error(Season1819TestY[k], y_Predict)
# calulcate the root mean squared error
model_rmse = math.sqrt(model_mse)
# display the output
print("MSE {:.3}".format(model_mse))
print("MAE {:.3}".format(model_mae))
print("RMSE {:.3}".format(model_rmse))
print()
print()
if __name__ == '__main__':
main()