I'll help you work through these Olympic medal prediction improvements step by step. Let's start with the basics and build up gradually.
Step 1: Load and Explore Your Data
First, make sure you have the athlete-level data file loaded:
import pandas as pd
import numpy as np
# Load the data
df = pd.read_csv('athlete_events.csv')
# Look at the first few rows
print(df.head())
# Check the columns available
print(df.columns.tolist())
# Basic info about the dataset
print(df.info())
Step 2: Add Basic Predictors
Let's start by adding height and age as predictors:
# Check for missing values
print(df[['Height', 'Age']].isnull().sum())
# Create a clean dataset for modeling
# Remove rows with missing height or age
df_clean = df.dropna(subset=['Height', 'Age'])
# Create a binary medal indicator (1 if won any medal, 0 if not)
df_clean['Won_Medal'] = df_clean['Medal'].notna().astype(int)
Step 3: Calculate Years of Competition
Now let's compute how many years each athlete has competed:
# Sort by athlete and year
df_clean = df_clean.sort_values(['Name', 'Year'])
# For each athlete, find their first and last year
athlete_years = df_clean.groupby('Name')['Year'].agg(['min', 'max'])
athlete_years['Years_Competing'] = (athlete_years['max'] - athlete_years['min']) / 4 + 1
# Merge this back to the main dataframe
df_clean = df_clean.merge(
athlete_years[['Years_Competing']],
left_on='Name',
right_index=True
)
Step 4: Create Additional Features
Let's add more useful features:
# Calculate athlete's age at first Olympics
first_olympics = df_clean.groupby('Name').agg({
'Year': 'min',
'Age': 'min'
}).rename(columns={'Age': 'Age_First_Olympics'})
df_clean = df_clean.merge(
first_olympics[['Age_First_Olympics']],
left_on='Name',
right_index=True
)
# Create experience variable (how many Olympics attended before current one)
df_clean['Olympics_Experience'] = df_clean.groupby('Name').cumcount()
Step 5: Build a Simple Model
Start with a basic logistic regression model:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
# Select features for the model
features = ['Height', 'Age', 'Years_Competing', 'Olympics_Experience']
X = df_clean[features]
y = df_clean['Won_Medal']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Train the model
model = LogisticRegression(random_state=42)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Check accuracy
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
Step 6: Build Event-Specific Models
For better predictions, create models for specific events:
# Get the most common events
top_events = df_clean['Event'].value_counts().head(10).index
# Build a model for each event
event_models = {}
for event in top_events:
# Filter data for this event
event_data = df_clean[df_clean['Event'] == event]
if len(event_data) > 100: # Only model if enough data
X_event = event_data[features]
y_event = event_data['Won_Medal']
# Train model
model = LogisticRegression(random_state=42)
model.fit(X_event, y_event)
event_models[event] = model
print(f"Model trained for: {event}")
Step 7: Predict Country Medal Counts
Finally, aggregate predictions by country:
# For the most recent Olympics in your data
recent_year = df_clean['Year'].max()
recent_data = df_clean[df_clean['Year'] == recent_year]
# Make predictions for each athlete
predictions = []
for idx, row in recent_data.iterrows():
event = row['Event']
# Use event-specific model if available
if event in event_models:
X_athlete = row[features].values.reshape(1, -1)
prob = event_models[event].predict_proba(X_athlete)[0, 1]
else:
# Use general model
X_athlete = row[features].values.reshape(1, -1)
prob = model.predict_proba(X_athlete)[0, 1]
predictions.append({
'Country': row['NOC'],
'Athlete': row['Name'],
'Event': row['Event'],
'Medal_Probability': prob
})
# Convert to dataframe and aggregate by country
pred_df = pd.DataFrame(predictions)
country_predictions = pred_df.groupby('Country')['Medal_Probability'].sum()
country_predictions = country_predictions.sort_values(ascending=False)
print("Predicted medal counts by country:")
print(country_predictions.head(20))
Next Steps for Improvement
- Add more features like previous medal history, world rankings if available
- Try different models (Random Forest, XGBoost)
- Use cross-validation to better evaluate your models
- Consider the type of medal (Gold, Silver, Bronze) separately
- Account for team events differently than individual events
Start with steps 1-3 to get comfortable with the data, then gradually work through the more complex modeling approaches. Let me know if you need help with any specific step!