Sure! Building a machine learning model to predict AFL match outcomes involves several steps, including data preprocessing, feature engineering, model selection, training, and evaluation. Below, I'll walk you through a comprehensive approach to achieve this, including full Python code using popular libraries such as pandas, scikit-learn, and XGBoost.
1. Understanding Relevant Factors for AFL Predictions
Before diving into the code, it's essential to identify the factors that can influence the outcome of an AFL match. Here are some relevant factors commonly used by sports betting agencies:
- Team Performance Metrics:
- Home Team Metrics:
- Average points scored per game.
- Average points conceded per game.
- Recent form (e.g., last 5 games).
- Away Team Metrics:
- Average points scored per game.
- Average points conceded per game.
- Recent form.
- Match Location:
- Home advantage (teams tend to perform better at their home venue).
- Head-to-Head Statistics:
- Historical performance between the two teams.
- Playoff Relevance:
- Whether the game is part of the playoffs can affect team performance due to higher stakes.
- In-Game Statistics:
- Date and Season Stage:
- Teams might have fatigue or momentum based on the season's progression.
2. Setting Up the Environment
Ensure you have the necessary libraries installed. You can install them using pip if you haven't already:
pip install pandas numpy scikit-learn xgboost openpyxl
3. Full Python Code for the Prediction Model
import pandas as pd
import numpy as np
from datetime import datetime
import os
# Machine Learning Libraries
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.metrics import mean_absolute_error, r2_score, accuracy_score, classification_report
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
import xgboost as xgb
# Suppress warnings for cleaner output
import warnings
warnings.filterwarnings('ignore')
# 1. Data Loading
file_path = '/Users/rahulkulkarni/Downloads/afl.xlsx'
# Ensure the file exists
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file at {file_path} does not exist. Please check the path.")
# Read the Excel file
df = pd.read_excel(file_path)
# Display the first few rows
print("Initial Data Sample:")
print(df.head())
# 2. Data Preprocessing
# a. Convert 'Date' to datetime
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
# b. Create additional time-based features
df['Month'] = df['Date'].dt.month
df['DayOfWeek'] = df['Date'].dt.dayofweek
# c. Encode categorical variables
# List of categorical columns
categorical_cols = ['Home Team', 'Away Team', 'Venue', 'Play Off Game?']
# Fill missing values if any
df[categorical_cols] = df[categorical_cols].fillna('Unknown')
# Label Encoding for binary categorical features
label_enc = LabelEncoder()
df['Play Off Game?'] = label_enc.fit_transform(df['Play Off Game?'])
# One-Hot Encoding for other categorical features
df = pd.get_dummies(df, columns=['Home Team', 'Away Team', 'Venue'], drop_first=True)
# d. Feature Engineering
# Calculate the margin
df['Margin'] = df['Home Score'] - df['Away Score']
# Binary target for winning (1 if Home wins, 0 otherwise)
df['Home Win'] = (df['Margin'] > 0).astype(int)
# 3. Feature Selection
# Define feature columns (exclude columns that should not be used as features)
feature_cols = list(df.columns)
exclude_cols = ['Date', 'Home Score', 'Away Score', 'Home Goals', 'Home Behinds',
'Away Goals', 'Away Behinds', 'Margin', 'Home Win']
for col in exclude_cols:
feature_cols.remove(col)
# Define X and y for regression (predicting Margin)
X = df[feature_cols]
y_margin = df['Margin']
# Define y for classification (predicting Home Win)
y_win = df['Home Win']
# 4. Data Splitting
# Split for regression
X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(X, y_margin, test_size=0.2, random_state=42)
# Split for classification
X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(X, y_win, test_size=0.2, random_state=42)
# 5. Feature Scaling
scaler = StandardScaler()
X_train_r_scaled = scaler.fit_transform(X_train_r)
X_test_r_scaled = scaler.transform(X_test_r)
X_train_c_scaled = scaler.fit_transform(X_train_c)
X_test_c_scaled = scaler.transform(X_test_c)
# 6. Model Building
# a. Regression Model to Predict Margin
regressor = xgb.XGBRegressor(objective='reg:squarederror', random_state=42)
regressor.fit(X_train_r_scaled, y_train_r)
# b. Classification Model to Predict Home Win Probability
classifier = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss', random_state=42)
classifier.fit(X_train_c_scaled, y_train_c)
# 7. Model Evaluation
# a. Regression Evaluation
y_pred_r = regressor.predict(X_test_r_scaled)
mae = mean_absolute_error(y_test_r, y_pred_r)
r2 = r2_score(y_test_r, y_pred_r)
print("\nRegression Model Evaluation:")
print(f"Mean Absolute Error: {mae:.2f}")
print(f"R² Score: {r2:.2f}")
# b. Classification Evaluation
y_pred_c = classifier.predict(X_test_c_scaled)
y_pred_proba_c = classifier.predict_proba(X_test_c_scaled)[:,1]
accuracy = accuracy_score(y_test_c, y_pred_c)
print("\nClassification Model Evaluation:")
print(f"Accuracy: {accuracy:.2f}")
print(classification_report(y_test_c, y_pred_c))
# 8. Predicting Future Matches
def predict_match(features, reg_model, clf_model, scaler, label_encoder=None):
"""
Predict the margin and winning probability of a match.
Parameters:
- features: dict containing match features
- reg_model: trained regression model
- clf_model: trained classification model
- scaler: fitted scaler
- label_encoder: label encoder for categorical variables (if any)
Returns:
- margin_pred: Predicted margin
- win_prob: Probability of Home Team winning
"""
# Create DataFrame from features
input_df = pd.DataFrame([features])
# Handle categorical variables
# Assume that 'Play Off Game?' is already encoded as 0 or 1
# One-Hot encode other categorical variables as per training data
# This step requires the same encoding as training data
# Example:
# For simplicity, assume all necessary encoding is done before calling this function
# and 'input_df' has the same columns as 'X'
# Align the input features with training features
input_df = input_df.reindex(columns=X.columns, fill_value=0)
# Scaling
input_scaled = scaler.transform(input_df)
# Predict margin
margin_pred = reg_model.predict(input_scaled)[0]
# Predict win probability
win_prob = clf_model.predict_proba(input_scaled)[0][1] * 100 # percentage
return margin_pred, win_prob
# Example Prediction
# Replace the following dictionary with actual match data
example_match = {
'Play Off Game?': 0, # 0 for No, 1 for Yes
'Month': 9,
'DayOfWeek': 6,
# One-Hot Encoded columns for Home Team, Away Team, Venue
# Set to 1 for the corresponding team, 0 otherwise
# Example for Home Team Sydney, Away Team Brisbane, Venue MCG
# Assuming 'Home Team_Sydney', 'Away Team_Brisbane', 'Venue_MCG' exist
'Home Team_Geelong': 0,
'Home Team_Brisbane': 0,
'Home Team_Port Adelaide': 0,
'Home Team_Sydney': 1,
# Add all other Home Team columns with 0
'Away Team_Geelong': 0,
'Away Team_Brisbane': 1,
'Away Team_Port Adelaide': 0,
'Away Team_Sydney': 0,
# Add all other Away Team columns with 0
'Venue_MCG': 1,
# Add all other Venue columns with 0
}
# Ensure all feature columns are present; if not, set to 0
for col in X.columns:
if col not in example_match:
example_match[col] = 0
margin, win_pct = predict_match(example_match, regressor, classifier, scaler)
print(f"\nPredicted Margin: {margin:.2f}")
print(f"Probability of Home Team Winning: {win_pct:.2f}%")
4. Explanation of the Code
-
Data Loading:
- The code begins by loading the AFL data from an Excel file using
pandas. It ensures the file exists before attempting to read it.
-
Data Preprocessing:
- Date Conversion: The 'Date' column is converted to a datetime object to extract additional features like month and day of the week.
- Categorical Encoding: Categorical variables such as 'Home Team', 'Away Team', 'Venue', and 'Play Off Game?' are encoded. 'Play Off Game?' is label-encoded since it's binary, while other categorical variables are one-hot encoded to capture all possible categories.
- Margin Calculation: A new feature 'Margin' is calculated as the difference between 'Home Score' and 'Away Score'. Additionally, a binary target 'Home Win' is created to indicate whether the home team won.
-
Feature Selection:
- The code identifies which columns to use as features by excluding irrelevant ones like actual scores and date information.
-
Data Splitting:
- The dataset is split into training and testing sets for both regression (predicting margin) and classification (predicting home win).
-
Feature Scaling:
- Features are scaled using
StandardScaler to normalize the data, which is especially important for models like XGBoost.
-
Model Building:
- Regression Model: An XGBoost regressor is trained to predict the margin.
- Classification Model: An XGBoost classifier is trained to predict the probability of the home team winning.
-
Model Evaluation:
- The regression model is evaluated using Mean Absolute Error (MAE) and R² score.
- The classification model is evaluated using accuracy and a classification report, which includes precision, recall, and F1-score.
-
Predicting Future Matches:
- A
predict_match function is defined to take in match features and output the predicted margin and home win probability. This function ensures that the input features are aligned with the training data and properly scaled before making predictions.
- An example prediction is provided, which should be replaced with actual match data. Ensure that all one-hot encoded features are correctly set for the home team, away team, and venue.
5. Important Considerations
-
Feature Engineering: The current approach uses basic feature engineering. Incorporating more advanced features like player statistics, injuries, weather conditions, and historical head-to-head performance can improve model accuracy.
-
Handling Imbalanced Data: If the dataset has an imbalance between home wins and losses, consider techniques like SMOTE or class weighting to address it.
-
Hyperparameter Tuning: The models use default parameters. Tuning hyperparameters using GridSearchCV or RandomizedSearchCV can enhance performance.
-
Cross-Validation: Implement cross-validation to ensure that the model generalizes well to unseen data.
-
Model Interpretability: Tools like SHAP or feature importance plots can help understand which features contribute most to the predictions.
6. Final Notes
This code provides a foundational framework for predicting AFL match outcomes using machine learning. Depending on the richness and size of your dataset, further enhancements and refinements can be made to improve prediction accuracy. Always ensure that the data is up-to-date and captures all relevant factors influencing match outcomes.