-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
523 lines (443 loc) · 25.1 KB
/
main.py
File metadata and controls
523 lines (443 loc) · 25.1 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
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import sqlite3 as sq3
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, precision_recall_fscore_support, confusion_matrix, log_loss
from sklearn.utils import class_weight
import numpy as np
import joblib
from tqdm import tqdm
from datetime import datetime
import random
# --- Constants ---
DATABASE_PATH = "database.sqlite"
ROLLING_WINDOW_SIZE = 5
ELO_K_FACTOR = 30
INITIAL_ELO = 1500
CLASSIFIER_EPOCHS = 300
REGRESSOR_EPOCHS = 300
LEARNING_RATE = 0.01
DROPOUT_RATE = 0.2
TRAIN_TEST_SPLIT_RATIO = 0.8
# --- Team Name Aliases ---
# Included here to make the script self-contained
team_name_aliases = {
'manchester united': 'Manchester United',
'man utd': 'Manchester United',
'man city': 'Manchester City',
'manchester city': 'Manchester City',
'real madrid': 'Real Madrid CF',
'barcelona': 'FC Barcelona',
'bayern munich': 'FC Bayern München',
'bayern': 'FC Bayern München',
'psg': 'Paris Saint-Germain',
'chelsea': 'Chelsea',
'arsenal': 'Arsenal',
'liverpool': 'Liverpool',
'juventus': 'Juventus',
'inter': 'Internazionale',
'milan': 'Milan'
}
# --- Model Definitions (Best Practice) ---
class ClassificationModel(nn.Module):
def __init__(self, num_features, num_classes, dropout_rate=DROPOUT_RATE):
super(ClassificationModel, self).__init__()
self.layers = nn.Sequential(
nn.Linear(num_features, 128),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(128, 64),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(64, num_classes)
)
def forward(self, x):
return self.layers(x)
class GoalRegressionModel(nn.Module):
def __init__(self, num_features, dropout_rate=DROPOUT_RATE):
super(GoalRegressionModel, self).__init__()
self.layers = nn.Sequential(
nn.Linear(num_features, 128),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(128, 64),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(64, 2) # Output for home and away goals
)
def forward(self, x):
return self.layers(x)
# --- Main Application Logic ---
def main():
with sq3.connect(DATABASE_PATH) as connect:
matches = pd.read_sql_query("""
SELECT
match_api_id,
home_team_api_id,
away_team_api_id,
home_team_goal,
away_team_goal,
season,
date
FROM Match
WHERE home_team_goal IS NOT NULL AND away_team_goal IS NOT NULL
ORDER BY date ASC;
""", connect)
matches['date'] = pd.to_datetime(matches['date'])
matches['result'] = matches.apply(
lambda row: 0 if row['home_team_goal'] > row['away_team_goal']
else 1 if row['home_team_goal'] == row['away_team_goal']
else 2, axis=1
)
team_attrs = pd.read_sql_query("SELECT * FROM Team_Attributes", connect)
team_attrs['date'] = pd.to_datetime(team_attrs['date'])
team_names_df = pd.read_sql_query("SELECT team_api_id, team_long_name FROM Team", connect)
selected_static_features = [
'buildUpPlaySpeed', 'buildUpPlayPassing',
'chanceCreationPassing', 'chanceCreationShooting',
'defencePressure', 'defenceAggression'
]
def create_match_rolling_features(matches_df, window_size=ROLLING_WINDOW_SIZE):
matches_with_features = matches_df.copy()
matches_with_features = matches_with_features.sort_values('date').reset_index(drop=True)
all_match_features = []
team_stats_history = {}
for idx, match in tqdm(matches_with_features.iterrows(), total=len(matches_with_features), desc="Creating Rolling Features"):
home_team = match['home_team_api_id']
away_team = match['away_team_api_id']
if home_team not in team_stats_history:
team_stats_history[home_team] = {'goals_scored': [], 'goals_conceded': [], 'wins': [], 'draws': [], 'losses': []}
if away_team not in team_stats_history:
team_stats_history[away_team] = {'goals_scored': [], 'goals_conceded': [], 'wins': [], 'draws': [], 'losses': []}
home_gs_avg = np.mean(team_stats_history[home_team]['goals_scored'][-window_size:]) if team_stats_history[home_team]['goals_scored'] else 0
home_gc_avg = np.mean(team_stats_history[home_team]['goals_conceded'][-window_size:]) if team_stats_history[home_team]['goals_conceded'] else 0
home_win_rate = np.mean(team_stats_history[home_team]['wins'][-window_size:]) if team_stats_history[home_team]['wins'] else 0.33
home_draw_rate = np.mean(team_stats_history[home_team]['draws'][-window_size:]) if team_stats_history[home_team]['draws'] else 0.33
home_loss_rate = np.mean(team_stats_history[home_team]['losses'][-window_size:]) if team_stats_history[home_team]['losses'] else 0.33
away_gs_avg = np.mean(team_stats_history[away_team]['goals_scored'][-window_size:]) if team_stats_history[away_team]['goals_scored'] else 0
away_gc_avg = np.mean(team_stats_history[away_team]['goals_conceded'][-window_size:]) if team_stats_history[away_team]['goals_conceded'] else 0
away_win_rate = np.mean(team_stats_history[away_team]['wins'][-window_size:]) if team_stats_history[away_team]['wins'] else 0.33
away_draw_rate = np.mean(team_stats_history[away_team]['draws'][-window_size:]) if team_stats_history[away_team]['draws'] else 0.33
away_loss_rate = np.mean(team_stats_history[away_team]['losses'][-window_size:]) if team_stats_history[away_team]['losses'] else 0.33
current_match_features = match.to_dict()
current_match_features.update({
'home_avg_goals_scored': home_gs_avg,
'home_avg_goals_conceded': home_gc_avg,
'home_win_rate': home_win_rate,
'home_draw_rate': home_draw_rate,
'home_loss_rate': home_loss_rate,
'away_avg_goals_scored': away_gs_avg,
'away_avg_goals_conceded': away_gc_avg,
'away_win_rate': away_win_rate,
'away_draw_rate': away_draw_rate,
'away_loss_rate': away_loss_rate,
})
all_match_features.append(current_match_features)
team_stats_history[home_team]['goals_scored'].append(match['home_team_goal'])
team_stats_history[home_team]['goals_conceded'].append(match['away_team_goal'])
team_stats_history[home_team]['wins'].append(1 if match['result'] == 0 else 0)
team_stats_history[home_team]['draws'].append(1 if match['result'] == 1 else 0)
team_stats_history[home_team]['losses'].append(1 if match['result'] == 2 else 0)
team_stats_history[away_team]['goals_scored'].append(match['away_team_goal'])
team_stats_history[away_team]['goals_conceded'].append(match['home_team_goal'])
team_stats_history[away_team]['wins'].append(1 if match['result'] == 2 else 0)
team_stats_history[away_team]['draws'].append(1 if match['result'] == 1 else 0)
team_stats_history[away_team]['losses'].append(1 if match['result'] == 0 else 0)
return pd.DataFrame(all_match_features)
def calculate_elo_ratings(matches_df, k=ELO_K_FACTOR, initial_elo=INITIAL_ELO):
elo_ratings = {team_id: initial_elo for team_id in pd.concat([matches_df['home_team_api_id'], matches_df['away_team_api_id']]).unique()}
elo_history = []
for index, match in tqdm(matches_df.iterrows(), total=len(matches_df), desc="Calculating Elo Ratings"):
home_team_id = match['home_team_api_id']
away_team_id = match['away_team_api_id']
home_goals = match['home_team_goal']
away_goals = match['away_team_goal']
R_home = elo_ratings.get(home_team_id, initial_elo)
R_away = elo_ratings.get(away_team_id, initial_elo)
E_home = 1 / (1 + 10 ** ((R_away - R_home) / 400))
E_away = 1 / (1 + 10 ** ((R_home - R_away) / 400))
if home_goals > away_goals:
S_home, S_away = 1, 0
elif home_goals == away_goals:
S_home, S_away = 0.5, 0.5
else:
S_home, S_away = 0, 1
elo_history.append({
'match_api_id': match['match_api_id'],
'date': match['date'],
'home_team_api_id': home_team_id,
'away_team_api_id': away_team_id,
'home_elo_before': R_home,
'away_elo_before': R_away
})
new_R_home = R_home + k * (S_home - E_home)
new_R_away = R_away + k * (S_away - E_away)
elo_ratings[home_team_id] = new_R_home
elo_ratings[away_team_id] = new_R_away
return pd.DataFrame(elo_history)
matches_with_rolling_features = create_match_rolling_features(matches)
elo_df = calculate_elo_ratings(matches)
final_matches = pd.merge(matches_with_rolling_features, elo_df[['match_api_id', 'home_elo_before', 'away_elo_before']],
on='match_api_id', how='left')
final_matches.rename(columns={'home_elo_before': 'home_team_elo',
'away_elo_before': 'away_team_elo'}, inplace=True)
final_matches['elo_difference'] = final_matches['home_team_elo'] - final_matches['away_team_elo']
team_attrs_sorted = team_attrs.sort_values('date')
temp_attrs_home = team_attrs_sorted[['team_api_id', 'date'] + selected_static_features].copy()
temp_attrs_home.rename(columns={'team_api_id': 'merge_team_api_id_home', 'date': 'attr_date_home'}, inplace=True)
temp_attrs_home.rename(columns={col: f'home_{col}' for col in selected_static_features}, inplace=True)
final_matches = pd.merge_asof(
final_matches,
temp_attrs_home,
left_on='date',
right_on='attr_date_home',
left_by='home_team_api_id',
right_by='merge_team_api_id_home',
direction='backward'
)
final_matches.drop(columns=['attr_date_home', 'merge_team_api_id_home'], inplace=True, errors='ignore')
temp_attrs_away = team_attrs_sorted[['team_api_id', 'date'] + selected_static_features].copy()
temp_attrs_away.rename(columns={'team_api_id': 'merge_team_api_id_away', 'date': 'attr_date_away'}, inplace=True)
temp_attrs_away.rename(columns={col: f'away_{col}' for col in selected_static_features}, inplace=True)
final_matches = pd.merge_asof(
final_matches,
temp_attrs_away,
left_on='date',
right_on='attr_date_away',
left_by='away_team_api_id',
right_by='merge_team_api_id_away',
direction='backward'
)
final_matches.drop(columns=['attr_date_away', 'merge_team_api_id_away'], inplace=True, errors='ignore')
if 'date_x' in final_matches.columns:
final_matches.rename(columns={'date_x': 'date'}, inplace=True)
if 'date_y' in final_matches.columns:
final_matches.drop(columns=['date_y'], inplace=True, errors='ignore')
final_matches.dropna(inplace=True)
feature_columns = [f'home_{col}' for col in selected_static_features] + \
[f'away_{col}' for col in selected_static_features] + \
['home_avg_goals_scored', 'home_avg_goals_conceded', 'home_win_rate', 'home_draw_rate', 'home_loss_rate',
'away_avg_goals_scored', 'away_avg_goals_conceded', 'away_win_rate', 'away_draw_rate', 'away_loss_rate',
'home_team_elo', 'away_team_elo', 'elo_difference']
final_matches = final_matches.sort_values('date').reset_index(drop=True)
split_idx = int(len(final_matches) * TRAIN_TEST_SPLIT_RATIO)
X_train_df = final_matches.iloc[:split_idx][feature_columns]
X_test_df_original = final_matches.iloc[split_idx:].copy()
X_test_df = X_test_df_original[feature_columns]
y_train_classification = final_matches.iloc[:split_idx]['result']
y_test_classification = final_matches.iloc[split_idx:]['result']
y_train_regression = final_matches.iloc[:split_idx][['home_team_goal', 'away_team_goal']]
y_test_regression = final_matches.iloc[split_idx:][['home_team_goal', 'away_team_goal']]
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train_df)
X_test_scaled = scaler.transform(X_test_df)
joblib.dump(scaler, "scaler_new_features.pkl")
X_train_tensor = torch.tensor(X_train_scaled, dtype=torch.float32)
X_test_tensor = torch.tensor(X_test_scaled, dtype=torch.float32)
y_train_classification_tensor = torch.tensor(y_train_classification.values, dtype=torch.long)
y_test_classification_tensor = torch.tensor(y_test_classification.values, dtype=torch.long)
y_train_regression_tensor = torch.tensor(y_train_regression.values, dtype=torch.float32)
y_test_regression_tensor = torch.tensor(y_test_regression.values, dtype=torch.float32)
num_features = X_train_tensor.shape[1]
num_classes = 3
# --- Train Classifier ---
classification_model = ClassificationModel(num_features, num_classes)
class_weights = class_weight.compute_class_weight(
class_weight='balanced',
classes=np.unique(y_train_classification_tensor.numpy()),
y=y_train_classification_tensor.numpy()
)
weights_tensor = torch.tensor(class_weights, dtype=torch.float32)
classification_loss_fn = nn.CrossEntropyLoss(weight=weights_tensor)
classification_optimizer = optim.Adam(classification_model.parameters(), lr=LEARNING_RATE)
for epoch in range(CLASSIFIER_EPOCHS):
classification_model.train()
preds = classification_model(X_train_tensor)
loss = classification_loss_fn(preds, y_train_classification_tensor)
classification_optimizer.zero_grad()
loss.backward()
classification_optimizer.step()
if epoch % 50 == 0 or epoch == CLASSIFIER_EPOCHS - 1:
print(f"[Classifier] Epoch {epoch}/{CLASSIFIER_EPOCHS}, Loss: {loss.item():.4f}")
torch.save(classification_model.state_dict(), "result_model_improved.pt")
# --- Evaluate Classifier ---
classification_model.eval()
with torch.no_grad():
test_preds_logits = classification_model(X_test_tensor)
predicted_classes = torch.argmax(test_preds_logits, dim=1)
accuracy = accuracy_score(y_test_classification.values, predicted_classes.numpy())
print(f"\n🔍 Classification Accuracy: {accuracy * 100:.2f}%")
precision, recall, f1, _ = precision_recall_fscore_support(
y_test_classification.values, predicted_classes.numpy(), average='weighted', zero_division=0
)
print(f"📊 Weighted Precision: {precision:.2f}, Recall: {recall:.2f}, F1-Score: {f1:.2f}")
cm = confusion_matrix(y_test_classification.values, predicted_classes.numpy())
print("\nConfusion Matrix (Actual vs. Predicted):")
print(cm)
test_preds_probs = torch.softmax(test_preds_logits, dim=1).numpy()
logloss = log_loss(y_test_classification.values, test_preds_probs)
print(f"📈 Log Loss: {logloss:.4f}")
# --- Train Regressor ---
goal_model = GoalRegressionModel(num_features)
goal_loss_fn = nn.MSELoss()
goal_optimizer = optim.Adam(goal_model.parameters(), lr=LEARNING_RATE)
for epoch in range(REGRESSOR_EPOCHS):
goal_model.train()
preds = goal_model(X_train_tensor)
loss = goal_loss_fn(preds, y_train_regression_tensor)
goal_optimizer.zero_grad()
loss.backward()
goal_optimizer.step()
if epoch % 50 == 0 or epoch == REGRESSOR_EPOCHS - 1:
print(f"[GoalRegressor] Epoch {epoch}/{REGRESSOR_EPOCHS}, Loss: {loss.item():.4f}")
torch.save(goal_model.state_dict(), "goal_model_improved.pt")
# --- Evaluate Regressor ---
goal_model.eval()
with torch.no_grad():
test_goal_preds = goal_model(X_test_tensor)
predicted_home_goals_eval = torch.round(test_goal_preds[:, 0]).int()
predicted_away_goals_eval = torch.round(test_goal_preds[:, 1]).int()
actual_home_goals = y_test_regression_tensor[:, 0].int()
actual_away_goals = y_test_regression_tensor[:, 1].int()
mae_home = torch.mean(torch.abs(predicted_home_goals_eval.float() - actual_home_goals.float())).item()
mae_away = torch.mean(torch.abs(predicted_away_goals_eval.float() - actual_away_goals.float())).item()
print(f"\n⚽ Goal Prediction MAE (Home): {mae_home:.2f}")
print(f"⚽ Goal Prediction MAE (Away): {mae_away:.2f}")
exact_score_accuracy = ((predicted_home_goals_eval == actual_home_goals) & (predicted_away_goals_eval == actual_away_goals)).float().mean().item()
print(f"🎯 Exact Scoreline Accuracy: {exact_score_accuracy * 100:.2f}%")
#=================================================================#
# INTERACTIVE PREDICTION PART #
#=================================================================#
def get_team_id_from_name(team_input_name, team_df, aliases):
standardized_name = team_input_name.lower()
if standardized_name in aliases:
db_name = aliases[standardized_name]
match = team_df[team_df['team_long_name'] == db_name]
if not match.empty:
return match['team_api_id'].values[0]
match = team_df[team_df['team_long_name'].str.lower() == standardized_name]
if not match.empty:
return match['team_api_id'].values[0]
return None
scaler_loaded = joblib.load("scaler_new_features.pkl")
classification_model_loaded = ClassificationModel(num_features, num_classes)
classification_model_loaded.load_state_dict(torch.load("result_model_improved.pt"))
classification_model_loaded.eval()
goal_model_loaded = GoalRegressionModel(num_features)
goal_model_loaded.load_state_dict(torch.load("goal_model_improved.pt"))
goal_model_loaded.eval()
def get_team_attributes_for_prediction(team_id, current_date):
latest_attrs = team_attrs[(team_attrs['team_api_id'] == team_id) & (team_attrs['date'] <= current_date)].sort_values('date', ascending=False)
if not latest_attrs.empty:
return latest_attrs[selected_static_features].iloc[0]
return None
def get_rolling_features_for_prediction(team_id, historical_matches_df, window_size=ROLLING_WINDOW_SIZE):
team_history = historical_matches_df[(historical_matches_df['home_team_api_id'] == team_id) | (historical_matches_df['away_team_api_id'] == team_id)].sort_values('date', ascending=False).head(window_size)
if team_history.empty:
return {'avg_goals_scored': 0, 'avg_goals_conceded': 0, 'win_rate': 0.33, 'draw_rate': 0.33, 'loss_rate': 0.33}
goals_scored, goals_conceded, wins, draws, losses = [], [], [], [], []
for _, row in team_history.iterrows():
if row['home_team_api_id'] == team_id:
goals_scored.append(row['home_team_goal'])
goals_conceded.append(row['away_team_goal'])
if row['result'] == 0: wins.append(1)
elif row['result'] == 1: draws.append(1)
else: losses.append(0)
else:
goals_scored.append(row['away_team_goal'])
goals_conceded.append(row['home_team_goal'])
if row['result'] == 2: wins.append(1)
elif row['result'] == 1: draws.append(1)
else: losses.append(0)
return {
'avg_goals_scored': np.mean(goals_scored) if goals_scored else 0,
'avg_goals_conceded': np.mean(goals_conceded) if goals_conceded else 0,
'win_rate': sum(wins) / len(team_history) if wins else 0.33,
'draw_rate': sum(draws) / len(team_history) if draws else 0.33,
'loss_rate': 1 - (sum(wins) + sum(draws)) / len(team_history) if (wins or draws) else 0.33
}
# --- CRITICAL FIX: Corrected Elo retrieval function ---
def get_elo_for_prediction(team_id, elo_df_history, all_matches_df, prediction_date, k=ELO_K_FACTOR, initial_elo=INITIAL_ELO):
team_matches_before_date = elo_df_history[
((elo_df_history['home_team_api_id'] == team_id) | (elo_df_history['away_team_api_id'] == team_id)) &
(elo_df_history['date'] < prediction_date)
].sort_values('date', ascending=False)
if team_matches_before_date.empty:
return initial_elo
last_match_elo_data = team_matches_before_date.iloc[0]
R_home_before = last_match_elo_data['home_elo_before']
R_away_before = last_match_elo_data['away_elo_before']
actual_match_data = all_matches_df[all_matches_df['match_api_id'] == last_match_elo_data['match_api_id']].iloc[0]
home_goals = actual_match_data['home_team_goal']
away_goals = actual_match_data['away_team_goal']
if home_goals > away_goals: S_home, S_away = 1, 0
elif home_goals == away_goals: S_home, S_away = 0.5, 0.5
else: S_home, S_away = 0, 1
E_home = 1 / (1 + 10 ** ((R_away_before - R_home_before) / 400))
E_away = 1 - E_home
new_R_home = R_home_before + k * (S_home - E_home)
new_R_away = R_away_before + k * (S_away - E_away)
return new_R_home if last_match_elo_data['home_team_api_id'] == team_id else new_R_away
home_name_input = input("\n🏟️ Enter Home Team Name: ").strip()
away_name_input = input("🚗 Enter Away Team Name: ").strip()
date_str = input("📅 Enter Prediction Date (YYYY-MM-DD): ").strip()
try:
prediction_date = datetime.strptime(date_str, '%Y-%m-%d')
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
return
home_id = get_team_id_from_name(home_name_input, team_names_df, team_name_aliases)
away_id = get_team_id_from_name(away_name_input, team_names_df, team_name_aliases)
if home_id is None or away_id is None:
print("Invalid team name entered. Please check spelling or if the team exists.")
return
home_static_attrs = get_team_attributes_for_prediction(home_id, prediction_date)
away_static_attrs = get_team_attributes_for_prediction(away_id, prediction_date)
if home_static_attrs is None or away_static_attrs is None:
print("⚠️ Team attributes not found for the given date. Cannot predict.")
return
historical_matches_for_rolling = matches[matches['date'] < prediction_date]
home_rolling_feats = get_rolling_features_for_prediction(home_id, historical_matches_for_rolling)
away_rolling_feats = get_rolling_features_for_prediction(away_id, historical_matches_for_rolling)
home_elo_current = get_elo_for_prediction(home_id, elo_df, matches, prediction_date)
away_elo_current = get_elo_for_prediction(away_id, elo_df, matches, prediction_date)
elo_diff_current = home_elo_current - away_elo_current
prediction_data = {
**{f'home_{col}': home_static_attrs[col] for col in selected_static_features},
**{f'away_{col}': away_static_attrs[col] for col in selected_static_features},
'home_avg_goals_scored': home_rolling_feats['avg_goals_scored'],
'home_avg_goals_conceded': home_rolling_feats['avg_goals_conceded'],
'home_win_rate': home_rolling_feats['win_rate'],
'home_draw_rate': home_rolling_feats['draw_rate'],
'home_loss_rate': home_rolling_feats['loss_rate'],
'away_avg_goals_scored': away_rolling_feats['avg_goals_scored'],
'away_avg_goals_conceded': away_rolling_feats['avg_goals_conceded'],
'away_win_rate': away_rolling_feats['win_rate'],
'away_draw_rate': away_rolling_feats['draw_rate'],
'away_loss_rate': away_rolling_feats['loss_rate'],
'home_team_elo': home_elo_current,
'away_team_elo': away_elo_current,
'elo_difference': elo_diff_current
}
prediction_row = pd.DataFrame([prediction_data], columns=feature_columns)
X_pred_scaled = scaler_loaded.transform(prediction_row)
X_pred_tensor = torch.tensor(X_pred_scaled, dtype=torch.float32)
with torch.no_grad():
classification_output = classification_model_loaded(X_pred_tensor)
prediction_probabilities = torch.softmax(classification_output, dim=1).squeeze().numpy()
home_win_prob, draw_prob, away_win_prob = prediction_probabilities * 100
goal_output = goal_model_loaded(X_pred_tensor)
predicted_home_goals = int(round(goal_output[0][0].item()))
predicted_away_goals = int(round(goal_output[0][1].item()))
if predicted_home_goals > predicted_away_goals: predicted_result = "Home Win"
elif predicted_home_goals < predicted_away_goals: predicted_result = "Away Win"
else: predicted_result = "Draw"
print(f"\n--- Prediction for {home_name_input} vs {away_name_input} ---")
print(f"📈 Predicted Result: {predicted_result}")
print(f"⚽ Predicted Scoreline: {home_name_input} {predicted_home_goals} - {predicted_away_goals} {away_name_input}")
print(f"📊 Probabilities: Home Win: {home_win_prob:.2f}% | Draw: {draw_prob:.2f}% | Away Win: {away_win_prob:.2f}%")
print("\nScript finished.")
if __name__ == '__main__':
main()