Spaces:
Sleeping
Sleeping
Commit ·
58fa837
0
Parent(s):
initial commit
Browse files- .dockerignore +11 -0
- .gitattributes +9 -0
- .gitignore +8 -0
- Dockerfile +14 -0
- README.md +214 -0
- app.py +48 -0
- cross_attn_best_weight_dx.pt +3 -0
- cross_attn_best_weight_dy.pt +3 -0
- gru.py +973 -0
- gru_app_predict.py +191 -0
- gru_scaler.joblib +3 -0
- lightGBT.py +594 -0
- lightGBT_app_predict.py +74 -0
- lightGBT_dx_model.txt +3 -0
- lightGBT_dy_model.txt +3 -0
- requirements.txt +11 -0
- sample_nfl_plays.csv +3 -0
- sample_nfl_plays_actual_output.csv +3 -0
- train_data_analysis.py +239 -0
.dockerignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
checkpoints_dx/
|
| 2 |
+
checkpoints_dy/
|
| 3 |
+
.idea/
|
| 4 |
+
.vscode/
|
| 5 |
+
__pycache__/
|
| 6 |
+
gru_test_results.csv
|
| 7 |
+
lightgbt_test_data_results.csv
|
| 8 |
+
sample_nfl_plays_actual_output.csv
|
| 9 |
+
sample_nfl_plays.csv
|
| 10 |
+
train_data_analysis.py
|
| 11 |
+
README.md
|
.gitattributes
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sample_nfl_plays.csv filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
sample_nfl_plays_actual_output.csv filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
cross_attn_best_weight_dx.pt filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
cross_attn_best_weight_dy.pt filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
gru_scaler.joblib filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
lightGBT_dx_model.txt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
lightGBT_dy_model.txt filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
train_input/* filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
train_output/* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/*
|
| 2 |
+
.idea/*
|
| 3 |
+
.vscode/*
|
| 4 |
+
checkpoints_dx/*
|
| 5 |
+
checkpoints_dy/*
|
| 6 |
+
train_input/*
|
| 7 |
+
train_output/*
|
| 8 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.14.3-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt ./
|
| 6 |
+
|
| 7 |
+
RUN pip3 install --no-cache-dir --break-system-packages -r requirements.txt
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
COPY gru_scaler.joblib app.py gru_app_predict.py lightGBT_app_predict.py gru.py lightGBT.py ./
|
| 11 |
+
COPY cross_attn_best_weight_dx.pt cross_attn_best_weight_dy.pt ./
|
| 12 |
+
COPY lightGBT_dx_model.txt lightGBT_dy_model.txt ./
|
| 13 |
+
|
| 14 |
+
CMD ["python3", "app.py", "--port", "7860"]
|
README.md
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 📘 NFL Player Trajectory Prediction — Spatiotemporal Modeling (Kaggle Big Data Bowl 2026)
|
| 2 |
+
|
| 3 |
+
## 📌 Overview
|
| 4 |
+
This project is based on a Kaggle competition focused on predicting player positions in the NFL after the quarterback releases the ball.
|
| 5 |
+
The challenge involves forecasting the next **N frames (on an average 11)** of movement for selected players using their past tracking data.
|
| 6 |
+
|
| 7 |
+
Player movement during a downfield pass is highly dynamic and uncertain — outcomes range from completions to interceptions. Understanding these trajectories helps the NFL analyze behavior of receivers, defenders, and passers during critical moments of a play.
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## 🏈 Problem Description
|
| 12 |
+
During a pass play:
|
| 13 |
+
|
| 14 |
+
- The quarterback (QB) receives the snap.
|
| 15 |
+
- At the moment the ball is thrown, the prediction window begins.
|
| 16 |
+
- Tracking data provides positions and physical attributes for all players near the action.
|
| 17 |
+
- Not all 22 players are relevant — only those within the vicinity of the play (often 10–14 players).
|
| 18 |
+
|
| 19 |
+
### 🎯 Goal
|
| 20 |
+
Predict the **next N (20–40)** positions *(x, y)* for a subset of players (**P_pred ≤ P**) given:
|
| 21 |
+
|
| 22 |
+
- Their historical movement prior to the pass
|
| 23 |
+
- Ball landing location
|
| 24 |
+
- Player roles (Passer, Targeted Receiver, Defense, etc.)
|
| 25 |
+
- Game- and play-level context
|
| 26 |
+
|
| 27 |
+
---
|
| 28 |
+
|
| 29 |
+
## 📂 Input Features
|
| 30 |
+
Each frame includes tracking data before the pass is thrown:
|
| 31 |
+
|
| 32 |
+
- `game_id`: Game identifier, unique (numeric)
|
| 33 |
+
- `play_id`: Play identifier, not unique across games (numeric)
|
| 34 |
+
- `player_to_predict`: Whether or not the x/y prediction for this player will be scored (bool)
|
| 35 |
+
- `nfl_id`: Player identification number, unique across players (numeric)
|
| 36 |
+
- `frame_id`: Frame identifier for each play/type, starting at 1 for each game_id/play_id/file type (input or output) (numeric)
|
| 37 |
+
- `play_direction`: Direction that the offense is moving (left or right)
|
| 38 |
+
- `absolute_yardline_number`: Distance from end zone for possession team (numeric) (how far from the score zone)
|
| 39 |
+
- `player_name`: Player name (text)
|
| 40 |
+
- `player_height`: Player height (ft-in)
|
| 41 |
+
- `player_weight`: Player weight (lbs)
|
| 42 |
+
- `player_birth_date`: Birth date (yyyy-mm-dd)
|
| 43 |
+
- `player_position`: Player's position (role on the field)
|
| 44 |
+
- `player_side`: Team player is on (Offense or Defense)
|
| 45 |
+
- `player_role`: Role on the play (Defensive Coverage, Targeted Receiver, Passer, Other Route Runner)
|
| 46 |
+
- `x`: Player position along the long axis of the field (0–120 yards)
|
| 47 |
+
- `y`: Player position along the short axis of the field (0–53.3 yards)
|
| 48 |
+
- `s`: Speed in yards/second (numeric)
|
| 49 |
+
- `a`: Acceleration in yards/second² (numeric)
|
| 50 |
+
- `o`: Orientation of player (degrees)
|
| 51 |
+
- `dir`: Angle of player motion (degrees)
|
| 52 |
+
- `num_frames_output`: Number of frames to predict in output data for the given game_id/play_id/nfl_id (numeric)
|
| 53 |
+
- `ball_land_x`: Ball landing x-position (0–120 yards)
|
| 54 |
+
- `ball_land_y`: Ball landing y-position (0–53.3 yards)
|
| 55 |
+
|
| 56 |
+
---
|
| 57 |
+
|
| 58 |
+
## 🛠 Feature Engineering
|
| 59 |
+
|
| 60 |
+
Feature engineering is performed using the `NFLFeatureTransformer` class, which normalizes numerical fields and adds several new features.
|
| 61 |
+
|
| 62 |
+
### 🔹 Angle-Based Features
|
| 63 |
+
-
|
| 64 |
+
- `sin_dir`, `cos_dir`
|
| 65 |
+
- `sin_o`, `cos_o`
|
| 66 |
+
- `angle_between_ball_land_and_player`
|
| 67 |
+
- `angle_between_ball_land_and_player_orient`
|
| 68 |
+
- `sin_angle_between_ball_land_and_player`
|
| 69 |
+
- `cos_angle_between_ball_land_and_player`
|
| 70 |
+
- `sin_angle_between_ball_land_and_player_orient`
|
| 71 |
+
- `cos_angle_between_ball_land_and_player_orient`
|
| 72 |
+
- `sin_change_in_o`
|
| 73 |
+
- `cos_change_in_o`
|
| 74 |
+
- `change_in_dir`
|
| 75 |
+
- `sin_change_in_dir`
|
| 76 |
+
- `cos_change_in_dir`
|
| 77 |
+
- `change_in_o`
|
| 78 |
+
- `angle_between_orientation_and_player`
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
These help the model understand relative direction and orientation with respect to the ball.
|
| 82 |
+
|
| 83 |
+
### 🔹 Distance & Physics Features
|
| 84 |
+
|
| 85 |
+
- `velocity_x`, `velocity_y`
|
| 86 |
+
- `acc_x`, `acc_y`
|
| 87 |
+
- `distance_to_x`, `distance_to_y`
|
| 88 |
+
- `distance_to_sideline`,
|
| 89 |
+
- `distance_to_ball_land_x`, `distance_to_ball_land_y`
|
| 90 |
+
- `absolute_yardline_number`
|
| 91 |
+
- `distance_between_the_reciever`
|
| 92 |
+
- `distance_between_the_passer`
|
| 93 |
+
- `distance_to_defense`
|
| 94 |
+
- `distance_to_defense_x`
|
| 95 |
+
- `distance_to_defense_y`
|
| 96 |
+
- `distance_to_offense`
|
| 97 |
+
- `distance_to_offense_x`
|
| 98 |
+
- `distance_to_offense_y`
|
| 99 |
+
- `nearest_teammate_dis`
|
| 100 |
+
- `nearest_teammate_dis_x`
|
| 101 |
+
- `nearest_teammate_dis_y`,
|
| 102 |
+
- `required_velocity_x`
|
| 103 |
+
- `required_velocity_y`
|
| 104 |
+
- `required_acc_x`
|
| 105 |
+
- `required_acc_y`
|
| 106 |
+
- `proj_x_acc`
|
| 107 |
+
- `proj_y_acc`
|
| 108 |
+
- `proj_x_velocity`
|
| 109 |
+
- `proj_y_velocity`
|
| 110 |
+
- `required_speed`
|
| 111 |
+
- `required_acceleration`
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
These features capture how players move in relation to the field and ball landing location.
|
| 115 |
+
|
| 116 |
+
### 🔹 Temporal Change Features
|
| 117 |
+
|
| 118 |
+
- `time_left`
|
| 119 |
+
- `required_speed`, `required_acceleration`
|
| 120 |
+
- `change_in_x`, `change_in_y`
|
| 121 |
+
- `change_in_speed`
|
| 122 |
+
- `change_in_acceleration`
|
| 123 |
+
- `change_in_o`
|
| 124 |
+
- `change_in_dir`
|
| 125 |
+
- `proj_x_acc_diff`
|
| 126 |
+
- `proj_y_acc_diff`
|
| 127 |
+
- `proj_x_velocity_diff`
|
| 128 |
+
- `proj_y_velocity_diff`
|
| 129 |
+
- `required_speed_diff`
|
| 130 |
+
- `required_velocity_x_diff`
|
| 131 |
+
- `required_velocity_y_diff`
|
| 132 |
+
- `required_acc_x_diff`
|
| 133 |
+
- `required_acc_y_diff`
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
These model short-term motion dynamics and evolution of movement.
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
---
|
| 140 |
+
|
| 141 |
+
## 📁 Project files
|
| 142 |
+
|
| 143 |
+
- `gru.py`
|
| 144 |
+
- `lightGBT.py`
|
| 145 |
+
|
| 146 |
+
Each python file represents a separate modeling approach to the same prediction task.
|
| 147 |
+
|
| 148 |
+
---
|
| 149 |
+
|
| 150 |
+
## 🔷 Model 1: LightGBT
|
| 151 |
+
|
| 152 |
+
### 🧱 Architecture
|
| 153 |
+
|
| 154 |
+
This approach combines:
|
| 155 |
+
|
| 156 |
+
1. Takes the last given frame and uses that data to predict the next `num_frames_output`.
|
| 157 |
+
2. We predict the residual from the last known x and y positions.
|
| 158 |
+
3. Uses a separate model dx_model , dy_model to predict the residuals.
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
## 🔷 Model 2: RNN With Cross Attention and MLP
|
| 162 |
+
|
| 163 |
+
### 🧱 Architecture
|
| 164 |
+
|
| 165 |
+
This approach combines:
|
| 166 |
+
|
| 167 |
+
Uses Two Models to find dx , dy from the last known x and y positions.
|
| 168 |
+
|
| 169 |
+
1. **Spatial Encoder**
|
| 170 |
+
- Operates on `[T, P, din]`
|
| 171 |
+
- Captures relationships among players at a given time frame
|
| 172 |
+
|
| 173 |
+
2. **GRU Layer**
|
| 174 |
+
- Operates on `[P, T, din]`
|
| 175 |
+
- Models temporal evolution for each player's trajectory (taken only on the players to predict)
|
| 176 |
+
- Takes cross attention with Spatial Encoder at each time t.
|
| 177 |
+
|
| 178 |
+
3. **MLP Layer**
|
| 179 |
+
- Operates on `[P*T, din]`
|
| 180 |
+
- outputs the change in displacment dx, dy
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
Input is fed as:
|
| 184 |
+
|
| 185 |
+
- `[P, T, din]`
|
| 186 |
+
|
| 187 |
+
Where:
|
| 188 |
+
|
| 189 |
+
- `P`: total players under focus
|
| 190 |
+
- `T`: total time steps
|
| 191 |
+
- `din`: input feature dimension
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
### 📉 Loss Function
|
| 195 |
+
|
| 196 |
+
- **Mean Squared Error (MSE)**
|
| 197 |
+
|
| 198 |
+
### 📊 Performance
|
| 199 |
+
|
| 200 |
+
- **RMSE: 1.71 yards** on physics first order linear exerpolation
|
| 201 |
+
- **RMSE: 0.66 yards** on LightGBT
|
| 202 |
+
- **RMSE: 0.60 yards** on RNN With Cross Attention and MLP
|
| 203 |
+
|
| 204 |
+
---
|
| 205 |
+
|
| 206 |
+
## 🚀 Future Work
|
| 207 |
+
- Explore graph neural networks for player–player interaction modeling.
|
| 208 |
+
|
| 209 |
+
---
|
| 210 |
+
|
| 211 |
+
## 🎉 Conclusion
|
| 212 |
+
|
| 213 |
+
This project applies deep feature engineering, transformers, and recurrent architectures to model complex NFL player movement in pass plays.
|
| 214 |
+
The lightGBT approach is lot simpler and acheives slightly better performance.
|
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, Response
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import gru_app_predict
|
| 4 |
+
import lightGBT_app_predict
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
import argparse
|
| 8 |
+
|
| 9 |
+
app = Flask(__name__)
|
| 10 |
+
|
| 11 |
+
logging.basicConfig(level=logging.INFO)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@app.route('/nfl/health')
|
| 15 |
+
def health_check():
|
| 16 |
+
return 'dont worry i m there'
|
| 17 |
+
|
| 18 |
+
@app.route('/nfl/gru_predict_play', methods=['POST'])
|
| 19 |
+
def gru_predict__play():
|
| 20 |
+
csv_file = request.files['file']
|
| 21 |
+
df = pd.read_csv(csv_file.stream)
|
| 22 |
+
res_df = gru_app_predict.predict(df)
|
| 23 |
+
|
| 24 |
+
return Response(
|
| 25 |
+
res_df.to_csv(index=False),
|
| 26 |
+
mimetype="text/csv",
|
| 27 |
+
headers={"Content-Disposition": "attachment; filename=gru_predict.csv"}
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
@app.route('/nfl/lightGBT_predict_play', methods=['POST'])
|
| 31 |
+
def lightGBT_predict_play():
|
| 32 |
+
csv_file = request.files['file']
|
| 33 |
+
df = pd.read_csv(csv_file.stream)
|
| 34 |
+
|
| 35 |
+
res_df = lightGBT_app_predict.predict(df)
|
| 36 |
+
|
| 37 |
+
return Response(
|
| 38 |
+
res_df.to_csv(index=False),
|
| 39 |
+
mimetype="text/csv",
|
| 40 |
+
headers={"Content-Disposition": "attachment; filename=lightGBT_predict.csv"}
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == '__main__':
|
| 45 |
+
parser = argparse.ArgumentParser(description="Run the FastAPI application.")
|
| 46 |
+
parser.add_argument("--port", type=int, default=5050, help="Port to run the app on")
|
| 47 |
+
args = parser.parse_args()
|
| 48 |
+
app.run(host='0.0.0.0', port=args.port)
|
cross_attn_best_weight_dx.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:16fef2a972fc1694de301174a9cd9b50d076bd7ff660510bfa8eae7b48a707d2
|
| 3 |
+
size 2510996
|
cross_attn_best_weight_dy.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e7847d5469de0861b311ff21db1349234a60cff1f60de77b7133153ed5ed3de3
|
| 3 |
+
size 2510996
|
gru.py
ADDED
|
@@ -0,0 +1,973 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
MODEL_INPUT_FEATURES = ['frame_id', 'absolute_yardline_number',
|
| 7 |
+
'player_height', 'player_weight', 'x', 'y', 's', 'a', 'dir', 'o',
|
| 8 |
+
'num_frames_output', 'ball_land_x', 'ball_land_y', 'sin_dir', 'cos_dir',
|
| 9 |
+
'sin_o', 'cos_o', 'velocity_x', 'velocity_y', 'acc_x', 'acc_y',
|
| 10 |
+
'distance_to_sideline', 'distance_to_ball_land',
|
| 11 |
+
'distance_to_ball_land_x', 'distance_to_ball_land_y',
|
| 12 |
+
'angle_between_ball_land_and_player',
|
| 13 |
+
'angle_between_ball_land_and_player_orient',
|
| 14 |
+
'sin_angle_between_ball_land_and_player',
|
| 15 |
+
'cos_angle_between_ball_land_and_player',
|
| 16 |
+
'sin_angle_between_ball_land_and_player_orient',
|
| 17 |
+
'cos_angle_between_ball_land_and_player_orient', 'time_left',
|
| 18 |
+
'required_speed', 'required_acceleration', 'change_in_x', 'change_in_y',
|
| 19 |
+
'change_in_speed', 'change_in_acceleration', 'change_in_o',
|
| 20 |
+
'sin_change_in_o', 'cos_change_in_o', 'change_in_dir',
|
| 21 |
+
'sin_change_in_dir', 'cos_change_in_dir',
|
| 22 |
+
'distance_between_the_reciever', 'distance_between_the_passer',
|
| 23 |
+
'distance_to_defense', 'distance_to_defense_x', 'distance_to_defense_y',
|
| 24 |
+
'distance_to_offense', 'distance_to_offense_x', 'distance_to_offense_y',
|
| 25 |
+
'nearest_teammate_dis', 'nearest_teammate_dis_x',
|
| 26 |
+
'nearest_teammate_dis_y', 'player_role_Defensive Coverage',
|
| 27 |
+
'player_role_Other Route Runner', 'player_role_Passer',
|
| 28 |
+
'player_role_Targeted Receiver', 'player_role_unknown',
|
| 29 |
+
'required_velocity_x', 'required_velocity_y', 'required_acc_x',
|
| 30 |
+
'required_acc_y', 'required_speed_diff', 'required_velocity_x_diff',
|
| 31 |
+
'required_velocity_y_diff', 'required_acc_x_diff',
|
| 32 |
+
'required_acc_y_diff', 'proj_x_acc', 'proj_y_acc', 'proj_x_velocity',
|
| 33 |
+
'proj_y_velocity', 'proj_x_acc_diff', 'proj_y_acc_diff',
|
| 34 |
+
'proj_x_velocity_diff', 'proj_y_velocity_diff',
|
| 35 |
+
'angle_between_orientation_and_player', 'player_age']
|
| 36 |
+
|
| 37 |
+
MODEL_OUTPUTS = ['x', 'y']
|
| 38 |
+
|
| 39 |
+
TRAIN_INPUT_FILE_PATH=f'train_input'
|
| 40 |
+
TRAIN_OUTPUT_FILE_PATH=f'train_output'
|
| 41 |
+
|
| 42 |
+
DX_CHECKPOINT_DIR = f'checkpoints_dx'
|
| 43 |
+
DY_CHECKPOINT_DIR = f'checkpoints_dy'
|
| 44 |
+
|
| 45 |
+
BEST_DX_MODEL_CHECKPOINT = f'cross_attn_best_weight_dx.pt'
|
| 46 |
+
BEST_DY_MODEL_CHECKPOINT = f'cross_attn_best_weight_dy.pt'
|
| 47 |
+
|
| 48 |
+
JOBLIB_FILE_PATH = f'gru_scaler.joblib'
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
from enum import Enum
|
| 52 |
+
class ModelType(Enum):
|
| 53 |
+
DX_MODEL = 1
|
| 54 |
+
DY_MODEL = 2
|
| 55 |
+
|
| 56 |
+
from datetime import date
|
| 57 |
+
from scipy.spatial.distance import cdist
|
| 58 |
+
|
| 59 |
+
class NFLFeatureTransformer:
|
| 60 |
+
|
| 61 |
+
def _convert_to_radians(self, degrees):
|
| 62 |
+
return degrees * np.pi / 180
|
| 63 |
+
|
| 64 |
+
def _convert_to_degrees(self, radians):
|
| 65 |
+
return radians * 180 / np.pi
|
| 66 |
+
|
| 67 |
+
def _sin(self, X):
|
| 68 |
+
return np.sin(self._convert_to_radians(X))
|
| 69 |
+
|
| 70 |
+
def _cos(self, X):
|
| 71 |
+
return np.cos(self._convert_to_radians(X))
|
| 72 |
+
|
| 73 |
+
def _x_component(self, magnitude, direction):
|
| 74 |
+
return magnitude * self._sin(direction)
|
| 75 |
+
|
| 76 |
+
def _y_component(self, magnitude, direction):
|
| 77 |
+
return magnitude * self._cos(direction)
|
| 78 |
+
|
| 79 |
+
def _distance_between_two_points(self, x1, y1, x2, y2):
|
| 80 |
+
return np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _angle_between_two_points(self, x1, y1, x2, y2):
|
| 84 |
+
num = x2 - x1
|
| 85 |
+
denom = (y2-y1)+1e-6
|
| 86 |
+
angle_in_radians = np.arctan2(num, denom)
|
| 87 |
+
angle = self._convert_to_degrees(angle_in_radians)
|
| 88 |
+
return (angle + 360) % 360
|
| 89 |
+
|
| 90 |
+
def _angle_between_two_vectors(self, x1, y1, x2, y2):
|
| 91 |
+
denom = np.sqrt((x1**2)+(y1**2)) * np.sqrt((x2**2)+(y2**2)) + 1e-6
|
| 92 |
+
dot = x1*x2 + y1*y2
|
| 93 |
+
cos_angle = dot / denom
|
| 94 |
+
cos_angle = np.clip(cos_angle, -1.0, 1.0)
|
| 95 |
+
angle_in_radians = np.arccos(cos_angle)
|
| 96 |
+
return self._convert_to_degrees(angle_in_radians)
|
| 97 |
+
|
| 98 |
+
def _convert_to_inches(self, X):
|
| 99 |
+
splits = X.str.split('-', expand=True)
|
| 100 |
+
feet = splits.iloc[:,0].astype(np.float32)
|
| 101 |
+
inches = splits.iloc[:,1].astype(np.float32)
|
| 102 |
+
return feet * 12 + inches
|
| 103 |
+
|
| 104 |
+
MAXIMUM_X = 120
|
| 105 |
+
MAXIMUM_Y = 53.3
|
| 106 |
+
|
| 107 |
+
#measured along diagonal
|
| 108 |
+
MAXIMUM_DIS = 131.30
|
| 109 |
+
|
| 110 |
+
#measures short change in angle like (1 degree - 359 degree gives -358 degree/360 gives a larger value)
|
| 111 |
+
def _change_in_angle(self, prev, curr):
|
| 112 |
+
return ((curr - prev +180) % 360) - 180
|
| 113 |
+
|
| 114 |
+
def reflect_input_coordinates(self, X, play_direction):
|
| 115 |
+
if play_direction == 'left':
|
| 116 |
+
X['x'] = self.MAXIMUM_X - X['x']
|
| 117 |
+
X['dir'] = (360 - X['dir']) % 360
|
| 118 |
+
X['o'] = (360 - X['o']) % 360
|
| 119 |
+
X['ball_land_x'] = self.MAXIMUM_X - X['ball_land_x']
|
| 120 |
+
return X
|
| 121 |
+
|
| 122 |
+
def reflect_output_coordinates(self, Y, play_direction):
|
| 123 |
+
if play_direction == 'left':
|
| 124 |
+
Y['x'] = self.MAXIMUM_X - Y['x']
|
| 125 |
+
return Y
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def transform_X(self, X, prev_frame, total_frames):
|
| 129 |
+
|
| 130 |
+
X['x'] = X['x'].bfill().ffill()
|
| 131 |
+
X['y'] = X['y'].bfill().ffill()
|
| 132 |
+
X['s'] = X['s'].bfill().ffill()
|
| 133 |
+
X['a'] = X['a'].bfill().ffill()
|
| 134 |
+
X['dir'] = X['dir'].bfill().ffill()
|
| 135 |
+
X['o'] = X['o'].bfill().ffill()
|
| 136 |
+
X['player_height'] = X['player_height'].bfill().ffill()
|
| 137 |
+
|
| 138 |
+
prev_x_ = prev_frame['x'].bfill().ffill().values
|
| 139 |
+
prev_y_ = prev_frame['y'].bfill().ffill().values
|
| 140 |
+
prev_s_ = prev_frame['s'].bfill().ffill().values
|
| 141 |
+
prev_a_ = prev_frame['a'].bfill().ffill().values
|
| 142 |
+
prev_dir_ = prev_frame['dir'].bfill().ffill().values
|
| 143 |
+
prev_o_ = prev_frame['o'].bfill().ffill().values
|
| 144 |
+
|
| 145 |
+
player_role_categories = ['Defensive Coverage', 'Other Route Runner', 'Passer', 'Targeted Receiver', 'unknown']
|
| 146 |
+
X['player_role'] = X['player_role'].fillna('unknown')
|
| 147 |
+
X['player_role'] = pd.Categorical(X['player_role'], categories=player_role_categories)
|
| 148 |
+
|
| 149 |
+
offense_indices = X['player_side'] == 'Offense'
|
| 150 |
+
defense_indices = X['player_side'] == 'Defense'
|
| 151 |
+
targeted_reciever = X[X['player_role'] == 'Targeted Receiver']
|
| 152 |
+
passer = X[X['player_role'] == 'Passer']
|
| 153 |
+
|
| 154 |
+
if np.any(defense_indices):
|
| 155 |
+
defense_x_ = X[defense_indices]['x'].values
|
| 156 |
+
defense_y_ = X[defense_indices]['y'].values
|
| 157 |
+
defense_pos = np.column_stack((defense_x_, defense_y_))
|
| 158 |
+
|
| 159 |
+
if np.any(offense_indices):
|
| 160 |
+
offense_x_ = X[offense_indices]['x'].values
|
| 161 |
+
offense_y_ = X[offense_indices]['y'].values
|
| 162 |
+
offense_pos = np.column_stack((offense_x_, offense_y_))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
X['sin_dir'] = self._sin(X['dir'])
|
| 166 |
+
X['cos_dir'] = self._cos(X['dir'])
|
| 167 |
+
X['sin_o'] = self._sin(X['o'])
|
| 168 |
+
X['cos_o'] = self._cos(X['o'])
|
| 169 |
+
X['velocity_x'] = self._x_component(X['s'], X['dir'])
|
| 170 |
+
X['velocity_y'] = self._y_component(X['s'], X['dir'])
|
| 171 |
+
|
| 172 |
+
X['acc_x'] = self._x_component(X['a'], X['dir'])
|
| 173 |
+
X['acc_y'] = self._y_component(X['a'], X['dir'])
|
| 174 |
+
|
| 175 |
+
X['distance_to_sideline'] = np.minimum(X['y'], self.MAXIMUM_Y - X['y'])
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
X['distance_to_ball_land'] = self._distance_between_two_points(X['x'], X['y'], X['ball_land_x'],X['ball_land_y'])
|
| 179 |
+
X['distance_to_ball_land_x'] = X['x'] - X['ball_land_x']
|
| 180 |
+
X['distance_to_ball_land_y'] = X['y'] - X['ball_land_y']
|
| 181 |
+
|
| 182 |
+
X['angle_between_ball_land_and_player'] = (
|
| 183 |
+
self._angle_between_two_vectors(X['sin_dir'], X['cos_dir'], X['distance_to_ball_land_x'], X['distance_to_ball_land_y'] )
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
X['angle_between_ball_land_and_player_orient'] = (
|
| 187 |
+
self._angle_between_two_vectors(X['sin_o'], X['cos_o'], X['distance_to_ball_land_x'], X['distance_to_ball_land_y'] )
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
X['sin_angle_between_ball_land_and_player'] = self._sin(X['angle_between_ball_land_and_player'])
|
| 191 |
+
X['cos_angle_between_ball_land_and_player'] = self._cos(X['angle_between_ball_land_and_player'])
|
| 192 |
+
|
| 193 |
+
X['sin_angle_between_ball_land_and_player_orient'] = self._sin(X['angle_between_ball_land_and_player_orient'])
|
| 194 |
+
X['cos_angle_between_ball_land_and_player_orient'] = self._cos(X['angle_between_ball_land_and_player_orient'])
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
X['time_left'] = (total_frames - (X['frame_id'] - 1)) / 10
|
| 198 |
+
X['required_speed'] = (X['distance_to_ball_land'] / X['time_left'])
|
| 199 |
+
X['required_acceleration'] = ((X['required_speed'] - X['s']) / X['time_left'])
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
X['change_in_x'] = (X['x'] - prev_x_)
|
| 203 |
+
X['change_in_y'] = (X['y'] - prev_y_)
|
| 204 |
+
X['change_in_speed'] = (X['s'] - prev_s_)
|
| 205 |
+
X['change_in_acceleration'] = (X['a'] - prev_a_)
|
| 206 |
+
|
| 207 |
+
X['change_in_o'] = self._change_in_angle(X['o'], prev_o_)
|
| 208 |
+
X['sin_change_in_o'] = self._sin(X['change_in_o'])
|
| 209 |
+
X['cos_change_in_o'] = self._cos(X['change_in_o'])
|
| 210 |
+
|
| 211 |
+
X['change_in_dir'] = self._change_in_angle(X['dir'] , prev_dir_)
|
| 212 |
+
X['sin_change_in_dir'] = self._sin(X['change_in_dir'])
|
| 213 |
+
X['cos_change_in_dir'] = self._cos(X['change_in_dir'])
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if targeted_reciever.empty:
|
| 217 |
+
X['distance_between_the_reciever'] = self.MAXIMUM_DIS
|
| 218 |
+
else:
|
| 219 |
+
X['distance_between_the_reciever'] = (
|
| 220 |
+
self._distance_between_two_points(X['x'], X['y'], targeted_reciever['x'].values, targeted_reciever['y'].values)
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if passer.empty:
|
| 224 |
+
X['distance_between_the_passer'] = self.MAXIMUM_DIS
|
| 225 |
+
else:
|
| 226 |
+
X['distance_between_the_passer'] = self._distance_between_two_points(X['x'], X['y'], passer['x'].values, passer['y'].values)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
if np.any(offense_indices) and np.any(defense_indices):
|
| 230 |
+
cross_distance_matrix = cdist(offense_pos, defense_pos, metric='euclidean')
|
| 231 |
+
|
| 232 |
+
offense_distance_matrix = cdist(offense_pos, offense_pos, metric='euclidean')
|
| 233 |
+
np.fill_diagonal(offense_distance_matrix, self.MAXIMUM_DIS)
|
| 234 |
+
|
| 235 |
+
defense_distance_matrix = cdist(defense_pos, defense_pos, metric='euclidean')
|
| 236 |
+
np.fill_diagonal(defense_distance_matrix, self.MAXIMUM_DIS)
|
| 237 |
+
|
| 238 |
+
X.loc[offense_indices, ['distance_to_defense']] = np.min(cross_distance_matrix, axis=1)
|
| 239 |
+
X.loc[offense_indices, ['distance_to_defense_x']] = defense_pos[np.argmin(cross_distance_matrix, axis=1), 0]
|
| 240 |
+
X.loc[offense_indices, ['distance_to_defense_y']] = defense_pos[np.argmin(cross_distance_matrix, axis=1), 1]
|
| 241 |
+
|
| 242 |
+
X.loc[offense_indices, ['distance_to_offense']] = 0
|
| 243 |
+
X.loc[offense_indices, ['distance_to_offense_x']] = 0
|
| 244 |
+
X.loc[offense_indices, ['distance_to_offense_y']] = 0
|
| 245 |
+
|
| 246 |
+
X.loc[offense_indices, ['nearest_teammate_dis']] = np.min(offense_distance_matrix, axis=1)
|
| 247 |
+
X.loc[offense_indices, ['nearest_teammate_dis_x']] = offense_pos[np.argmin(offense_distance_matrix, axis=1), 0]
|
| 248 |
+
X.loc[offense_indices, ['nearest_teammate_dis_y']] = offense_pos[np.argmin(offense_distance_matrix, axis=1), 1]
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
X.loc[defense_indices, ['distance_to_offense']] = np.min(cross_distance_matrix, axis=0)
|
| 253 |
+
X.loc[defense_indices, ['distance_to_offense_x']] = offense_pos[np.argmin(cross_distance_matrix, axis=0), 0]
|
| 254 |
+
X.loc[defense_indices, ['distance_to_offense_y']] = offense_pos[np.argmin(cross_distance_matrix, axis=0), 1]
|
| 255 |
+
|
| 256 |
+
X.loc[defense_indices, ['distance_to_defense']] = 0
|
| 257 |
+
X.loc[defense_indices, ['distance_to_defense_x']] = 0
|
| 258 |
+
X.loc[defense_indices, ['distance_to_defense_y']] = 0
|
| 259 |
+
|
| 260 |
+
X.loc[defense_indices, ['nearest_teammate_dis']] = np.min(defense_distance_matrix, axis=1)
|
| 261 |
+
X.loc[defense_indices, ['nearest_teammate_dis_x']] = defense_pos[np.argmin(defense_distance_matrix, axis=1), 0]
|
| 262 |
+
X.loc[defense_indices, ['nearest_teammate_dis_y']] = defense_pos[np.argmin(defense_distance_matrix, axis=1), 1]
|
| 263 |
+
else:
|
| 264 |
+
if np.any(offense_indices):
|
| 265 |
+
offense_distance_matrix = cdist(offense_pos, offense_pos, metric='euclidean')
|
| 266 |
+
np.fill_diagonal(offense_distance_matrix, self.MAXIMUM_DIS)
|
| 267 |
+
X.loc[offense_indices, ['distance_to_defense']] = self.MAXIMUM_DIS
|
| 268 |
+
X.loc[offense_indices, ['distance_to_defense_x']] = self.MAXIMUM_DIS
|
| 269 |
+
X.loc[offense_indices, ['distance_to_defense_y']] = self.MAXIMUM_DIS
|
| 270 |
+
|
| 271 |
+
X.loc[offense_indices, ['distance_to_offense']] = 0
|
| 272 |
+
X.loc[offense_indices, ['distance_to_offense_x']] = 0
|
| 273 |
+
X.loc[offense_indices, ['distance_to_offense_y']] = 0
|
| 274 |
+
|
| 275 |
+
X.loc[offense_indices, ['nearest_teammate_dis']] = np.min(offense_distance_matrix, axis=1)
|
| 276 |
+
X.loc[offense_indices, ['nearest_teammate_dis_x']] = offense_pos[np.argmin(offense_distance_matrix, axis=1), 0]
|
| 277 |
+
X.loc[offense_indices, ['nearest_teammate_dis_y']] = offense_pos[np.argmin(offense_distance_matrix, axis=1), 1]
|
| 278 |
+
|
| 279 |
+
if np.any(defense_indices):
|
| 280 |
+
defense_distance_matrix = cdist(defense_pos, defense_pos, metric='euclidean')
|
| 281 |
+
np.fill_diagonal(defense_distance_matrix, self.MAXIMUM_DIS)
|
| 282 |
+
X.loc[defense_indices, ['distance_to_offense']] = self.MAXIMUM_DIS
|
| 283 |
+
X.loc[defense_indices, ['distance_to_offense_x']] = self.MAXIMUM_DIS
|
| 284 |
+
X.loc[defense_indices, ['distance_to_offense_y']] = self.MAXIMUM_DIS
|
| 285 |
+
|
| 286 |
+
X.loc[defense_indices, ['distance_to_defense']] = 0
|
| 287 |
+
X.loc[defense_indices, ['distance_to_defense_x']] = 0
|
| 288 |
+
X.loc[defense_indices, ['distance_to_defense_y']] = 0
|
| 289 |
+
|
| 290 |
+
X.loc[defense_indices, ['nearest_teammate_dis']] = np.min(defense_distance_matrix, axis=1)
|
| 291 |
+
X.loc[defense_indices, ['nearest_teammate_dis_x']] = defense_pos[np.argmin(defense_distance_matrix, axis=1), 0]
|
| 292 |
+
X.loc[defense_indices, ['nearest_teammate_dis_y']] = defense_pos[np.argmin(defense_distance_matrix, axis=1), 1]
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
X = pd.get_dummies(X, columns=['player_role'], dtype=np.float32)
|
| 296 |
+
|
| 297 |
+
X['required_velocity_x'] = X['distance_to_ball_land_x'] / X['time_left']
|
| 298 |
+
X['required_velocity_y'] = X['distance_to_ball_land_y'] / X['time_left']
|
| 299 |
+
|
| 300 |
+
X['required_acc_x'] = (X['required_velocity_x'] - X['velocity_x']) / X['time_left']
|
| 301 |
+
X['required_acc_y'] = (X['required_velocity_y'] - X['velocity_y']) / X['time_left']
|
| 302 |
+
|
| 303 |
+
X['required_speed_diff'] = X['required_speed'] - X['s']
|
| 304 |
+
X['required_velocity_x_diff'] = X['required_velocity_x'] - X['velocity_x']
|
| 305 |
+
X['required_velocity_y_diff'] = X['required_velocity_y'] - X['velocity_y']
|
| 306 |
+
|
| 307 |
+
X['required_acc_x_diff'] = X['required_acc_x'] - X['acc_x']
|
| 308 |
+
X['required_acc_y_diff'] = X['required_acc_y'] - X['acc_y']
|
| 309 |
+
|
| 310 |
+
X['proj_x_acc'] = X['x'] + X['velocity_x']*X['time_left'] + 0.5*X['acc_x']*(X['time_left']**2)
|
| 311 |
+
X['proj_y_acc'] = X['y'] + X['velocity_y']*X['time_left'] + 0.5*X['acc_y']*(X['time_left']**2)
|
| 312 |
+
|
| 313 |
+
X['proj_x_velocity'] = X['x'] + X['velocity_x']*X['time_left']
|
| 314 |
+
X['proj_y_velocity'] = X['y'] + X['velocity_y']*X['time_left']
|
| 315 |
+
|
| 316 |
+
X['proj_x_acc_diff'] = X['ball_land_x'] - X['proj_x_acc']
|
| 317 |
+
X['proj_y_acc_diff'] = X['ball_land_y'] - X['proj_y_acc']
|
| 318 |
+
|
| 319 |
+
X['proj_x_velocity_diff'] = X['ball_land_x'] - X['proj_x_velocity']
|
| 320 |
+
X['proj_y_velocity_diff'] = X['ball_land_y'] - X['proj_y_velocity']
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
X['angle_between_orientation_and_player'] = self._change_in_angle(X['o'], X['dir'])
|
| 324 |
+
year = date.today().year
|
| 325 |
+
|
| 326 |
+
parsed = pd.to_datetime(X['player_birth_date'], format="%Y-%m-%d")
|
| 327 |
+
|
| 328 |
+
X['player_age'] = year - parsed.dt.year
|
| 329 |
+
X['player_height'] = self._convert_to_inches(X['player_height'])
|
| 330 |
+
X['player_weight'] = X['player_weight']
|
| 331 |
+
|
| 332 |
+
X['absolute_yardline_number'] = np.clip(X['absolute_yardline_number'], 0, 100.0)
|
| 333 |
+
|
| 334 |
+
return X
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
from torch.utils.data import Dataset, get_worker_info
|
| 338 |
+
import os
|
| 339 |
+
import random
|
| 340 |
+
|
| 341 |
+
class NFLDataset(Dataset):
|
| 342 |
+
def __init__(self, input_groups, output_groups, nfl_feature_transformer, shuffle=True):
|
| 343 |
+
self.nfl_feature_transformer = nfl_feature_transformer
|
| 344 |
+
self.input_groups = input_groups
|
| 345 |
+
self.output_groups = output_groups
|
| 346 |
+
|
| 347 |
+
self.indices = list(range(len(input_groups)))
|
| 348 |
+
if shuffle:
|
| 349 |
+
random.shuffle(self.indices)
|
| 350 |
+
self.input_groups = input_groups
|
| 351 |
+
self.output_groups = output_groups
|
| 352 |
+
|
| 353 |
+
def _get_output_array(self, dx, dy):
|
| 354 |
+
numpy_array = np.column_stack((dx, dy)).astype(np.float32)
|
| 355 |
+
return np.expand_dims(numpy_array, axis=1)
|
| 356 |
+
|
| 357 |
+
def _get_input_array(self, df):
|
| 358 |
+
model_input_features = MODEL_INPUT_FEATURES
|
| 359 |
+
numpy_array = df[model_input_features].to_numpy().astype(np.float32)
|
| 360 |
+
return np.expand_dims(numpy_array, axis=1)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def __len__(self):
|
| 364 |
+
return len(self.input_groups)
|
| 365 |
+
|
| 366 |
+
def __getitem__(self, indx):
|
| 367 |
+
val_indx = self.indices[indx]
|
| 368 |
+
input_df = self.input_groups[val_indx].copy()
|
| 369 |
+
output_df = self.output_groups[val_indx].copy()
|
| 370 |
+
|
| 371 |
+
play_direction = input_df.iloc[0]['play_direction']
|
| 372 |
+
|
| 373 |
+
input_df = self.nfl_feature_transformer.reflect_input_coordinates(input_df, play_direction)
|
| 374 |
+
output_df = self.nfl_feature_transformer.reflect_output_coordinates(output_df, play_direction)
|
| 375 |
+
|
| 376 |
+
given_frames = input_df['frame_id'].max()
|
| 377 |
+
output_frames = input_df['num_frames_output'].iloc[0]
|
| 378 |
+
|
| 379 |
+
total_frames = given_frames + output_frames
|
| 380 |
+
|
| 381 |
+
min_frame_start = max(given_frames - 10, 1)
|
| 382 |
+
|
| 383 |
+
prev_frame = None
|
| 384 |
+
x = None
|
| 385 |
+
for f in range(min_frame_start, given_frames+1):
|
| 386 |
+
|
| 387 |
+
grouped_frame = input_df[input_df['frame_id'] == f].sort_values(by=['nfl_id'], ascending=[True]).reset_index(drop=True)
|
| 388 |
+
|
| 389 |
+
prev_frame = grouped_frame if prev_frame is None else prev_frame
|
| 390 |
+
transformed_input_df = self.nfl_feature_transformer.transform_X(grouped_frame, prev_frame, total_frames)
|
| 391 |
+
input_array = self._get_input_array(transformed_input_df)
|
| 392 |
+
x = input_array if x is None else np.concat((x, input_array), axis=1)
|
| 393 |
+
prev_frame = grouped_frame
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
num_output = prev_frame['num_frames_output'].iloc[0] # type: ignore
|
| 397 |
+
players_to_predict = prev_frame['player_to_predict'].values.tolist() # type: ignore
|
| 398 |
+
|
| 399 |
+
x_last = prev_frame[prev_frame['player_to_predict']]['x'].values # type: ignore
|
| 400 |
+
y_last = prev_frame[prev_frame['player_to_predict']]['y'].values # type: ignore
|
| 401 |
+
|
| 402 |
+
y = None
|
| 403 |
+
for f in range(1, output_frames+1):
|
| 404 |
+
|
| 405 |
+
grouped_frame = output_df[output_df['frame_id'] == f].sort_values(by=['nfl_id'], ascending=[True]).reset_index(drop=True)
|
| 406 |
+
|
| 407 |
+
dx = grouped_frame['x'] - x_last
|
| 408 |
+
dy = grouped_frame['y'] - y_last
|
| 409 |
+
|
| 410 |
+
output_tensor = self._get_output_array(dx, dy)
|
| 411 |
+
y = output_tensor if y is None else np.concat((y, output_tensor), axis=1)
|
| 412 |
+
|
| 413 |
+
return x, y, players_to_predict, num_output
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
import os
|
| 417 |
+
def get_train_file_paths():
|
| 418 |
+
|
| 419 |
+
def get_output_file(input_filename):
|
| 420 |
+
return input_filename.replace('input', 'output')
|
| 421 |
+
|
| 422 |
+
input_file_paths = []
|
| 423 |
+
output_file_paths = []
|
| 424 |
+
input_files_dir = TRAIN_INPUT_FILE_PATH
|
| 425 |
+
for w in range(1, 19):
|
| 426 |
+
input_filename = f'input_2023_w{w:02d}.csv'
|
| 427 |
+
if os.path.isfile(f'{input_files_dir}/{input_filename}'):
|
| 428 |
+
output_filename = get_output_file(input_filename)
|
| 429 |
+
input_file_path = os.path.join(TRAIN_INPUT_FILE_PATH, input_filename)
|
| 430 |
+
output_file_path = os.path.join(TRAIN_OUTPUT_FILE_PATH, output_filename)
|
| 431 |
+
input_file_paths.append(input_file_path)
|
| 432 |
+
output_file_paths.append(output_file_path)
|
| 433 |
+
else:
|
| 434 |
+
raise Exception(f'input file for week {w} does not exist')
|
| 435 |
+
|
| 436 |
+
return (input_file_paths, output_file_paths)
|
| 437 |
+
|
| 438 |
+
import random
|
| 439 |
+
import pandas as pd
|
| 440 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 441 |
+
|
| 442 |
+
def load_file(file_path):
|
| 443 |
+
return pd.read_csv(file_path)
|
| 444 |
+
|
| 445 |
+
def get_input_output_df():
|
| 446 |
+
input_file_paths, output_file_paths = get_train_file_paths()
|
| 447 |
+
|
| 448 |
+
with ThreadPoolExecutor(max_workers = 8) as executor:
|
| 449 |
+
input_dfs = executor.map(load_file, input_file_paths)
|
| 450 |
+
input_df = pd.concat(input_dfs, axis=0)
|
| 451 |
+
|
| 452 |
+
with ThreadPoolExecutor(max_workers = 8) as executor:
|
| 453 |
+
output_dfs = executor.map(load_file, output_file_paths)
|
| 454 |
+
output_df = pd.concat(output_dfs, axis=0)
|
| 455 |
+
|
| 456 |
+
return input_df.reset_index(drop=True), output_df.reset_index(drop=True)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
import random
|
| 460 |
+
def split_train_test(input_df, output_df, nfl_feature_transformer, test_ratio = 0.2):
|
| 461 |
+
|
| 462 |
+
input_groups = [group for _, group in input_df.groupby(by=['game_id', 'play_id'], sort=True)]
|
| 463 |
+
output_groups = [group for _, group in output_df.groupby(by=['game_id', 'play_id'], sort=True)]
|
| 464 |
+
|
| 465 |
+
n_groups = len(input_groups)
|
| 466 |
+
|
| 467 |
+
test_start = int(n_groups - n_groups*(test_ratio))
|
| 468 |
+
|
| 469 |
+
train_input_groups, train_output_groups = input_groups[:test_start], output_groups[:test_start]
|
| 470 |
+
train_data = NFLDataset(train_input_groups, train_output_groups, nfl_feature_transformer)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
test_input_groups, test_output_groups = input_groups[test_start:], output_groups[test_start:]
|
| 474 |
+
test_data = NFLDataset(test_input_groups, test_output_groups, nfl_feature_transformer, shuffle=False)
|
| 475 |
+
|
| 476 |
+
return train_data, test_data
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# %%
|
| 481 |
+
from torch.nn import TransformerEncoder, TransformerEncoderLayer, GRU, Linear, Module, MSELoss, MultiheadAttention, Sequential, Linear, ReLU, Dropout
|
| 482 |
+
from positional_encodings.torch_encodings import PositionalEncoding1D
|
| 483 |
+
|
| 484 |
+
class SpatialTemporalLayer(Module):
|
| 485 |
+
def __init__(self, d_model, nhead, spatial_encoder_layers, dropout, in_features):
|
| 486 |
+
|
| 487 |
+
super().__init__()
|
| 488 |
+
|
| 489 |
+
features_to_predict = 2
|
| 490 |
+
dim_feedforward = 2*d_model
|
| 491 |
+
|
| 492 |
+
transformer_encoder_layer = TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward,
|
| 493 |
+
dropout=dropout, batch_first=True)
|
| 494 |
+
|
| 495 |
+
self.se_input_projection = Linear(in_features = in_features, out_features = d_model)
|
| 496 |
+
|
| 497 |
+
self.spatial_encoder = TransformerEncoder(encoder_layer=transformer_encoder_layer,enable_nested_tensor=False, num_layers=spatial_encoder_layers)
|
| 498 |
+
|
| 499 |
+
self.temporal_encoder = GRU(input_size=d_model, hidden_size=d_model, num_layers=1, batch_first=True)
|
| 500 |
+
self.temporal_decoder = GRU(input_size=features_to_predict, hidden_size=d_model, num_layers=1, batch_first=True)
|
| 501 |
+
self.td_output_projection = Linear(in_features = d_model, out_features = features_to_predict)
|
| 502 |
+
|
| 503 |
+
self.cross_attn = MultiheadAttention(embed_dim=d_model, num_heads=nhead, batch_first=True)
|
| 504 |
+
self.gate = Linear(2 * d_model, d_model)
|
| 505 |
+
|
| 506 |
+
self.mlp = Sequential(
|
| 507 |
+
Linear(d_model, 2*d_model),
|
| 508 |
+
ReLU(),
|
| 509 |
+
Linear(2*d_model, 2*d_model),
|
| 510 |
+
ReLU(),
|
| 511 |
+
Linear(2*d_model, 1)
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
self.mse_loss = MSELoss(reduction='mean')
|
| 515 |
+
self.sum_se = MSELoss(reduction='sum')
|
| 516 |
+
|
| 517 |
+
self.pos_enc = PositionalEncoding1D(d_model)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
#x must be [P, T, din] T-> time in a play_id , P --> number of players of that play_id, din --> input_feature
|
| 521 |
+
#y must be in [P, T, 2]
|
| 522 |
+
def forward(self, x, y, predict_bool, num_output):
|
| 523 |
+
|
| 524 |
+
#converts to d_model
|
| 525 |
+
x_projected = self.se_input_projection(x)
|
| 526 |
+
|
| 527 |
+
time_encodings = self.pos_enc(x_projected)
|
| 528 |
+
x_encodings_added = time_encodings + x_projected
|
| 529 |
+
|
| 530 |
+
x_permuted = x_encodings_added.permute(1, 0, 2)
|
| 531 |
+
|
| 532 |
+
se_output = self.spatial_encoder(x_permuted)
|
| 533 |
+
|
| 534 |
+
predict_players_x = x_projected[predict_bool, :, :]
|
| 535 |
+
|
| 536 |
+
no_players = predict_players_x.shape[0]
|
| 537 |
+
d_model = predict_players_x.shape[2]
|
| 538 |
+
time = predict_players_x.shape[1]
|
| 539 |
+
|
| 540 |
+
hidden_state = torch.zeros(1, no_players, d_model, device=predict_players_x.device)
|
| 541 |
+
for t in range(time):
|
| 542 |
+
query = predict_players_x[:,t, :]
|
| 543 |
+
key = se_output[t, :,:]
|
| 544 |
+
value = se_output[t, :,:]
|
| 545 |
+
|
| 546 |
+
cross_attn_output = self.cross_attn(query, key, value, need_weights=False)[0].unsqueeze(0)
|
| 547 |
+
|
| 548 |
+
combined = torch.cat([hidden_state, cross_attn_output], dim=-1)
|
| 549 |
+
g = torch.sigmoid(self.gate(combined))
|
| 550 |
+
|
| 551 |
+
hidden_state = g * hidden_state + (1 - g) * cross_attn_output
|
| 552 |
+
|
| 553 |
+
gru_output, hidden_state = self.temporal_encoder(predict_players_x[:,t:t+1, :], hidden_state)
|
| 554 |
+
|
| 555 |
+
time_expanded_state = gru_output.repeat(1, num_output, 1)
|
| 556 |
+
encodings = self.pos_enc(time_expanded_state)
|
| 557 |
+
encodings_added = time_expanded_state + encodings
|
| 558 |
+
|
| 559 |
+
preds = self.mlp(encodings_added)
|
| 560 |
+
|
| 561 |
+
preds_reshaped = preds.reshape(-1, 1)
|
| 562 |
+
preds_detached=preds_reshaped.detach()
|
| 563 |
+
|
| 564 |
+
if y is None:
|
| 565 |
+
return preds_detached
|
| 566 |
+
|
| 567 |
+
actual_reshaped = y.reshape(-1, 1)
|
| 568 |
+
|
| 569 |
+
return self.mse_loss(preds_reshaped, actual_reshaped), self.sum_se(preds_reshaped, actual_reshaped), preds_detached
|
| 570 |
+
|
| 571 |
+
def checkpoint_state(epoch, model, optimizer, checkpoint_dir):
|
| 572 |
+
directory = checkpoint_dir
|
| 573 |
+
checkpoint = {'model_state': model.state_dict(), 'optimizer_state': optimizer.state_dict()}
|
| 574 |
+
|
| 575 |
+
new_file_name = f'checkpoint-{epoch}.pt'
|
| 576 |
+
old_file_name = f'checkpoint-{epoch - 1}.pt'
|
| 577 |
+
|
| 578 |
+
# flush previous checkpoints
|
| 579 |
+
for item in os.listdir(directory):
|
| 580 |
+
item_path = os.path.join(directory, item)
|
| 581 |
+
if os.path.isfile(item_path) and item.startswith('checkpoint-') and item != old_file_name:
|
| 582 |
+
os.remove(item_path)
|
| 583 |
+
|
| 584 |
+
file_path = os.path.join(directory, new_file_name)
|
| 585 |
+
|
| 586 |
+
torch.save(checkpoint, file_path)
|
| 587 |
+
|
| 588 |
+
def setup_state_from_checkpoint(model, optimizer, checkpoint_dir, best_model_checkpoint_loc, device='cuda'):
|
| 589 |
+
latest_epoch = -1
|
| 590 |
+
directory = checkpoint_dir
|
| 591 |
+
for item in os.listdir(directory):
|
| 592 |
+
item_path = os.path.join(directory, item)
|
| 593 |
+
if os.path.isfile(item_path) and item.startswith('checkpoint-'):
|
| 594 |
+
epoch = int(item.removeprefix('checkpoint-').removesuffix('.pt'))
|
| 595 |
+
latest_epoch = max(epoch, latest_epoch)
|
| 596 |
+
|
| 597 |
+
if latest_epoch == -1:
|
| 598 |
+
print('no existing checkpoint found')
|
| 599 |
+
return 0, math.inf
|
| 600 |
+
|
| 601 |
+
print(f'resuming states with {latest_epoch} checkpoint')
|
| 602 |
+
checkpoint_pt = torch.load(os.path.join(directory, f'checkpoint-{latest_epoch}.pt'), map_location=device)
|
| 603 |
+
model.load_state_dict(checkpoint_pt['model_state'])
|
| 604 |
+
if 'optimizer_state' in checkpoint_pt:
|
| 605 |
+
optimizer.load_state_dict(checkpoint_pt['optimizer_state'], )
|
| 606 |
+
|
| 607 |
+
best_val = 0
|
| 608 |
+
if os.path.isfile(best_model_checkpoint_loc):
|
| 609 |
+
ckpt = torch.load(best_model_checkpoint_loc)
|
| 610 |
+
best_val = ckpt['best_val']
|
| 611 |
+
|
| 612 |
+
return latest_epoch + 1, best_val
|
| 613 |
+
|
| 614 |
+
def scale_features(std_scaler, X):
|
| 615 |
+
p, t, din = X.shape[0], X.shape[1], X.shape[2]
|
| 616 |
+
X_reshaped = X.reshape(p * t, din)
|
| 617 |
+
X_scaled = std_scaler.transform(X_reshaped).reshape(p, t, din)
|
| 618 |
+
return torch.tensor(X_scaled, dtype=torch.float32)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
import math
|
| 622 |
+
class ValidationDatasetMetric:
|
| 623 |
+
|
| 624 |
+
def __init__(self, model, validation_dataset, std_scaler, model_type = ModelType.DX_MODEL):
|
| 625 |
+
self.model = model
|
| 626 |
+
self.validation_dataset = validation_dataset
|
| 627 |
+
self.std_scaler = std_scaler
|
| 628 |
+
self.model_type = model_type
|
| 629 |
+
batch_size = 1
|
| 630 |
+
self.validation_dataset_dataloader = DataLoader(validation_dataset, batch_size=batch_size, pin_memory=True, in_order=False)
|
| 631 |
+
|
| 632 |
+
def get_metrics(self):
|
| 633 |
+
|
| 634 |
+
self.model.eval()
|
| 635 |
+
self.model.to('cuda')
|
| 636 |
+
|
| 637 |
+
loop = tqdm(self.validation_dataset_dataloader, total=len(self.validation_dataset_dataloader), desc=f"validating {self.model_type}")
|
| 638 |
+
|
| 639 |
+
se_sum = 0
|
| 640 |
+
instances = 0
|
| 641 |
+
with torch.no_grad():
|
| 642 |
+
for (x, y, predict_bool, num_output) in loop:
|
| 643 |
+
|
| 644 |
+
x_ = scale_features(self.std_scaler, x.squeeze(0)).to('cuda')
|
| 645 |
+
|
| 646 |
+
if self.model_type == ModelType.DX_MODEL:
|
| 647 |
+
y_ = y[0,:,:,0]
|
| 648 |
+
else:
|
| 649 |
+
y_ = y[0,:,:,1]
|
| 650 |
+
|
| 651 |
+
y_ = torch.as_tensor(y_, dtype=torch.float32, device='cuda')
|
| 652 |
+
predict_bool_ = torch.tensor(predict_bool, device='cuda')
|
| 653 |
+
num_output_ = int(num_output.item())
|
| 654 |
+
|
| 655 |
+
output = self.model(x_, y_, predict_bool_, num_output_)
|
| 656 |
+
|
| 657 |
+
se_sum+= output[1].item()
|
| 658 |
+
instances+=y_.numel()
|
| 659 |
+
|
| 660 |
+
del output
|
| 661 |
+
|
| 662 |
+
mse = (se_sum / instances)
|
| 663 |
+
rmse = math.sqrt(mse)
|
| 664 |
+
return mse, rmse, se_sum, instances
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def evaluate(self):
|
| 669 |
+
avg_mse, avg_rmse, se_sum, instances = self.get_metrics()
|
| 670 |
+
return {'valid_mse': avg_mse , 'valid_rmse': avg_rmse, 'se_sum':se_sum, 'instances' : instances}
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
from torch.utils.data import DataLoader
|
| 677 |
+
import time
|
| 678 |
+
from torch.nn.utils import clip_grad_norm_
|
| 679 |
+
from tqdm import tqdm
|
| 680 |
+
import math
|
| 681 |
+
|
| 682 |
+
class Runner:
|
| 683 |
+
|
| 684 |
+
def __init__(self, model, train_data, test_data, std_scaler, model_type = ModelType.DX_MODEL, lr=5e-5, wd=1e-4):
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
batch_size = 1
|
| 688 |
+
self.train_data_loader = DataLoader(train_data, batch_size=batch_size, pin_memory=True, in_order=False)
|
| 689 |
+
self.model = model
|
| 690 |
+
|
| 691 |
+
self.std_scaler = std_scaler
|
| 692 |
+
|
| 693 |
+
self.validation_dataset_metric = ValidationDatasetMetric(self.model, test_data, std_scaler, model_type=model_type)
|
| 694 |
+
|
| 695 |
+
self.model_type = model_type
|
| 696 |
+
|
| 697 |
+
if self.model_type == ModelType.DX_MODEL:
|
| 698 |
+
self.best_model_checkpoint_loc = BEST_DX_MODEL_CHECKPOINT
|
| 699 |
+
self.checkpoint_dir = DX_CHECKPOINT_DIR
|
| 700 |
+
else:
|
| 701 |
+
self.best_model_checkpoint_loc = BEST_DY_MODEL_CHECKPOINT
|
| 702 |
+
self.checkpoint_dir = DY_CHECKPOINT_DIR
|
| 703 |
+
|
| 704 |
+
self.trainable_params = []
|
| 705 |
+
for _, param in self.model.named_parameters():
|
| 706 |
+
self.trainable_params.append(param)
|
| 707 |
+
|
| 708 |
+
self.optimizer = torch.optim.AdamW(self.trainable_params, lr=lr, weight_decay=wd)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
def run(self):
|
| 713 |
+
|
| 714 |
+
resume = False
|
| 715 |
+
new_lr = 1e-5
|
| 716 |
+
self.model.to('cuda')
|
| 717 |
+
|
| 718 |
+
if resume:
|
| 719 |
+
start_epoch, best_val = setup_state_from_checkpoint(self.model, self.optimizer, self.checkpoint_dir, self.best_model_checkpoint_loc)
|
| 720 |
+
for param_group in self.optimizer.param_groups:
|
| 721 |
+
param_group['lr'] = new_lr
|
| 722 |
+
else:
|
| 723 |
+
start_epoch = 0
|
| 724 |
+
best_val = math.inf
|
| 725 |
+
|
| 726 |
+
end_epoch = start_epoch + 10
|
| 727 |
+
for epoch in range(start_epoch, end_epoch):
|
| 728 |
+
|
| 729 |
+
loop = tqdm(self.train_data_loader, total=len(self.train_data_loader), desc=f"Epoch {epoch}")
|
| 730 |
+
start = time.perf_counter()
|
| 731 |
+
|
| 732 |
+
se_sum = 0
|
| 733 |
+
instances = 0
|
| 734 |
+
step = 0
|
| 735 |
+
for (x, y, predict_bool, num_output) in loop:
|
| 736 |
+
|
| 737 |
+
x_ = scale_features(self.std_scaler, x.squeeze(0)).to('cuda')
|
| 738 |
+
if self.model_type == ModelType.DX_MODEL:
|
| 739 |
+
y_ = y[0,:,:,0]
|
| 740 |
+
else:
|
| 741 |
+
y_ = y[0,:,:,1]
|
| 742 |
+
|
| 743 |
+
y_ = torch.as_tensor(y_, dtype=torch.float32, device='cuda')
|
| 744 |
+
predict_bool_ = torch.tensor(predict_bool, device='cuda')
|
| 745 |
+
|
| 746 |
+
num_output_ = int(num_output.item())
|
| 747 |
+
|
| 748 |
+
output = self.model(x_, y_, predict_bool_, num_output_)
|
| 749 |
+
|
| 750 |
+
se_sum+= output[1].item()
|
| 751 |
+
|
| 752 |
+
instances+=y_.numel()
|
| 753 |
+
|
| 754 |
+
mse_loss = output[0]
|
| 755 |
+
mse_loss.backward()
|
| 756 |
+
|
| 757 |
+
gradient_before_clipping = clip_grad_norm_(self.trainable_params, max_norm=1, foreach=True)
|
| 758 |
+
self.optimizer.step()
|
| 759 |
+
self.optimizer.zero_grad()
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
loop.set_postfix({
|
| 763 |
+
'gradient': gradient_before_clipping.item(),
|
| 764 |
+
'step': step,
|
| 765 |
+
'loss': mse_loss.item(),
|
| 766 |
+
'learning_rates': '[' + ','.join(
|
| 767 |
+
[str(param_group['lr']) for param_group in self.optimizer.state_dict()['param_groups']]) + ']'
|
| 768 |
+
}
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
step += 1
|
| 773 |
+
|
| 774 |
+
del output, mse_loss, x_, y_, predict_bool_
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
mse = se_sum / instances
|
| 778 |
+
rmse = math.sqrt(mse)
|
| 779 |
+
metrics = self.validation_dataset_metric.evaluate()
|
| 780 |
+
valid_mse = metrics['valid_mse']
|
| 781 |
+
valid_rmse = metrics['valid_rmse']
|
| 782 |
+
|
| 783 |
+
score = valid_rmse
|
| 784 |
+
if score < best_val:
|
| 785 |
+
torch.save({'model_state': self.model.state_dict(), 'best_val': score}, self.best_model_checkpoint_loc)
|
| 786 |
+
best_val = score
|
| 787 |
+
|
| 788 |
+
end = time.perf_counter()
|
| 789 |
+
print(f'{{ step {step} train_avg_mse: {mse}, train_avg_rmse : {rmse} \n valid_avg_mse: {valid_mse} valid_avg_rmse:{valid_rmse} took {end - start:.3f} seconds}}')
|
| 790 |
+
checkpoint_state(epoch, self.model, self.optimizer, self.checkpoint_dir)
|
| 791 |
+
self.model.train()
|
| 792 |
+
se_sum = 0
|
| 793 |
+
instances = 0
|
| 794 |
+
|
| 795 |
+
def train(model, train_data, test_data, std_scaler, model_type = ModelType.DX_MODEL):
|
| 796 |
+
runner = Runner(model, train_data, test_data, std_scaler, model_type, lr=1e-4, wd=1e-4)
|
| 797 |
+
runner.run()
|
| 798 |
+
|
| 799 |
+
def evaluate_metrics(dx_model, dy_model, test_data, std_scaler):
|
| 800 |
+
|
| 801 |
+
dx_checkpoint_pt = torch.load(BEST_DX_MODEL_CHECKPOINT, map_location='cpu')
|
| 802 |
+
dx_model.load_state_dict(dx_checkpoint_pt['model_state'])
|
| 803 |
+
|
| 804 |
+
dx_validation_dataset_metric = ValidationDatasetMetric(dx_model, test_data, std_scaler, model_type=ModelType.DX_MODEL)
|
| 805 |
+
dx_metrics = dx_validation_dataset_metric.evaluate()
|
| 806 |
+
|
| 807 |
+
dy_checkpoint_pt = torch.load(BEST_DY_MODEL_CHECKPOINT, map_location='cpu')
|
| 808 |
+
dy_model.load_state_dict(dy_checkpoint_pt['model_state'])
|
| 809 |
+
|
| 810 |
+
dy_validation_dataset_metric = ValidationDatasetMetric(dy_model, test_data, std_scaler, model_type=ModelType.DY_MODEL)
|
| 811 |
+
dy_metrics = dy_validation_dataset_metric.evaluate()
|
| 812 |
+
|
| 813 |
+
total_se_sum = dx_metrics['se_sum'] + dy_metrics['se_sum']
|
| 814 |
+
total_instances = dx_metrics['instances'] + dy_metrics['instances']
|
| 815 |
+
avg_mse = total_se_sum / total_instances if total_instances > 0 else 0
|
| 816 |
+
avg_rmse = math.sqrt(avg_mse)
|
| 817 |
+
|
| 818 |
+
avg_rmse_x = np.sqrt(dx_metrics['se_sum'] / dx_metrics['instances'])
|
| 819 |
+
avg_rmse_y = np.sqrt(dy_metrics['se_sum'] / dy_metrics['instances'])
|
| 820 |
+
print(f'model rmse on the test dataset on dx {avg_rmse_x}')
|
| 821 |
+
print(f'model rmse on the test dataset on dy {avg_rmse_y}')
|
| 822 |
+
print(f'model rmse on test dataset: {avg_rmse}')
|
| 823 |
+
|
| 824 |
+
def predict(dx_model, dy_model, test_data, std_scaler):
|
| 825 |
+
|
| 826 |
+
dx_checkpoint_pt = torch.load(BEST_DX_MODEL_CHECKPOINT, map_location='cpu')
|
| 827 |
+
dx_model.load_state_dict(dx_checkpoint_pt['model_state'])
|
| 828 |
+
|
| 829 |
+
dy_checkpoint_pt = torch.load(BEST_DY_MODEL_CHECKPOINT, map_location='cpu')
|
| 830 |
+
dy_model.load_state_dict(dy_checkpoint_pt['model_state'])
|
| 831 |
+
|
| 832 |
+
dx_model.eval()
|
| 833 |
+
dx_model.to('cuda')
|
| 834 |
+
|
| 835 |
+
dy_model.eval()
|
| 836 |
+
dy_model.to('cuda')
|
| 837 |
+
|
| 838 |
+
n = len(test_data)
|
| 839 |
+
|
| 840 |
+
preds = []
|
| 841 |
+
with torch.no_grad():
|
| 842 |
+
for t in tqdm(range(n), total=n, desc = 'predict'):
|
| 843 |
+
input_df = test_data.input_groups[t]
|
| 844 |
+
output_df = test_data.output_groups[t]
|
| 845 |
+
|
| 846 |
+
(x, _, predict_bool, num_output) = test_data[t]
|
| 847 |
+
x_ = scale_features(std_scaler, x).to('cuda') # type: ignore
|
| 848 |
+
|
| 849 |
+
predict_bool_ = torch.tensor(predict_bool, device='cuda')
|
| 850 |
+
num_output_ = int(num_output.item())
|
| 851 |
+
|
| 852 |
+
dx = dx_model(x_, None, predict_bool_, num_output_)
|
| 853 |
+
|
| 854 |
+
dy = dy_model(x_, None, predict_bool_, num_output_)
|
| 855 |
+
|
| 856 |
+
predict_players = input_df[input_df['player_to_predict']]
|
| 857 |
+
max_frame_id = predict_players['frame_id'].max()
|
| 858 |
+
predict_players_last_frame = predict_players[predict_players['frame_id'] == max_frame_id]
|
| 859 |
+
|
| 860 |
+
predict_players_output_frames = ( predict_players_last_frame.merge(output_df, on=['nfl_id'], how='left')
|
| 861 |
+
.sort_values(by=['nfl_id', 'frame_id_y']).reset_index(drop=True)
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
f = 1
|
| 865 |
+
if predict_players_output_frames['play_direction'].iloc[0] == 'left':
|
| 866 |
+
f = -1
|
| 867 |
+
|
| 868 |
+
pred_x = predict_players_output_frames['x_x'].values + f*dx[:,0].cpu().numpy()
|
| 869 |
+
pred_y = predict_players_output_frames['y_x'].values + dy[:,0].cpu().numpy()
|
| 870 |
+
|
| 871 |
+
game_id = predict_players_output_frames['game_id_x'].values
|
| 872 |
+
play_id = predict_players_output_frames['play_id_x'].values
|
| 873 |
+
nfl_id = predict_players_output_frames['nfl_id'].values
|
| 874 |
+
frame_id = predict_players_output_frames['frame_id_y'].values
|
| 875 |
+
player_position = predict_players_output_frames['player_position'].values
|
| 876 |
+
player_role = predict_players_output_frames['player_role'].values
|
| 877 |
+
x_last = predict_players_output_frames['x_x'].values
|
| 878 |
+
y_last = predict_players_output_frames['y_x'].values
|
| 879 |
+
play_direction = predict_players_output_frames['play_direction'].values
|
| 880 |
+
|
| 881 |
+
actual_x = predict_players_output_frames['x_y'].values
|
| 882 |
+
actual_y = predict_players_output_frames['y_y'].values
|
| 883 |
+
|
| 884 |
+
pred_x = np.clip(pred_x, 0.0, 120.0)
|
| 885 |
+
pred_y = np.clip(pred_y, 0.0, 53.3)
|
| 886 |
+
|
| 887 |
+
columns = np.column_stack([game_id, play_id, nfl_id, frame_id, player_position,
|
| 888 |
+
player_role,play_direction,x_last, y_last, actual_x, actual_y, pred_x, pred_y])
|
| 889 |
+
|
| 890 |
+
preds.append(columns)
|
| 891 |
+
|
| 892 |
+
combined = np.concat(preds, axis=0)
|
| 893 |
+
df = pd.DataFrame(combined, columns=['game_id', 'play_id', 'nfl_id','frame_id', 'player_position',
|
| 894 |
+
'player_role','play_direction', 'x_last', 'y_last',
|
| 895 |
+
'actual_x', 'actual_y', 'pred_x', 'pred_y'])
|
| 896 |
+
|
| 897 |
+
df.to_csv('gru_test_data_results.csv', index=False)
|
| 898 |
+
print('results published')
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def train_test():
|
| 903 |
+
import joblib
|
| 904 |
+
from sklearn.preprocessing import StandardScaler
|
| 905 |
+
|
| 906 |
+
def save_joblib(train_data):
|
| 907 |
+
|
| 908 |
+
def get_x(n):
|
| 909 |
+
x,_,_,_ = train_data[n]
|
| 910 |
+
p = x.shape[0]
|
| 911 |
+
t = x.shape[1]
|
| 912 |
+
din = x.shape[2]
|
| 913 |
+
|
| 914 |
+
print(n)
|
| 915 |
+
return x.reshape(p*t, din)
|
| 916 |
+
|
| 917 |
+
percentage_of_sample = 0.02
|
| 918 |
+
sample_n = int(len(train_data)*percentage_of_sample)
|
| 919 |
+
sample_range = range(sample_n)
|
| 920 |
+
with ThreadPoolExecutor(max_workers = 12) as executor:
|
| 921 |
+
all_x = executor.map(get_x, sample_range)
|
| 922 |
+
combined_x = np.concat(list(all_x),axis=0)
|
| 923 |
+
|
| 924 |
+
std_scaler = StandardScaler()
|
| 925 |
+
std_scaler.fit(combined_x)
|
| 926 |
+
|
| 927 |
+
joblib.dump(std_scaler, JOBLIB_FILE_PATH)
|
| 928 |
+
return std_scaler
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
def load_scaler():
|
| 932 |
+
return joblib.load(JOBLIB_FILE_PATH)
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
print('loading dataframes...')
|
| 936 |
+
input_df, output_df = get_input_output_df()
|
| 937 |
+
|
| 938 |
+
print('splitting train test...')
|
| 939 |
+
nfl_feature_transformer = NFLFeatureTransformer()
|
| 940 |
+
train_data, test_data = split_train_test(input_df, output_df, nfl_feature_transformer, 0.02)
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
if not os.path.isfile(JOBLIB_FILE_PATH):
|
| 944 |
+
print('fitting scaler and saving joblib...')
|
| 945 |
+
std_scaler = save_joblib(train_data)
|
| 946 |
+
else:
|
| 947 |
+
print('loading scaler from joblib...')
|
| 948 |
+
std_scaler = load_scaler()
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
dx_model = SpatialTemporalLayer(d_model=128, nhead=8, spatial_encoder_layers=2, dropout=0.0, in_features=len(MODEL_INPUT_FEATURES))
|
| 952 |
+
dy_model = SpatialTemporalLayer(d_model=128, nhead=8, spatial_encoder_layers=2, dropout=0.0, in_features=len(MODEL_INPUT_FEATURES))
|
| 953 |
+
|
| 954 |
+
print('training models...')
|
| 955 |
+
# train(dx_model, train_data, test_data, std_scaler, model_type=ModelType.DX_MODEL)
|
| 956 |
+
# train(dy_model, train_data, test_data, std_scaler, model_type=ModelType.DY_MODEL)
|
| 957 |
+
|
| 958 |
+
# print('predicting test_data...')
|
| 959 |
+
# predict(dx_model, dy_model, test_data, std_scaler)
|
| 960 |
+
|
| 961 |
+
print('evaluating models...')
|
| 962 |
+
evaluate_metrics(dx_model, dy_model, test_data, std_scaler)
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
if __name__ == '__main__':
|
| 966 |
+
train_test()
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
|
gru_app_predict.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from gru import NFLFeatureTransformer, SpatialTemporalLayer, scale_features, MODEL_INPUT_FEATURES
|
| 2 |
+
from torch.utils.data import Dataset
|
| 3 |
+
import os
|
| 4 |
+
import numpy as np
|
| 5 |
+
import joblib
|
| 6 |
+
import torch
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class NFLDataset(Dataset):
|
| 11 |
+
def __init__(self, input_groups, nfl_feature_transformer):
|
| 12 |
+
self.nfl_feature_transformer = nfl_feature_transformer
|
| 13 |
+
self.input_groups = input_groups
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _get_output_array(self, dx, dy):
|
| 17 |
+
numpy_array = np.column_stack((dx, dy)).astype(np.float32)
|
| 18 |
+
return np.expand_dims(numpy_array, axis=1)
|
| 19 |
+
|
| 20 |
+
def _get_input_array(self, df):
|
| 21 |
+
model_input_features = MODEL_INPUT_FEATURES
|
| 22 |
+
numpy_array = df[model_input_features].to_numpy().astype(np.float32)
|
| 23 |
+
return np.expand_dims(numpy_array, axis=1)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def __len__(self):
|
| 27 |
+
return len(self.input_groups)
|
| 28 |
+
|
| 29 |
+
def __getitem__(self, indx):
|
| 30 |
+
input_df = self.input_groups[indx].copy()
|
| 31 |
+
|
| 32 |
+
play_direction = input_df.iloc[0]['play_direction']
|
| 33 |
+
|
| 34 |
+
input_df = self.nfl_feature_transformer.reflect_input_coordinates(input_df, play_direction)
|
| 35 |
+
|
| 36 |
+
given_frames = input_df['frame_id'].max()
|
| 37 |
+
output_frames = input_df['num_frames_output'].iloc[0]
|
| 38 |
+
|
| 39 |
+
total_frames = given_frames + output_frames
|
| 40 |
+
|
| 41 |
+
min_frame_start = max(given_frames - 10, 1)
|
| 42 |
+
|
| 43 |
+
prev_frame = None
|
| 44 |
+
x = None
|
| 45 |
+
for f in range(min_frame_start, given_frames+1):
|
| 46 |
+
|
| 47 |
+
grouped_frame = input_df[input_df['frame_id'] == f].sort_values(by=['nfl_id'], ascending=[True]).reset_index(drop=True)
|
| 48 |
+
|
| 49 |
+
prev_frame = grouped_frame if prev_frame is None else prev_frame
|
| 50 |
+
transformed_input_df = self.nfl_feature_transformer.transform_X(grouped_frame, prev_frame, total_frames)
|
| 51 |
+
input_array = self._get_input_array(transformed_input_df)
|
| 52 |
+
x = input_array if x is None else np.concat((x, input_array), axis=1)
|
| 53 |
+
prev_frame = grouped_frame
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
num_output = prev_frame['num_frames_output'].iloc[0] # type: ignore
|
| 57 |
+
players_to_predict = prev_frame['player_to_predict'].values.tolist() # type: ignore
|
| 58 |
+
|
| 59 |
+
return x, players_to_predict, num_output
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
JOBLIB_FILE_PATH = f'gru_scaler.joblib'
|
| 65 |
+
BEST_DX_MODEL_CHECKPOINT = f'cross_attn_best_weight_dx.pt'
|
| 66 |
+
BEST_DY_MODEL_CHECKPOINT = f'cross_attn_best_weight_dy.pt'
|
| 67 |
+
|
| 68 |
+
BASE_COLS = ['game_id', 'play_id', 'player_to_predict', 'nfl_id', 'frame_id',
|
| 69 |
+
'play_direction', 'absolute_yardline_number', 'player_name',
|
| 70 |
+
'player_height', 'player_weight', 'player_birth_date',
|
| 71 |
+
'player_position', 'player_side', 'player_role', 'x', 'y', 's', 'a',
|
| 72 |
+
'dir', 'o', 'num_frames_output', 'ball_land_x', 'ball_land_y']
|
| 73 |
+
|
| 74 |
+
MANDATORY_COLS=['game_id', 'play_id', 'nfl_id']
|
| 75 |
+
|
| 76 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
nfl_feature_transformer = NFLFeatureTransformer()
|
| 80 |
+
|
| 81 |
+
std_scaler = joblib.load(JOBLIB_FILE_PATH)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
dx_model = SpatialTemporalLayer(d_model=128, nhead=8, spatial_encoder_layers=2, dropout=0.0, in_features=len(MODEL_INPUT_FEATURES))
|
| 85 |
+
dy_model = SpatialTemporalLayer(d_model=128, nhead=8, spatial_encoder_layers=2, dropout=0.0, in_features=len(MODEL_INPUT_FEATURES))
|
| 86 |
+
|
| 87 |
+
dx_checkpoint_pt = torch.load(BEST_DX_MODEL_CHECKPOINT, map_location='cpu')
|
| 88 |
+
dx_model.load_state_dict(dx_checkpoint_pt['model_state'])
|
| 89 |
+
|
| 90 |
+
dy_checkpoint_pt = torch.load(BEST_DY_MODEL_CHECKPOINT, map_location='cpu')
|
| 91 |
+
dy_model.load_state_dict(dy_checkpoint_pt['model_state'])
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
device = 'cpu'
|
| 95 |
+
|
| 96 |
+
dx_model.eval()
|
| 97 |
+
dx_model.to(device)
|
| 98 |
+
|
| 99 |
+
dy_model.eval()
|
| 100 |
+
dy_model.to(device)
|
| 101 |
+
|
| 102 |
+
def predict(df):
|
| 103 |
+
|
| 104 |
+
given_input_cols = set(df.columns)
|
| 105 |
+
for c in MANDATORY_COLS:
|
| 106 |
+
if c not in given_input_cols:
|
| 107 |
+
raise Exception(f'{c} is missing in input')
|
| 108 |
+
elif df[c].isna().any():
|
| 109 |
+
raise Exception(f'{c} in input contains nan')
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
for c in BASE_COLS:
|
| 113 |
+
if c not in df:
|
| 114 |
+
raise Exception(f'{c} is not there in input')
|
| 115 |
+
if df[c].isna().all():
|
| 116 |
+
raise Exception(f'{c} in input contains nan')
|
| 117 |
+
|
| 118 |
+
input_groups = [group for _, group in df.groupby(by=['game_id', 'play_id'], sort=True)]
|
| 119 |
+
test_data = NFLDataset(input_groups, nfl_feature_transformer)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
n = len(test_data)
|
| 123 |
+
|
| 124 |
+
preds = []
|
| 125 |
+
with torch.no_grad():
|
| 126 |
+
for i in range(n):
|
| 127 |
+
|
| 128 |
+
df = test_data.input_groups[i]
|
| 129 |
+
|
| 130 |
+
(x, predict_bool, num_output) = test_data[i]
|
| 131 |
+
x_ = scale_features(std_scaler, x).to(device)
|
| 132 |
+
|
| 133 |
+
predict_bool_ = torch.tensor(predict_bool, device=device)
|
| 134 |
+
num_output_ = int(num_output.item())
|
| 135 |
+
|
| 136 |
+
dx = dx_model(x_, None, predict_bool_, num_output_)
|
| 137 |
+
|
| 138 |
+
dy = dy_model(x_, None, predict_bool_, num_output_)
|
| 139 |
+
|
| 140 |
+
predict_players = df[df['player_to_predict']]
|
| 141 |
+
|
| 142 |
+
#this makes sure that last available data is fetched
|
| 143 |
+
predict_players_last_frame = predict_players.sort_values(by=['frame_id']).groupby(by=['nfl_id'],
|
| 144 |
+
as_index=False, sort=False).last()
|
| 145 |
+
|
| 146 |
+
num_frames_output = predict_players['num_frames_output'].iloc[0]
|
| 147 |
+
|
| 148 |
+
output_frames_n = list(range(1, num_frames_output+1))
|
| 149 |
+
|
| 150 |
+
output_frames = pd.DataFrame(output_frames_n, columns=['frame_id'])
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
predict_players_output_frames = (predict_players_last_frame.merge(output_frames, how='cross')
|
| 154 |
+
.sort_values(by=['nfl_id', 'frame_id_y']).reset_index(drop=True)
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
f = 1
|
| 158 |
+
if predict_players_output_frames['play_direction'].iloc[0] == 'left':
|
| 159 |
+
f = -1
|
| 160 |
+
|
| 161 |
+
pred_x = predict_players_output_frames['x'].values + f*dx[:,0].cpu().numpy()
|
| 162 |
+
pred_y = predict_players_output_frames['y'].values + dy[:,0].cpu().numpy()
|
| 163 |
+
|
| 164 |
+
game_id = predict_players_output_frames['game_id'].values
|
| 165 |
+
play_id = predict_players_output_frames['play_id'].values
|
| 166 |
+
nfl_id = predict_players_output_frames['nfl_id'].values
|
| 167 |
+
frame_id = predict_players_output_frames['frame_id_y'].values
|
| 168 |
+
player_position = predict_players_output_frames['player_position'].values
|
| 169 |
+
player_role = predict_players_output_frames['player_role'].values
|
| 170 |
+
x_last = predict_players_output_frames['x'].values
|
| 171 |
+
y_last = predict_players_output_frames['y'].values
|
| 172 |
+
play_direction = predict_players_output_frames['play_direction'].values
|
| 173 |
+
|
| 174 |
+
pred_x = np.clip(pred_x, 0.0, 120.0)
|
| 175 |
+
pred_y = np.clip(pred_y, 0.0, 53.3)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
columns = np.column_stack([game_id, play_id, nfl_id, frame_id, player_position,
|
| 179 |
+
player_role,play_direction,x_last, y_last, pred_x, pred_y])
|
| 180 |
+
|
| 181 |
+
preds.append(columns)
|
| 182 |
+
|
| 183 |
+
combined = np.concat(preds, axis=0)
|
| 184 |
+
df = pd.DataFrame(combined, columns=['game_id', 'play_id', 'nfl_id','frame_id', 'player_position',
|
| 185 |
+
'player_role','play_direction', 'x_last', 'y_last', 'pred_x', 'pred_y'])
|
| 186 |
+
|
| 187 |
+
return df.sort_values(by=['game_id', 'play_id', 'nfl_id', 'frame_id'])
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
|
gru_scaler.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7a742bc33a451acc019b5528661c03576818d62b81849b3a4bcf27d2514af651
|
| 3 |
+
size 2463
|
lightGBT.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 5 |
+
import numpy as np
|
| 6 |
+
from datetime import date
|
| 7 |
+
import lightgbm as lgb
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
MAXIMUM_X = 120
|
| 11 |
+
MAXIMUM_Y = 53.3
|
| 12 |
+
MAXIMUM_DIS = 131.30
|
| 13 |
+
BASE_COLS = []
|
| 14 |
+
|
| 15 |
+
#The features s, a represent the spped and acceleration
|
| 16 |
+
#the s and a are calculated from r, where r = <x(t), y(t)>
|
| 17 |
+
#so the function is a vector valued function in terms of time t
|
| 18 |
+
#velocity is given by <x'(t), y'(t)>
|
| 19 |
+
#acceleration is given by <x"(t), y"(t)>
|
| 20 |
+
#the s and a given here are the magnitude of these vectors
|
| 21 |
+
#the absolute yardline number refers to the distance to score endzone of the offense, calculated from the line of scrimmage
|
| 22 |
+
|
| 23 |
+
BASE_COLS = ['game_id', 'play_id', 'player_to_predict', 'nfl_id', 'frame_id',
|
| 24 |
+
'play_direction', 'absolute_yardline_number', 'player_name',
|
| 25 |
+
'player_height', 'player_weight', 'player_birth_date',
|
| 26 |
+
'player_position', 'player_side', 'player_role', 'x', 'y', 's', 'a',
|
| 27 |
+
'dir', 'o', 'num_frames_output', 'ball_land_x', 'ball_land_y']
|
| 28 |
+
|
| 29 |
+
MANDATORY_COLS=['game_id', 'play_id', 'nfl_id']
|
| 30 |
+
|
| 31 |
+
MODEL_NUMERICAL_INPUTS = ['frame_id', 'absolute_yardline_number', 'player_height',
|
| 32 |
+
'player_weight', 'x_last', 'y_last', 's', 'a', 'dir',
|
| 33 |
+
'o', 'num_frames_output', 'ball_land_x', 'ball_land_y', 'x_prev',
|
| 34 |
+
'y_prev', 'o_prev', 'dir_prev', 's_prev', 'a_prev',
|
| 35 |
+
'nearest_offense_dis', 'nearest_offense_dis_x', 'nearest_offense_dis_y',
|
| 36 |
+
'nearest_defense_dis', 'nearest_defense_dis_x', 'nearest_defense_dis_y',
|
| 37 |
+
'receiver_x', 'receiver_y', 'height', 'velocity_x', 'velocity_y',
|
| 38 |
+
'acc_x', 'acc_y', 'sin_o', 'cos_o', 'sin_dir', 'cos_dir', 'change_in_x',
|
| 39 |
+
'change_in_y', 'change_in_s', 'change_in_a', 'change_in_o',
|
| 40 |
+
'change_in_dir', 'dist_between_ball_land_and_player',
|
| 41 |
+
'dist_x_between_ball_and_player', 'dist_y_between_ball_and_player',
|
| 42 |
+
'angle_between_ball_and_dir', 'sin_angle_between_ball_and_dir',
|
| 43 |
+
'cos_angle_between_ball_and_dir', 'angle_between_ball_and_o',
|
| 44 |
+
'sin_angle_between_ball_and_o', 'cos_angle_between_ball_and_o',
|
| 45 |
+
'distance_to_sideline', 'distance_to_receiver',
|
| 46 |
+
'distance_x_to_receiver', 'distance_y_to_receiver',
|
| 47 |
+
'angle_between_dir_and_receiver', 'sin_angle_between_dir_and_receiver',
|
| 48 |
+
'cos_angle_between_dir_and_receiver', 'angle_between_o_and_receiver',
|
| 49 |
+
'sin_angle_between_o_and_receiver', 'cos_angle_between_o_and_receiver',
|
| 50 |
+
'time_left', 'required_speed', 'required_velocity_x',
|
| 51 |
+
'required_velocity_y', 'required_acc_x', 'required_acc_y',
|
| 52 |
+
'required_speed_diff', 'required_velocity_x_diff',
|
| 53 |
+
'required_velocity_y_diff', 'required_acc_x_diff',
|
| 54 |
+
'required_acc_y_diff', 'proj_x_acc', 'proj_y_acc', 'proj_x_velocity',
|
| 55 |
+
'proj_y_velocity', 'proj_x_acc_diff', 'proj_y_acc_diff',
|
| 56 |
+
'proj_x_velocity_diff', 'proj_y_velocity_diff', 'player_age']
|
| 57 |
+
|
| 58 |
+
MODEL_CAT_INPUTS = ['player_role']
|
| 59 |
+
|
| 60 |
+
MODEL_OUTPUTS = ['dx', 'dy']
|
| 61 |
+
|
| 62 |
+
TRAIN_INPUT_FILE_PATH = 'train_input'
|
| 63 |
+
TRAIN_OUTPUT_FILE_PATH = 'train_output'
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_train_file_paths():
|
| 67 |
+
|
| 68 |
+
def get_output_file(input_filename):
|
| 69 |
+
return input_filename.replace('input', 'output')
|
| 70 |
+
|
| 71 |
+
input_file_paths = []
|
| 72 |
+
output_file_paths = []
|
| 73 |
+
input_files_dir = TRAIN_INPUT_FILE_PATH
|
| 74 |
+
for w in range(1, 19):
|
| 75 |
+
input_filename = f'input_2023_w{w:02d}.csv'
|
| 76 |
+
if os.path.isfile(f'{input_files_dir}/{input_filename}'):
|
| 77 |
+
output_filename = get_output_file(input_filename)
|
| 78 |
+
input_file_path = os.path.join(TRAIN_INPUT_FILE_PATH, input_filename)
|
| 79 |
+
output_file_path = os.path.join(TRAIN_OUTPUT_FILE_PATH, output_filename)
|
| 80 |
+
input_file_paths.append(input_file_path)
|
| 81 |
+
output_file_paths.append(output_file_path)
|
| 82 |
+
else:
|
| 83 |
+
raise Exception(f'input file for week {w} does not exist')
|
| 84 |
+
|
| 85 |
+
return (input_file_paths, output_file_paths)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def load_file(file_path):
|
| 89 |
+
return pd.read_csv(file_path)
|
| 90 |
+
|
| 91 |
+
def get_input_output_df():
|
| 92 |
+
input_file_paths, output_file_paths = get_train_file_paths()
|
| 93 |
+
|
| 94 |
+
with ThreadPoolExecutor(max_workers = 8) as executor:
|
| 95 |
+
input_dfs = executor.map(load_file, input_file_paths)
|
| 96 |
+
input_df = pd.concat(input_dfs, axis=0)
|
| 97 |
+
|
| 98 |
+
with ThreadPoolExecutor(max_workers = 8) as executor:
|
| 99 |
+
output_dfs = executor.map(load_file, output_file_paths)
|
| 100 |
+
output_df = pd.concat(output_dfs, axis=0)
|
| 101 |
+
|
| 102 |
+
return input_df.reset_index(drop=True), output_df.reset_index(drop=True)
|
| 103 |
+
|
| 104 |
+
def reflect_input_player_positions(df):
|
| 105 |
+
mask = df['play_direction'] == 'left'
|
| 106 |
+
df.loc[mask, 'x'] = 120 - df.loc[mask, 'x']
|
| 107 |
+
df.loc[mask, 'dir'] = (360 - df.loc[mask, 'dir']) % 360
|
| 108 |
+
df.loc[mask, 'o'] = (360 - df.loc[mask, 'o']) % 360
|
| 109 |
+
df.loc[mask, 'ball_land_x'] = 120 - df.loc[mask, 'ball_land_x']
|
| 110 |
+
return df
|
| 111 |
+
|
| 112 |
+
def reflect_output_player_positions(df):
|
| 113 |
+
mask = df['play_direction'] == 'left'
|
| 114 |
+
df.loc[mask, 'x'] = 120 - df.loc[mask, 'x']
|
| 115 |
+
return df
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def add_nearest_dis_info(df):
|
| 119 |
+
plays = df.groupby(['game_id', 'play_id'], as_index=False)
|
| 120 |
+
res = []
|
| 121 |
+
for _, per_play in plays:
|
| 122 |
+
per_play = per_play.copy()
|
| 123 |
+
coords = per_play[['x_last', 'y_last']].to_numpy()
|
| 124 |
+
if coords.shape[0] == 1:
|
| 125 |
+
per_play['nearest_offense_dis'] = MAXIMUM_DIS
|
| 126 |
+
per_play['nearest_defense_dis'] = MAXIMUM_DIS
|
| 127 |
+
per_play['nearest_offense_dis_x'] = MAXIMUM_DIS
|
| 128 |
+
per_play['nearest_offense_dis_y'] = MAXIMUM_DIS
|
| 129 |
+
per_play['nearest_defense_dis_x'] = MAXIMUM_DIS
|
| 130 |
+
per_play['nearest_defense_dis_y'] = MAXIMUM_DIS
|
| 131 |
+
else:
|
| 132 |
+
distance = cdist(coords, coords, metric='euclidean')
|
| 133 |
+
np.fill_diagonal(distance, MAXIMUM_DIS)
|
| 134 |
+
|
| 135 |
+
offense_indices = (per_play['player_side'] == 'Offense')
|
| 136 |
+
defense_indices = (per_play['player_side'] == 'Defense')
|
| 137 |
+
|
| 138 |
+
if np.any(offense_indices):
|
| 139 |
+
per_play.loc[:,['nearest_offense_dis']] = np.min(distance[:,offense_indices], axis=-1)
|
| 140 |
+
|
| 141 |
+
idx = np.argmin(distance[:,offense_indices], axis=-1)
|
| 142 |
+
per_play.loc[:,['nearest_offense_dis_x']] = coords[offense_indices,][idx,0]
|
| 143 |
+
per_play.loc[:,['nearest_offense_dis_y']] = coords[offense_indices,][idx,1]
|
| 144 |
+
else:
|
| 145 |
+
per_play.loc[:,['nearest_offense_dis']] = MAXIMUM_DIS
|
| 146 |
+
per_play.loc[:,['nearest_offense_dis_x']] = MAXIMUM_X
|
| 147 |
+
per_play.loc[:,['nearest_offense_dis_y']] = MAXIMUM_Y
|
| 148 |
+
|
| 149 |
+
if np.any(defense_indices):
|
| 150 |
+
per_play.loc[:,['nearest_defense_dis']] = np.min(distance[:,defense_indices],axis=-1)
|
| 151 |
+
|
| 152 |
+
idx = np.argmin(distance[:,defense_indices], axis=-1)
|
| 153 |
+
per_play.loc[:,['nearest_defense_dis_x']] = coords[defense_indices,][idx,0]
|
| 154 |
+
per_play.loc[:,['nearest_defense_dis_y']] = coords[defense_indices][idx,1]
|
| 155 |
+
else:
|
| 156 |
+
per_play.loc[:,['nearest_defense_dis']] = MAXIMUM_DIS
|
| 157 |
+
per_play.loc[:,['nearest_defense_dis_x']] = MAXIMUM_X
|
| 158 |
+
per_play.loc[:,['nearest_defense_dis_y']] = MAXIMUM_Y
|
| 159 |
+
|
| 160 |
+
res.append(per_play)
|
| 161 |
+
|
| 162 |
+
return pd.concat(res, axis=0)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def add_reciever_info(df):
|
| 166 |
+
receiver = df.loc[df['player_role'] == 'Targeted Receiver',['game_id', 'play_id', 'x_last', 'y_last']]
|
| 167 |
+
|
| 168 |
+
receiver = receiver.rename(columns = {'x_last': 'receiver_x', 'y_last':'receiver_y'})
|
| 169 |
+
|
| 170 |
+
#if a play has no targeted receiever we leave with nan
|
| 171 |
+
return df.merge(receiver, on=['game_id', 'play_id'], how='left')
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def get_last_frame(df):
|
| 175 |
+
|
| 176 |
+
df_sorted = df.sort_values(['game_id', 'play_id', 'nfl_id', 'frame_id']).reset_index(drop=True)
|
| 177 |
+
|
| 178 |
+
group_by_cols = ['game_id', 'play_id', 'nfl_id']
|
| 179 |
+
|
| 180 |
+
feature_cols = ['x', 'y', 'o', 'dir', 's', 'a']
|
| 181 |
+
|
| 182 |
+
df_sorted[[f'{c}_prev' for c in feature_cols]] = df_sorted.groupby(group_by_cols)[feature_cols].shift(1)
|
| 183 |
+
|
| 184 |
+
#last() takes non none values from the last possible col
|
| 185 |
+
#so even if last frame misses a feature , value is taken from the previous available one
|
| 186 |
+
df_last_frame = df_sorted.groupby(group_by_cols, as_index=False).last()
|
| 187 |
+
|
| 188 |
+
df_last_frame = df_last_frame.rename(columns={'x':'x_last', 'y':'y_last'})
|
| 189 |
+
|
| 190 |
+
return df_last_frame
|
| 191 |
+
|
| 192 |
+
def clean_and_extract_features(df):
|
| 193 |
+
|
| 194 |
+
def convert_to_radians(degrees):
|
| 195 |
+
return degrees * np.pi / 180
|
| 196 |
+
|
| 197 |
+
def convert_to_degrees(radians):
|
| 198 |
+
return radians * 180 / np.pi
|
| 199 |
+
|
| 200 |
+
def sin(theta):
|
| 201 |
+
return np.sin(convert_to_radians(theta))
|
| 202 |
+
|
| 203 |
+
def cos(theta):
|
| 204 |
+
return np.cos(convert_to_radians(theta))
|
| 205 |
+
|
| 206 |
+
def distance_between_two_points(x1, y1, x2, y2):
|
| 207 |
+
return np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
|
| 208 |
+
|
| 209 |
+
def angle_between_two_vectors(x1, y1, x2, y2):
|
| 210 |
+
denom = np.sqrt((x1**2)+(y1**2)) * np.sqrt((x2**2)+(y2**2)) + 1e-6
|
| 211 |
+
dot = x1*x2 + y1*y2
|
| 212 |
+
cos_angle = dot / denom
|
| 213 |
+
cos_angle = np.clip(cos_angle, -1.0, 1.0)
|
| 214 |
+
angle_in_radians = np.arccos(cos_angle)
|
| 215 |
+
return convert_to_degrees(angle_in_radians)
|
| 216 |
+
|
| 217 |
+
def convert_to_inches(X):
|
| 218 |
+
splits = X.str.split('-', expand=True)
|
| 219 |
+
feet = splits.iloc[:,0].astype(np.float32)
|
| 220 |
+
inches = splits.iloc[:,1].astype(np.float32)
|
| 221 |
+
return feet * 12 + inches
|
| 222 |
+
|
| 223 |
+
#returns the shortest angle when curr = 1degree prev = 359degree, change is 2degree
|
| 224 |
+
def change_in_angle(curr, prev):
|
| 225 |
+
return ((curr - prev +180) % 360) - 180
|
| 226 |
+
|
| 227 |
+
df['x_last'] = df['x_last'].bfill().ffill()
|
| 228 |
+
df['x_prev'] = df['x_prev'].bfill().ffill()
|
| 229 |
+
df['y_last'] = df['y_last'].bfill().ffill()
|
| 230 |
+
df['y_prev'] = df['y_prev'].bfill().ffill()
|
| 231 |
+
df['s'] = df['s'].bfill().ffill()
|
| 232 |
+
df['s_prev'] = df['s_prev'].bfill().ffill()
|
| 233 |
+
df['a'] = df['a'].bfill().ffill()
|
| 234 |
+
df['a_prev'] = df['a_prev'].bfill().ffill()
|
| 235 |
+
df['dir'] = df['dir'].bfill().ffill()
|
| 236 |
+
df['dir_prev'] = df['dir_prev'].bfill().ffill()
|
| 237 |
+
df['o'] = df['o'].bfill().ffill()
|
| 238 |
+
df['o_prev'] = df['o_prev'].bfill().ffill()
|
| 239 |
+
df['receiver_x'] = df['receiver_x'].bfill().ffill()
|
| 240 |
+
df['receiver_y'] = df['receiver_y'].bfill().ffill()
|
| 241 |
+
df['player_height'] = df['player_height'].bfill().ffill()
|
| 242 |
+
|
| 243 |
+
df['velocity_x'] = df['s'] * sin(df['dir'])
|
| 244 |
+
df['velocity_y'] = df['s'] * cos(df['dir'])
|
| 245 |
+
df['acc_x'] = df['a'] * sin(df['dir'])
|
| 246 |
+
df['acc_y'] = df['a'] * cos(df['dir'])
|
| 247 |
+
|
| 248 |
+
df['sin_o'] = sin(df['o'])
|
| 249 |
+
df['cos_o'] = cos(df['o'])
|
| 250 |
+
|
| 251 |
+
df['sin_dir'] = sin(df['dir'])
|
| 252 |
+
df['cos_dir'] = cos(df['dir'])
|
| 253 |
+
|
| 254 |
+
df['change_in_x'] = df['x_last'] - df['x_prev']
|
| 255 |
+
df['change_in_y'] = df['y_last'] - df['y_prev']
|
| 256 |
+
df['change_in_s'] = df['s'] - df['s_prev']
|
| 257 |
+
df['change_in_a'] = df['a'] - df['a_prev']
|
| 258 |
+
df['change_in_o'] = change_in_angle(df['o'], df['o_prev'])
|
| 259 |
+
df['change_in_dir'] = change_in_angle(df['dir'], df['dir_prev'])
|
| 260 |
+
|
| 261 |
+
df['dist_between_ball_land_and_player'] = distance_between_two_points(
|
| 262 |
+
df['x_last'], df['y_last'], df['ball_land_x'], df['ball_land_y']
|
| 263 |
+
)
|
| 264 |
+
df['dist_x_between_ball_and_player'] = df['ball_land_x'] - df['x_last']
|
| 265 |
+
df['dist_y_between_ball_and_player'] = df['ball_land_y'] - df['y_last']
|
| 266 |
+
|
| 267 |
+
df['angle_between_ball_and_dir'] = angle_between_two_vectors(
|
| 268 |
+
df['sin_dir'], df['cos_dir'], df['dist_x_between_ball_and_player'], df['dist_y_between_ball_and_player']
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
df['sin_angle_between_ball_and_dir'] = sin(df['angle_between_ball_and_dir'])
|
| 272 |
+
df['cos_angle_between_ball_and_dir'] = cos(df['angle_between_ball_and_dir'])
|
| 273 |
+
|
| 274 |
+
df['angle_between_ball_and_o'] = angle_between_two_vectors(
|
| 275 |
+
df['sin_o'], df['cos_o'], df['dist_x_between_ball_and_player'], df['dist_y_between_ball_and_player']
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
df['sin_angle_between_ball_and_o'] = sin(df['angle_between_ball_and_o'])
|
| 279 |
+
df['cos_angle_between_ball_and_o'] = cos(df['angle_between_ball_and_o'])
|
| 280 |
+
|
| 281 |
+
df['distance_to_sideline'] = np.minimum(df['y_last'], MAXIMUM_Y - df['y_last'])
|
| 282 |
+
|
| 283 |
+
df['player_height'] = convert_to_inches(df['player_height'])
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
df['distance_to_receiver'] = distance_between_two_points(df['x_last'], df['y_last'], df['receiver_x'], df['receiver_y'])
|
| 287 |
+
df['distance_x_to_receiver'] = df['x_last'] - df['receiver_x']
|
| 288 |
+
df['distance_y_to_receiver'] = df['y_last'] - df['receiver_y']
|
| 289 |
+
df['angle_between_dir_and_receiver'] = angle_between_two_vectors(
|
| 290 |
+
df['sin_dir'], df['cos_dir'], df['distance_x_to_receiver'], df['distance_y_to_receiver']
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
df['sin_angle_between_dir_and_receiver'] = sin(df['angle_between_dir_and_receiver'])
|
| 294 |
+
df['cos_angle_between_dir_and_receiver'] = cos(df['angle_between_dir_and_receiver'])
|
| 295 |
+
|
| 296 |
+
df['angle_between_o_and_receiver'] = angle_between_two_vectors(df['sin_o'], df['cos_o'], df['distance_x_to_receiver'], df['distance_y_to_receiver'])
|
| 297 |
+
|
| 298 |
+
df['sin_angle_between_o_and_receiver'] = sin(df['angle_between_o_and_receiver'])
|
| 299 |
+
df['cos_angle_between_o_and_receiver'] = cos(df['angle_between_o_and_receiver'])
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
df['time_left'] = (df['num_frames_output'] - (df['frame_id'] - 1) )/10
|
| 303 |
+
|
| 304 |
+
df['required_speed'] = df['dist_between_ball_land_and_player'] / df['time_left']
|
| 305 |
+
df['required_velocity_x'] = df['dist_x_between_ball_and_player'] / df['time_left']
|
| 306 |
+
df['required_velocity_y'] = df['dist_y_between_ball_and_player'] / df['time_left']
|
| 307 |
+
df['required_acc_x'] = (df['required_velocity_x'] - df['velocity_x']) / df['time_left']
|
| 308 |
+
df['required_acc_y'] = (df['required_velocity_y'] - df['velocity_y']) / df['time_left']
|
| 309 |
+
|
| 310 |
+
df['required_speed_diff'] = df['required_speed'] - df['s']
|
| 311 |
+
df['required_velocity_x_diff'] = df['required_velocity_x'] - df['velocity_x']
|
| 312 |
+
df['required_velocity_y_diff'] = df['required_velocity_y'] - df['velocity_y']
|
| 313 |
+
df['required_acc_x_diff'] = df['required_acc_x'] - df['acc_x']
|
| 314 |
+
df['required_acc_y_diff'] = df['required_acc_y'] - df['acc_y']
|
| 315 |
+
|
| 316 |
+
df['proj_x_acc'] = df['x_last'] + df['velocity_x']*df['time_left'] + 0.5*df['acc_x']*(df['time_left']**2)
|
| 317 |
+
df['proj_y_acc'] = df['y_last'] + df['velocity_y']*df['time_left'] + 0.5*df['acc_y']*(df['time_left']**2)
|
| 318 |
+
|
| 319 |
+
df['proj_x_velocity'] = df['x_last'] + df['velocity_x']*df['time_left']
|
| 320 |
+
df['proj_y_velocity'] = df['y_last'] + df['velocity_y']*df['time_left']
|
| 321 |
+
|
| 322 |
+
df['proj_x_acc_diff'] = df['ball_land_x'] - df['proj_x_acc']
|
| 323 |
+
df['proj_y_acc_diff'] = df['ball_land_y'] - df['proj_y_acc']
|
| 324 |
+
|
| 325 |
+
df['proj_x_velocity_diff'] = df['ball_land_x'] - df['proj_x_velocity']
|
| 326 |
+
df['proj_y_velocity_diff'] = df['ball_land_y'] - df['proj_y_velocity']
|
| 327 |
+
|
| 328 |
+
year = date.today().year
|
| 329 |
+
s = pd.to_datetime(df['player_birth_date'])
|
| 330 |
+
df['player_age'] = year - s.dt.year
|
| 331 |
+
|
| 332 |
+
df['absolute_yardline_number'] = np.clip(df['absolute_yardline_number'], 0, 100.0)
|
| 333 |
+
|
| 334 |
+
return df
|
| 335 |
+
|
| 336 |
+
def get_train_df(input_df, output_df):
|
| 337 |
+
input_df = input_df.copy()
|
| 338 |
+
input_df = reflect_input_player_positions(input_df)
|
| 339 |
+
|
| 340 |
+
output_df = output_df.copy()
|
| 341 |
+
|
| 342 |
+
df_last_frame = get_last_frame(input_df)
|
| 343 |
+
df_last_frame = add_nearest_dis_info(df_last_frame)
|
| 344 |
+
df_last_frame = add_reciever_info(df_last_frame)
|
| 345 |
+
|
| 346 |
+
cols = ['game_id', 'play_id', 'nfl_id', 'absolute_yardline_number', 'player_height', 'player_weight', 'player_birth_date',
|
| 347 |
+
'play_direction','player_position', 'player_role', 'x_last', 'y_last', 's', 'a', 'dir', 'o', 'num_frames_output', 'ball_land_x',
|
| 348 |
+
'ball_land_y', 'x_prev', 'y_prev', 'o_prev', 'dir_prev', 's_prev', 'a_prev', 'nearest_offense_dis', 'nearest_offense_dis_x',
|
| 349 |
+
'nearest_offense_dis_y', 'nearest_defense_dis', 'nearest_defense_dis_x', 'nearest_defense_dis_y', 'receiver_x', 'receiver_y']
|
| 350 |
+
|
| 351 |
+
df_last_frame = df_last_frame[cols]
|
| 352 |
+
|
| 353 |
+
df_merged = output_df.merge(df_last_frame, on=['game_id', 'play_id', 'nfl_id'], how='left')
|
| 354 |
+
|
| 355 |
+
df_merged = reflect_output_player_positions(df_merged)
|
| 356 |
+
|
| 357 |
+
X_df = clean_and_extract_features(df_merged)
|
| 358 |
+
|
| 359 |
+
X_df['player_role'] = X_df['player_role'].astype('category')
|
| 360 |
+
|
| 361 |
+
dx = X_df['x'] - X_df['x_last']
|
| 362 |
+
dy = X_df['y'] - X_df['y_last']
|
| 363 |
+
Y_df = pd.DataFrame({'dx' : dx, 'dy' :dy})
|
| 364 |
+
|
| 365 |
+
return X_df, Y_df
|
| 366 |
+
|
| 367 |
+
def get_train_valid_split(X_df, Y_df, test_ratio=0.2):
|
| 368 |
+
tr = X_df.shape[0]
|
| 369 |
+
test_s = int(tr*(1-test_ratio))
|
| 370 |
+
X_df_train = X_df[:test_s]
|
| 371 |
+
Y_df_train = Y_df[:test_s]
|
| 372 |
+
|
| 373 |
+
X_df_valid = X_df[test_s:]
|
| 374 |
+
Y_df_valid = Y_df[test_s:]
|
| 375 |
+
|
| 376 |
+
return X_df_train, Y_df_train, X_df_valid, Y_df_valid
|
| 377 |
+
|
| 378 |
+
def create_output_frames(df):
|
| 379 |
+
num_frames = df['num_frames_output'].iloc[0]
|
| 380 |
+
frame_id = pd.Series(np.arange(1, num_frames+1), name='frame_id')
|
| 381 |
+
return df.merge(frame_id, how='cross')
|
| 382 |
+
|
| 383 |
+
def get_params(is_pred=True):
|
| 384 |
+
|
| 385 |
+
params = {
|
| 386 |
+
'task':'train',
|
| 387 |
+
'objective':'regression',
|
| 388 |
+
'bagging_freq' : 1,
|
| 389 |
+
'bagging_fraction' : 0.75,
|
| 390 |
+
'learning_rate' : 0.05,
|
| 391 |
+
'device_type' : 'gpu',
|
| 392 |
+
'num_threads':8,
|
| 393 |
+
'n_estimators':2000,
|
| 394 |
+
'seed' : 42,
|
| 395 |
+
'max_depth':80,
|
| 396 |
+
'max_leaves' : 100,
|
| 397 |
+
'min_data_in_leaf' : 200,
|
| 398 |
+
'feature_fraction' : 0.80,
|
| 399 |
+
'lambda_l1' : 0.5,
|
| 400 |
+
'lambda_l2' : 0.5,
|
| 401 |
+
'early_stopping_rounds' : 100,
|
| 402 |
+
'early_stopping_min_delta' : 0.001,
|
| 403 |
+
'verbose':-1,
|
| 404 |
+
'metric' :'rmse'
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
if is_pred:
|
| 408 |
+
params['task'] = 'predict'
|
| 409 |
+
|
| 410 |
+
return params
|
| 411 |
+
|
| 412 |
+
def get_test_df(input_df):
|
| 413 |
+
df = input_df.copy()
|
| 414 |
+
|
| 415 |
+
df = reflect_input_player_positions(df)
|
| 416 |
+
df_last_frame = get_last_frame(df)
|
| 417 |
+
df_last_frame = add_nearest_dis_info(df_last_frame)
|
| 418 |
+
df_last_frame = add_reciever_info(df_last_frame)
|
| 419 |
+
|
| 420 |
+
df_last_frame = df_last_frame[df_last_frame['player_to_predict']].reset_index(drop=True)
|
| 421 |
+
|
| 422 |
+
num_frames_output = df_last_frame['num_frames_output'].values
|
| 423 |
+
|
| 424 |
+
df_with_output_frames = df_last_frame.loc[df_last_frame.index.repeat(num_frames_output)]
|
| 425 |
+
|
| 426 |
+
df_with_output_frames['frame_id'] = df_with_output_frames.groupby(level=0).cumcount() + 1
|
| 427 |
+
|
| 428 |
+
X_df = clean_and_extract_features(df_with_output_frames.reset_index(drop=True))
|
| 429 |
+
|
| 430 |
+
X_df['player_role'] = X_df['player_role'].astype('category')
|
| 431 |
+
|
| 432 |
+
return X_df
|
| 433 |
+
|
| 434 |
+
def calculate_rmse(X_df, Y_df, dx_train, dy_train):
|
| 435 |
+
|
| 436 |
+
dx_features = dx_train.feature_name()
|
| 437 |
+
dy_features = dy_train.feature_name()
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
pred_dx = dx_train.predict(X_df[dx_features])
|
| 441 |
+
pred_dy = dy_train.predict(X_df[dy_features])
|
| 442 |
+
|
| 443 |
+
n = Y_df.size
|
| 444 |
+
residual = (pred_dx - Y_df['dx'])**2 + (pred_dy - Y_df['dy'])**2
|
| 445 |
+
|
| 446 |
+
residual_avg = np.sum(residual) / n
|
| 447 |
+
|
| 448 |
+
return np.sqrt(residual_avg)
|
| 449 |
+
|
| 450 |
+
def publish_results(X_df, Y_df, dx_model, dy_model):
|
| 451 |
+
|
| 452 |
+
dx_features = dx_model.feature_name()
|
| 453 |
+
dy_features = dy_model.feature_name()
|
| 454 |
+
|
| 455 |
+
pred_dx = dx_model.predict(X_df[dx_features])
|
| 456 |
+
pred_dy = dy_model.predict(X_df[dy_features])
|
| 457 |
+
|
| 458 |
+
game_id = X_df['game_id'].values
|
| 459 |
+
play_id = X_df['play_id'].values
|
| 460 |
+
nfl_id = X_df['nfl_id'].values
|
| 461 |
+
frame_id = X_df['frame_id'].values
|
| 462 |
+
player_position = X_df['player_position'].values
|
| 463 |
+
player_role = X_df['player_role'].values
|
| 464 |
+
x_last = X_df['x_last'].values
|
| 465 |
+
y_last = X_df['y_last'].values
|
| 466 |
+
actual_x = X_df['x'].values
|
| 467 |
+
actual_y = X_df['y'].values
|
| 468 |
+
play_direction = X_df['play_direction'].values
|
| 469 |
+
|
| 470 |
+
pred_x = pred_dx + x_last
|
| 471 |
+
pred_y = pred_dy + y_last
|
| 472 |
+
|
| 473 |
+
mask = (play_direction == 'left')
|
| 474 |
+
|
| 475 |
+
if np.any(mask):
|
| 476 |
+
pred_x[mask] = 120 - pred_x[mask]
|
| 477 |
+
actual_x[mask] = 120 - actual_x[mask]
|
| 478 |
+
|
| 479 |
+
pred_x = np.clip(pred_x, 0.0, 120.0)
|
| 480 |
+
pred_y = np.clip(pred_y, 0.0, 53.3)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
preds = np.column_stack([game_id, play_id, nfl_id, frame_id, player_position,
|
| 484 |
+
player_role, play_direction, x_last, y_last, actual_x, actual_y, pred_x, pred_y])
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
df = pd.DataFrame(preds, columns=['game_id', 'play_id', 'nfl_id','frame_id', 'player_position',
|
| 488 |
+
'player_role','play_direction',
|
| 489 |
+
'x_last', 'y_last', 'actual_x', 'actual_y', 'pred_x', 'pred_y'])
|
| 490 |
+
|
| 491 |
+
df.to_csv('lightGBT_test_data_results.csv', index=False)
|
| 492 |
+
print('results published')
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def train(input_df, output_df):
|
| 496 |
+
given_input_cols = set(input_df.columns)
|
| 497 |
+
for c in MANDATORY_COLS:
|
| 498 |
+
if c not in given_input_cols:
|
| 499 |
+
raise Exception(f'{c} is missing in input_df')
|
| 500 |
+
elif input_df[c].isna().any():
|
| 501 |
+
raise Exception(f'{c} in input_df contains nan')
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
given_output_cols = set(output_df.columns)
|
| 505 |
+
for c in MANDATORY_COLS:
|
| 506 |
+
if c not in given_output_cols:
|
| 507 |
+
raise Exception(f'{c} is missing in output_df')
|
| 508 |
+
elif output_df[c].isna().any():
|
| 509 |
+
raise Exception(f'{c} in output_df contains nan')
|
| 510 |
+
|
| 511 |
+
for c in BASE_COLS:
|
| 512 |
+
if c not in input_df.columns:
|
| 513 |
+
input_df[c] = np.nan
|
| 514 |
+
|
| 515 |
+
print('getting train_df, valid_df')
|
| 516 |
+
X_df, Y_df = get_train_df(input_df, output_df)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
print('splitting train test')
|
| 520 |
+
X_train_df, Y_train_df, X_valid_df, Y_valid_df = get_train_valid_split(X_df, Y_df, test_ratio=0.05)
|
| 521 |
+
|
| 522 |
+
filt_cols = ['player_birth_date', 'x', 'y', 'game_id', 'play_id', 'nfl_id', 'play_direction', 'player_position']
|
| 523 |
+
X_train_filt_df = X_train_df.drop(columns=filt_cols)
|
| 524 |
+
X_valid_filt_df = X_valid_df.drop(columns=filt_cols)
|
| 525 |
+
|
| 526 |
+
print('training started')
|
| 527 |
+
train_set_dx = lgb.Dataset(data=X_train_filt_df, label=Y_train_df['dx'])
|
| 528 |
+
train_sub_set_dx = lgb.Dataset(data=X_train_filt_df[:50000], label=Y_train_df['dx'][:50000], reference=train_set_dx)
|
| 529 |
+
valid_set_dx = lgb.Dataset(data=X_valid_filt_df, label=Y_valid_df['dx'], reference=train_set_dx)
|
| 530 |
+
|
| 531 |
+
train_set_dy = lgb.Dataset(data=X_train_filt_df, label=Y_train_df['dy'])
|
| 532 |
+
train_sub_set_dy = lgb.Dataset(data=X_train_filt_df[:50000], label=Y_train_df['dy'][:50000], reference=train_set_dy)
|
| 533 |
+
valid_set_dy = lgb.Dataset(data=X_valid_filt_df, label=Y_valid_df['dy'], reference=train_set_dy)
|
| 534 |
+
|
| 535 |
+
params = get_params(False)
|
| 536 |
+
|
| 537 |
+
dx_model = lgb.train(params = params,
|
| 538 |
+
train_set=train_set_dx,
|
| 539 |
+
valid_sets=[train_sub_set_dx, valid_set_dx],
|
| 540 |
+
valid_names=['train', 'valid'],
|
| 541 |
+
callbacks=[
|
| 542 |
+
lgb.log_evaluation(period=10)
|
| 543 |
+
]
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
dy_model = lgb.train(params = params,
|
| 547 |
+
train_set=train_set_dy,
|
| 548 |
+
valid_sets=[train_sub_set_dy, valid_set_dy],
|
| 549 |
+
valid_names=['train', 'valid'],
|
| 550 |
+
callbacks=[
|
| 551 |
+
lgb.log_evaluation(period=10)
|
| 552 |
+
]
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
publish_results(X_valid_df, Y_valid_df, dx_model, dy_model)
|
| 556 |
+
|
| 557 |
+
train_rmse = calculate_rmse(X_train_df, Y_train_df, dx_model, dy_model)
|
| 558 |
+
valid_rmse = calculate_rmse(X_valid_df, Y_valid_df, dx_model, dy_model)
|
| 559 |
+
|
| 560 |
+
print(f'rmse on the training set is :{train_rmse}')
|
| 561 |
+
print(f'rmse on the validation set is :{valid_rmse}')
|
| 562 |
+
return dx_model, dy_model
|
| 563 |
+
|
| 564 |
+
def get_features_by_importance(model):
|
| 565 |
+
sort_index = np.argsort(-model.feature_importance(importance_type='gain'))
|
| 566 |
+
return np.array(model.feature_name())[sort_index]
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def train_test():
|
| 570 |
+
print('started')
|
| 571 |
+
|
| 572 |
+
input_df, output_df = get_input_output_df()
|
| 573 |
+
|
| 574 |
+
print('fetched input and output')
|
| 575 |
+
|
| 576 |
+
dx_model, dy_model = train(input_df, output_df)
|
| 577 |
+
|
| 578 |
+
dx_model.save_model('lightGBT_dx_model.txt', num_iteration=dx_model.best_iteration)
|
| 579 |
+
print('model lightGBT_dx_model saved')
|
| 580 |
+
|
| 581 |
+
dy_model.save_model('lightGBT_dy_model.txt', num_iteration=dy_model.best_iteration)
|
| 582 |
+
print('model lightGBT_dy_model saved')
|
| 583 |
+
|
| 584 |
+
dx_model_feature_importance = get_features_by_importance(dx_model)
|
| 585 |
+
dy_model_feature_importance = get_features_by_importance(dy_model)
|
| 586 |
+
|
| 587 |
+
print(f'top 15 features for dx_model: {dx_model_feature_importance[:15]}')
|
| 588 |
+
print(f'top 15 features for dy_model: {dy_model_feature_importance[:15]}')
|
| 589 |
+
|
| 590 |
+
if __name__ == '__main__':
|
| 591 |
+
train_test()
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
|
lightGBT_app_predict.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from lightGBT import get_test_df
|
| 3 |
+
import lightgbm as lgb
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
dx_model = lgb.Booster(model_file='lightGBT_dx_model.txt')
|
| 8 |
+
dy_model = lgb.Booster(model_file='lightGBT_dy_model.txt')
|
| 9 |
+
|
| 10 |
+
BASE_COLS = ['game_id', 'play_id', 'player_to_predict', 'nfl_id', 'frame_id',
|
| 11 |
+
'play_direction', 'absolute_yardline_number', 'player_name',
|
| 12 |
+
'player_height', 'player_weight', 'player_birth_date',
|
| 13 |
+
'player_position', 'player_side', 'player_role', 'x', 'y', 's', 'a',
|
| 14 |
+
'dir', 'o', 'num_frames_output', 'ball_land_x', 'ball_land_y']
|
| 15 |
+
|
| 16 |
+
MANDATORY_COLS=['game_id', 'play_id', 'nfl_id']
|
| 17 |
+
|
| 18 |
+
def predict(df):
|
| 19 |
+
given_input_cols = set(df.columns)
|
| 20 |
+
for c in MANDATORY_COLS:
|
| 21 |
+
if c not in given_input_cols:
|
| 22 |
+
raise Exception(f'{c} is missing in input')
|
| 23 |
+
elif df[c].isna().any():
|
| 24 |
+
raise Exception(f'{c} in input contains nan')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
for c in BASE_COLS:
|
| 28 |
+
if c not in df:
|
| 29 |
+
raise Exception(f'{c} is not there in input')
|
| 30 |
+
if df[c].isna().all():
|
| 31 |
+
raise Exception(f'{c} in input contains all nan')
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
X_df = get_test_df(df)
|
| 35 |
+
|
| 36 |
+
dx_features = dx_model.feature_name()
|
| 37 |
+
dy_features = dy_model.feature_name()
|
| 38 |
+
|
| 39 |
+
pred_dx = dx_model.predict(X_df[dx_features])
|
| 40 |
+
pred_dy = dy_model.predict(X_df[dy_features])
|
| 41 |
+
|
| 42 |
+
game_id = X_df['game_id'].values
|
| 43 |
+
play_id = X_df['play_id'].values
|
| 44 |
+
nfl_id = X_df['nfl_id'].values
|
| 45 |
+
frame_id = X_df['frame_id'].values
|
| 46 |
+
player_position = X_df['player_position'].values
|
| 47 |
+
player_role = X_df['player_role'].values
|
| 48 |
+
x_last = X_df['x_last'].values
|
| 49 |
+
y_last = X_df['y_last'].values
|
| 50 |
+
|
| 51 |
+
play_direction = X_df['play_direction'].values
|
| 52 |
+
|
| 53 |
+
pred_x = pred_dx + x_last
|
| 54 |
+
pred_y = pred_dy + y_last
|
| 55 |
+
|
| 56 |
+
mask = (play_direction == 'left')
|
| 57 |
+
|
| 58 |
+
if np.any(mask):
|
| 59 |
+
pred_x[mask] = 120 - pred_x[mask]
|
| 60 |
+
|
| 61 |
+
pred_x = np.clip(pred_x, 0.0, 120.0)
|
| 62 |
+
pred_y = np.clip(pred_y, 0.0, 53.3)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
preds = np.column_stack([game_id, play_id, nfl_id, frame_id, player_position,
|
| 66 |
+
player_role, play_direction, x_last, y_last, pred_x, pred_y])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
df = pd.DataFrame(preds, columns=['game_id', 'play_id', 'nfl_id','frame_id', 'player_position',
|
| 70 |
+
'player_role','play_direction',
|
| 71 |
+
'x_last', 'y_last', 'pred_x', 'pred_y'])
|
| 72 |
+
|
| 73 |
+
return df.sort_values(by=['game_id', 'play_id', 'nfl_id', 'frame_id'])
|
| 74 |
+
|
lightGBT_dx_model.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5186c1e3ca4573bd4a9b9908a597e1c831134e7181cddfef1321e294bc84bdfe
|
| 3 |
+
size 6107979
|
lightGBT_dy_model.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ed6054cfd765fd19c82060a54939bbe709e06f2f6e5c5d2777866892092258d8
|
| 3 |
+
size 9111426
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy
|
| 2 |
+
pandas
|
| 3 |
+
scikit-learn
|
| 4 |
+
scipy
|
| 5 |
+
lightgbm
|
| 6 |
+
matplotlib
|
| 7 |
+
seaborn
|
| 8 |
+
torch
|
| 9 |
+
tqdm
|
| 10 |
+
positional-encodings
|
| 11 |
+
flask
|
sample_nfl_plays.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:30076e216d103880823b4e6b4681caad5cff83ee2982547446894b71a9e6dc99
|
| 3 |
+
size 163040
|
sample_nfl_plays_actual_output.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab9a9658472ebcaf960aa38e99c93e1e45131016aa3aa3cc283d56251a5f0a8b
|
| 3 |
+
size 6426
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from collections import Counter
|
| 3 |
+
import numpy as np
|
| 4 |
+
import seaborn as sns
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
TRAIN_INPUT_FILE_PATH = 'C:/Users/vigne/nfl/train_input'
|
| 12 |
+
TRAIN_OUTPUT_FILE_PATH = 'C:/Users/vigne/nfl/train_output'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_train_file_paths():
|
| 16 |
+
|
| 17 |
+
def get_output_file(input_filename):
|
| 18 |
+
return input_filename.replace('input', 'output')
|
| 19 |
+
|
| 20 |
+
input_file_paths = []
|
| 21 |
+
output_file_paths = []
|
| 22 |
+
input_files_dir = TRAIN_INPUT_FILE_PATH
|
| 23 |
+
for w in range(1, 19):
|
| 24 |
+
input_filename = f'input_2023_w{w:02d}.csv'
|
| 25 |
+
if os.path.isfile(f'{input_files_dir}/{input_filename}'):
|
| 26 |
+
output_filename = get_output_file(input_filename)
|
| 27 |
+
input_file_path = os.path.join(TRAIN_INPUT_FILE_PATH, input_filename)
|
| 28 |
+
output_file_path = os.path.join(TRAIN_OUTPUT_FILE_PATH, output_filename)
|
| 29 |
+
input_file_paths.append(input_file_path)
|
| 30 |
+
output_file_paths.append(output_file_path)
|
| 31 |
+
else:
|
| 32 |
+
raise Exception(f'input file for week {w} does not exist')
|
| 33 |
+
|
| 34 |
+
return (input_file_paths, output_file_paths)
|
| 35 |
+
|
| 36 |
+
def load_file(file_path):
|
| 37 |
+
return pd.read_csv(file_path)
|
| 38 |
+
|
| 39 |
+
def get_input_output_df():
|
| 40 |
+
input_file_paths, output_file_paths = get_train_file_paths()
|
| 41 |
+
|
| 42 |
+
with ThreadPoolExecutor(max_workers = 8) as executor:
|
| 43 |
+
input_dfs = executor.map(load_file, input_file_paths)
|
| 44 |
+
input_df = pd.concat(input_dfs, axis=0)
|
| 45 |
+
|
| 46 |
+
with ThreadPoolExecutor(max_workers = 8) as executor:
|
| 47 |
+
output_dfs = executor.map(load_file, output_file_paths)
|
| 48 |
+
output_df = pd.concat(output_dfs, axis=0)
|
| 49 |
+
|
| 50 |
+
return input_df.reset_index(drop=True), output_df.reset_index(drop=True)
|
| 51 |
+
|
| 52 |
+
def plot_distribution_of_features(input_df, output_df):
|
| 53 |
+
predict_players_position = Counter()
|
| 54 |
+
predict_players_role = Counter()
|
| 55 |
+
predict_players_side = Counter()
|
| 56 |
+
|
| 57 |
+
num_frames_to_predict = Counter()
|
| 58 |
+
no_players_prediction_in_a_play = Counter()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
plays = input_df.groupby(['game_id', 'play_id'], as_index = False)
|
| 62 |
+
|
| 63 |
+
per_play_change_in_dists = []
|
| 64 |
+
per_frame_change_in_dists = []
|
| 65 |
+
per_frame_change_in_x_dists = []
|
| 66 |
+
per_frame_change_in_y_dists = []
|
| 67 |
+
for _, play in plays:
|
| 68 |
+
|
| 69 |
+
predict_players = play[play['player_to_predict']]
|
| 70 |
+
|
| 71 |
+
no_players_prediction_in_a_play[predict_players['nfl_id'].nunique()]+=1
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
num_frames_output = play['num_frames_output'].iloc[0].item()
|
| 75 |
+
num_frames_to_predict[num_frames_output]+=1
|
| 76 |
+
|
| 77 |
+
predict_players_last_frame = predict_players.groupby(['nfl_id'], as_index=False).last()
|
| 78 |
+
for index, p_l in predict_players_last_frame.iterrows():
|
| 79 |
+
game_id = p_l['game_id']
|
| 80 |
+
play_id = p_l['play_id']
|
| 81 |
+
p_nfl_id = p_l['nfl_id']
|
| 82 |
+
p_output = output_df[(output_df['game_id'] == game_id) & (output_df['play_id'] == play_id) & (output_df['nfl_id'] == p_nfl_id)]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
s = np.array([p_l['x'], p_l['y']])
|
| 86 |
+
|
| 87 |
+
total_dis = 0
|
| 88 |
+
for _,p_o in p_output.iterrows():
|
| 89 |
+
e = np.array([p_o['x'].item(), p_o['y'].item()])
|
| 90 |
+
current_dis = np.linalg.norm(e - s)
|
| 91 |
+
per_frame_change_in_dists.append(current_dis)
|
| 92 |
+
per_frame_change_in_x_dists.append(np.abs(e[0] - s[0]))
|
| 93 |
+
per_frame_change_in_y_dists.append(np.abs(e[1] - s[1]))
|
| 94 |
+
|
| 95 |
+
total_dis+= current_dis
|
| 96 |
+
s = e
|
| 97 |
+
|
| 98 |
+
per_play_change_in_dists.append(total_dis)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
position = p_l['player_position']
|
| 102 |
+
role = p_l['player_role']
|
| 103 |
+
side = p_l['player_side']
|
| 104 |
+
|
| 105 |
+
predict_players_position[position]+=1
|
| 106 |
+
predict_players_role[role]+=1
|
| 107 |
+
predict_players_side[side]+=1
|
| 108 |
+
|
| 109 |
+
def plot_bargraph(dict_items, name):
|
| 110 |
+
plt.figure(figsize=(10, 6))
|
| 111 |
+
df = pd.DataFrame(list(dict_items), columns = [name, 'count'])
|
| 112 |
+
df = df.sort_values(by='count', ascending=False)
|
| 113 |
+
sns.barplot(data=df, x=name, y='count')
|
| 114 |
+
plt.show()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
plot_bargraph(predict_players_position.items(), 'predict_player position')
|
| 118 |
+
plot_bargraph(predict_players_role.items(), 'predict_player role')
|
| 119 |
+
plot_bargraph(predict_players_side.items(), 'predict_player side')
|
| 120 |
+
|
| 121 |
+
plot_bargraph(no_players_prediction_in_a_play.items(), 'num of player to predict in a play')
|
| 122 |
+
plot_bargraph(num_frames_to_predict.items(), 'num of frames to predict in a play')
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def plot_density_plot(data, title, x):
|
| 126 |
+
plt.figure(figsize=(10, 6))
|
| 127 |
+
sns.kdeplot(data, fill=True, color="dodgerblue")
|
| 128 |
+
plt.title(title)
|
| 129 |
+
plt.xlabel(x)
|
| 130 |
+
plt.ylabel('Density')
|
| 131 |
+
plt.show()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
plot_density_plot(per_play_change_in_dists, 'total distance moved by a player in a play', 'distance')
|
| 135 |
+
plot_density_plot(per_frame_change_in_dists, 'distance moved by a player per frame', 'distance')
|
| 136 |
+
plot_density_plot(per_frame_change_in_x_dists, 'distance moved by a player along x per frame', 'distance')
|
| 137 |
+
plot_density_plot(per_frame_change_in_y_dists, 'distance moved by a player along y per frame', 'distance')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_last_frame(df):
|
| 141 |
+
|
| 142 |
+
df_sorted = df.sort_values(['game_id', 'play_id', 'nfl_id', 'frame_id']).reset_index(drop=True)
|
| 143 |
+
|
| 144 |
+
group_by_cols = ['game_id', 'play_id', 'nfl_id']
|
| 145 |
+
|
| 146 |
+
feature_cols = ['x', 'y', 'o', 'dir', 's', 'a']
|
| 147 |
+
|
| 148 |
+
df_sorted[[f'{c}_prev' for c in feature_cols]] = df_sorted.groupby(group_by_cols)[feature_cols].shift(1)
|
| 149 |
+
|
| 150 |
+
#last() takes non none values from the last possible col
|
| 151 |
+
#so even if last frame misses a feature , value is taken from the previous available one
|
| 152 |
+
df_last_frame = df_sorted.groupby(group_by_cols, as_index=False).last()
|
| 153 |
+
|
| 154 |
+
df_last_frame = df_last_frame.rename(columns={'x':'x_last', 'y':'y_last'})
|
| 155 |
+
|
| 156 |
+
return df_last_frame
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def predict_physics_baseline(input_df, output_df):
|
| 160 |
+
|
| 161 |
+
def convert_to_radians(degrees):
|
| 162 |
+
return degrees * np.pi / 180
|
| 163 |
+
|
| 164 |
+
def sin(theta):
|
| 165 |
+
return np.sin(convert_to_radians(theta))
|
| 166 |
+
|
| 167 |
+
def cos(theta):
|
| 168 |
+
return np.cos(convert_to_radians(theta))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
input_df = input_df.copy()
|
| 172 |
+
|
| 173 |
+
output_df = output_df.copy()
|
| 174 |
+
|
| 175 |
+
df_last_frame = get_last_frame(input_df)
|
| 176 |
+
|
| 177 |
+
df_last_frame = df_last_frame[['game_id', 'play_id', 'nfl_id', 'x_last', 'y_last', 'o', 'dir', 's', 'a', 'num_frames_output']]
|
| 178 |
+
|
| 179 |
+
df = output_df.merge(df_last_frame, on=['game_id', 'play_id', 'nfl_id'], how='left')
|
| 180 |
+
|
| 181 |
+
sum_ = 0
|
| 182 |
+
for _, group_df in df.groupby(['game_id', 'play_id', 'nfl_id'], as_index=False):
|
| 183 |
+
|
| 184 |
+
group_df = group_df.sort_values('frame_id').reset_index(drop=True)
|
| 185 |
+
|
| 186 |
+
prev = (group_df.iloc[0]['x'], group_df.iloc[0]['y'])
|
| 187 |
+
for row in group_df.itertuples():
|
| 188 |
+
dt = 0.1
|
| 189 |
+
|
| 190 |
+
velocity_x = row.s * sin(row.dir)
|
| 191 |
+
velocity_y_ = row.s * cos(row.dir)
|
| 192 |
+
acc_x_ = row.a * sin(row.dir)
|
| 193 |
+
acc_y_ = row.a * cos(row.dir)
|
| 194 |
+
|
| 195 |
+
proj_x = prev[0] + velocity_x*dt + 0.5*acc_x_*(dt**2)
|
| 196 |
+
proj_y = prev[1] + velocity_y_*dt + 0.5*acc_y_*(dt**2)
|
| 197 |
+
|
| 198 |
+
sum_+= (row.x - proj_x)**2 + (row.y - proj_y)**2
|
| 199 |
+
prev = (proj_x, proj_y)
|
| 200 |
+
|
| 201 |
+
num_ele = df.shape[0]*2
|
| 202 |
+
rmse = np.sqrt(sum_ / num_ele)
|
| 203 |
+
print(f'RMSE of the simple physics based model is {rmse}')
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
input_df, output_df = get_input_output_df()
|
| 207 |
+
POSITION_MAPPING = [
|
| 208 |
+
"FS --> Free Safety",
|
| 209 |
+
"SS --> Strong Safety",
|
| 210 |
+
"CB --> Cornerback",
|
| 211 |
+
"MLB --> Middle Linebacker",
|
| 212 |
+
"WR --> Wide Receiver",
|
| 213 |
+
"TE --> Tight End",
|
| 214 |
+
"QB --> Quarterback",
|
| 215 |
+
"OLB --> Outside Linebacker",
|
| 216 |
+
"ILB --> Inside Linebacker",
|
| 217 |
+
"RB --> Running Back",
|
| 218 |
+
"DE --> Defensive End",
|
| 219 |
+
"FB --> Fullback",
|
| 220 |
+
"NT --> Nose Tackle",
|
| 221 |
+
"DT --> Defensive Tackle",
|
| 222 |
+
"S --> Safety",
|
| 223 |
+
"T --> Tackle",
|
| 224 |
+
"LB --> Linebacker",
|
| 225 |
+
"P --> Punter",
|
| 226 |
+
"K --> Kicker"
|
| 227 |
+
]
|
| 228 |
+
|
| 229 |
+
PLAYER_ROLES = ['Defensive Coverage' 'Other Route Runner' 'Passer' 'Targeted Receiver']
|
| 230 |
+
|
| 231 |
+
PLAYER_SIDES = ['Defense', 'Offense']
|
| 232 |
+
|
| 233 |
+
print(f'player positions are {POSITION_MAPPING}')
|
| 234 |
+
print(f'player roles are {PLAYER_ROLES}')
|
| 235 |
+
print(f'player roles are {PLAYER_SIDES}')
|
| 236 |
+
|
| 237 |
+
# plot_distribution_of_features(input_df[:1_000_00], output_df)
|
| 238 |
+
|
| 239 |
+
predict_physics_baseline(input_df, output_df)
|