Create src/main.py
Browse files- src/main.py +211 -0
src/main.py
ADDED
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import logging
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
import tensorflow as tf
|
7 |
+
from sklearn.model_selection import train_test_split
|
8 |
+
from sklearn.preprocessing import StandardScaler
|
9 |
+
|
10 |
+
# Set up logging
|
11 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
12 |
+
|
13 |
+
def load_data(start_year=2000, end_year=2017):
|
14 |
+
csv_files = [f'atp_matches_{year}.csv' for year in range(start_year, end_year + 1)]
|
15 |
+
dataframes = []
|
16 |
+
|
17 |
+
for file in csv_files:
|
18 |
+
try:
|
19 |
+
data = pd.read_csv(file)
|
20 |
+
logging.info(f"Loaded {file}: {len(data)} rows")
|
21 |
+
dataframes.append(data)
|
22 |
+
except FileNotFoundError:
|
23 |
+
logging.warning(f"File {file} not found.")
|
24 |
+
continue
|
25 |
+
|
26 |
+
if not dataframes:
|
27 |
+
raise FileNotFoundError("No CSV files found. Ensure data files are present.")
|
28 |
+
|
29 |
+
combined_df = pd.concat(dataframes, ignore_index=True)
|
30 |
+
logging.info(f"Total rows after combining all dataframes: {len(combined_df)}")
|
31 |
+
return combined_df
|
32 |
+
|
33 |
+
def preprocess_data(df):
|
34 |
+
logging.info(f"Before preprocessing: {len(df)} rows")
|
35 |
+
df = df.loc[:, ~df.columns.duplicated()]
|
36 |
+
df = df.drop_duplicates().reset_index(drop=True)
|
37 |
+
|
38 |
+
df['tourney_date'] = pd.to_datetime(df['tourney_date'], format='%Y%m%d', errors='coerce')
|
39 |
+
df['tourney_date_ordinal'] = df['tourney_date'].apply(lambda x: x.toordinal() if pd.notnull(x) else None)
|
40 |
+
|
41 |
+
df['winner_id'] = df['winner_id'].fillna(df['winner_id'].mode().iloc[0])
|
42 |
+
df['loser_id'] = df['loser_id'].fillna(df['loser_id'].mode().iloc[0])
|
43 |
+
df['winner_name'] = df['winner_name'].fillna('Unknown')
|
44 |
+
df['loser_name'] = df['loser_name'].fillna('Unknown')
|
45 |
+
|
46 |
+
logging.info(f"After preprocessing: {len(df)} rows")
|
47 |
+
logging.info(f"Date range: {df['tourney_date'].min()} to {df['tourney_date'].max()}")
|
48 |
+
logging.info(f"Years present in the data: {sorted(df['tourney_date'].dt.year.unique())}")
|
49 |
+
return df
|
50 |
+
|
51 |
+
def engineer_features(df):
|
52 |
+
numeric_columns = ['winner_rank', 'loser_rank', 'winner_seed', 'loser_seed',
|
53 |
+
'winner_age', 'loser_age', 'w_svpt', 'l_svpt', 'w_ace',
|
54 |
+
'l_ace', 'w_df', 'l_df', 'w_bpSaved', 'l_bpSaved',
|
55 |
+
'tourney_date_ordinal']
|
56 |
+
|
57 |
+
for col in numeric_columns:
|
58 |
+
if col in df.columns:
|
59 |
+
df[col] = pd.to_numeric(df[col], errors='coerce')
|
60 |
+
logging.info(f"Column {col}: {df[col].isnull().sum()} null values")
|
61 |
+
else:
|
62 |
+
logging.warning(f"Column '{col}' not found in dataframe.")
|
63 |
+
|
64 |
+
df[numeric_columns] = df[numeric_columns].fillna(df[numeric_columns].median())
|
65 |
+
|
66 |
+
df['age_diff'] = df['winner_age'] - df['loser_age']
|
67 |
+
df['service_diff'] = df['w_svpt'] - df['l_svpt']
|
68 |
+
df['ace_diff'] = df['w_ace'] - df['l_ace']
|
69 |
+
df['df_diff'] = df['w_df'] - df['l_df']
|
70 |
+
df['bp_saved_diff'] = df['w_bpSaved'] - df['l_bpSaved']
|
71 |
+
|
72 |
+
numeric_columns.extend(['age_diff', 'service_diff', 'ace_diff', 'df_diff', 'bp_saved_diff'])
|
73 |
+
|
74 |
+
logging.info(f"After feature engineering: {len(df)} rows")
|
75 |
+
return df, numeric_columns
|
76 |
+
|
77 |
+
def create_vae_model(input_dim, latent_dim=2):
|
78 |
+
encoder = tf.keras.Sequential([
|
79 |
+
tf.keras.layers.Dense(16, activation='relu', input_shape=(input_dim,)),
|
80 |
+
tf.keras.layers.Dense(latent_dim)
|
81 |
+
])
|
82 |
+
|
83 |
+
decoder = tf.keras.Sequential([
|
84 |
+
tf.keras.layers.Dense(16, activation='relu', input_shape=(latent_dim,)),
|
85 |
+
tf.keras.layers.Dense(input_dim, activation='sigmoid')
|
86 |
+
])
|
87 |
+
|
88 |
+
class VAEModel(tf.keras.Model):
|
89 |
+
def __init__(self, encoder, decoder, **kwargs):
|
90 |
+
super(VAEModel, self).__init__(**kwargs)
|
91 |
+
self.encoder = encoder
|
92 |
+
self.decoder = decoder
|
93 |
+
|
94 |
+
def call(self, inputs):
|
95 |
+
encoded = self.encoder(inputs)
|
96 |
+
decoded = self.decoder(encoded)
|
97 |
+
return decoded
|
98 |
+
|
99 |
+
vae = VAEModel(encoder, decoder)
|
100 |
+
vae.compile(optimizer='adam', loss='mse')
|
101 |
+
|
102 |
+
return vae
|
103 |
+
|
104 |
+
def detect_anomalies(df, threshold=None):
|
105 |
+
if threshold is None:
|
106 |
+
threshold = df['rank_diff'].abs().quantile(0.85) # 85th percentile
|
107 |
+
logging.info(f"Using anomaly threshold: {threshold}")
|
108 |
+
logging.info(f"Years in the data before anomaly detection: {sorted(df['tourney_date'].dt.year.unique())}")
|
109 |
+
|
110 |
+
anomalies = []
|
111 |
+
for i, row in df.iterrows():
|
112 |
+
rank_diff = row['winner_rank'] - row['loser_rank']
|
113 |
+
if abs(rank_diff) > threshold:
|
114 |
+
anomalies.append(row)
|
115 |
+
|
116 |
+
anomalies_df = pd.DataFrame(anomalies)
|
117 |
+
|
118 |
+
if anomalies_df.empty:
|
119 |
+
logging.warning("No anomalies detected!")
|
120 |
+
return anomalies_df
|
121 |
+
|
122 |
+
yearly_counts = anomalies_df['tourney_date'].dt.year.value_counts().sort_index()
|
123 |
+
logging.info(f"Anomalies per year:\n{yearly_counts}")
|
124 |
+
|
125 |
+
logging.info(f"Years in the anomalies: {sorted(anomalies_df['tourney_date'].dt.year.unique())}")
|
126 |
+
logging.info(f"Total anomalies: {len(anomalies_df)}")
|
127 |
+
|
128 |
+
return anomalies_df
|
129 |
+
|
130 |
+
def analyze_anomalies(anomalies):
|
131 |
+
anomalies['tourney_name'] = anomalies['tourney_name'].fillna('Unknown')
|
132 |
+
|
133 |
+
anomalies_per_year = anomalies.groupby(anomalies['tourney_date'].dt.year).size()
|
134 |
+
anomalies_per_player = pd.concat([anomalies['winner_name'], anomalies['loser_name']]).value_counts()
|
135 |
+
anomalies_per_tournament = anomalies['tourney_name'].value_counts()
|
136 |
+
|
137 |
+
grand_slams = anomalies[anomalies['tourney_name'].str.contains('Grand Slam', case=False, na=False)]['tourney_name'].value_counts()
|
138 |
+
masters_1000 = anomalies[anomalies['tourney_name'].str.contains('Masters 1000', case=False, na=False)]['tourney_name'].value_counts()
|
139 |
+
|
140 |
+
return anomalies_per_year, anomalies_per_player, anomalies_per_tournament, grand_slams, masters_1000
|
141 |
+
|
142 |
+
def save_results(anomalies, anomalies_per_year, anomalies_per_player, anomalies_per_tournament, grand_slams, masters_1000):
|
143 |
+
anomalies.to_csv('anomalies.csv', index=False)
|
144 |
+
anomalies_per_year.to_csv('anomalies_per_year.csv')
|
145 |
+
anomalies_per_player.to_csv('anomalies_per_player.csv')
|
146 |
+
anomalies_per_tournament.to_csv('anomalies_per_tournament.csv')
|
147 |
+
grand_slams.to_csv('anomalies_per_grand_slam.csv')
|
148 |
+
masters_1000.to_csv('anomalies_per_masters_1000.csv')
|
149 |
+
|
150 |
+
pd.DataFrame(anomalies_per_player.index.tolist(), columns=['Player']).to_csv('most_anomalies_players.csv', index=False)
|
151 |
+
pd.DataFrame(anomalies_per_tournament.index.tolist(), columns=['Tournament']).to_csv('most_anomalies_tournaments.csv', index=False)
|
152 |
+
pd.DataFrame(grand_slams.index.tolist(), columns=['Grand Slam']).to_csv('most_anomalies_grand_slams.csv', index=False)
|
153 |
+
pd.DataFrame(masters_1000.index.tolist(), columns=['Masters 1000']).to_csv('most_anomalies_masters_1000.csv', index=False)
|
154 |
+
|
155 |
+
def main():
|
156 |
+
logging.info("Starting script...")
|
157 |
+
|
158 |
+
df = load_data()
|
159 |
+
logging.info(f"Total rows after loading: {len(df)}")
|
160 |
+
|
161 |
+
df = preprocess_data(df)
|
162 |
+
df, numeric_columns = engineer_features(df)
|
163 |
+
logging.info(f"Total rows after preprocessing and feature engineering: {len(df)}")
|
164 |
+
|
165 |
+
# Calculate rank difference
|
166 |
+
df['rank_diff'] = df['winner_rank'] - df['loser_rank']
|
167 |
+
|
168 |
+
# Log rank difference statistics
|
169 |
+
logging.info(f"Rank difference stats:\n{df['rank_diff'].describe()}")
|
170 |
+
logging.info(f"Rank difference percentiles:")
|
171 |
+
for percentile in [50, 75, 90, 95, 99]:
|
172 |
+
logging.info(f"{percentile}th percentile: {df['rank_diff'].abs().quantile(percentile/100)}")
|
173 |
+
|
174 |
+
# Log some statistics about the 'winner_rank' and 'loser_rank' columns
|
175 |
+
logging.info(f"Winner rank stats:\n{df['winner_rank'].describe()}")
|
176 |
+
logging.info(f"Loser rank stats:\n{df['loser_rank'].describe()}")
|
177 |
+
|
178 |
+
X = df[numeric_columns].copy()
|
179 |
+
y = df['winner_rank'] - df['loser_rank']
|
180 |
+
|
181 |
+
scaler = StandardScaler()
|
182 |
+
X_scaled = scaler.fit_transform(X)
|
183 |
+
|
184 |
+
X_train_scaled, X_test_scaled, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
|
185 |
+
|
186 |
+
X_train_scaled = X_train_scaled.astype('float32')
|
187 |
+
X_test_scaled = X_test_scaled.astype('float32')
|
188 |
+
|
189 |
+
vae = create_vae_model(X_train_scaled.shape[1])
|
190 |
+
|
191 |
+
logging.info("Model compiled. Starting training...")
|
192 |
+
history = vae.fit(X_train_scaled, X_train_scaled, epochs=10, batch_size=32,
|
193 |
+
validation_data=(X_test_scaled, X_test_scaled), verbose=1)
|
194 |
+
logging.info("Model training complete.")
|
195 |
+
|
196 |
+
anomalies = detect_anomalies(df)
|
197 |
+
if not anomalies.empty:
|
198 |
+
logging.info(f"Number of anomalies: {len(anomalies)}")
|
199 |
+
logging.info(f"Anomalies date range: {anomalies['tourney_date'].min()} to {anomalies['tourney_date'].max()}")
|
200 |
+
|
201 |
+
anomalies_per_year, anomalies_per_player, anomalies_per_tournament, grand_slams, masters_1000 = analyze_anomalies(anomalies)
|
202 |
+
|
203 |
+
logging.info("Saving results...")
|
204 |
+
save_results(anomalies, anomalies_per_year, anomalies_per_player, anomalies_per_tournament, grand_slams, masters_1000)
|
205 |
+
else:
|
206 |
+
logging.warning("No anomalies detected. Skipping analysis and result saving.")
|
207 |
+
|
208 |
+
logging.info("Script execution completed.")
|
209 |
+
|
210 |
+
if __name__ == "__main__":
|
211 |
+
main()
|