| import os
|
| import pandas as pd
|
| import sklearn
|
| from sklearn.svm import SVC
|
| from sklearn.model_selection import train_test_split, cross_val_score
|
| from sklearn.preprocessing import StandardScaler
|
| from sklearn.pipeline import make_pipeline
|
|
|
|
|
|
|
|
|
| def main():
|
| """"""
|
| data=LoadData()
|
|
|
| svm_model = DepartData(data)
|
|
|
|
|
|
|
|
|
| def LoadData():
|
| dir_path=f"../summerOly_Teams_Data"
|
|
|
| data_dict = {}
|
| partition=32
|
|
|
| for filename in os.listdir(dir_path):
|
| if filename.endswith('.csv'):
|
|
|
| team_name = filename[:-4]
|
| file_path = os.path.join(dir_path, filename)
|
|
|
| df = pd.read_csv(file_path)
|
|
|
| df.set_index('Year', inplace=True)
|
|
|
| X = df.drop(columns=['Gold', 'Total'], errors='ignore')
|
|
|
|
|
| Y = (df['Total'][:partition] > 0).any()
|
|
|
|
|
| data_dict[team_name] = {}
|
| for year in X.index:
|
| if year >= 1992:
|
| continue
|
| data_dict[team_name][year] = {'X': X.loc[year], 'Y': Y}
|
| return data_dict
|
|
|
|
|
|
|
| def PrintData(data):
|
| team = 'United States'
|
| year = 1980
|
| if team in data and year in data[team]:
|
| X_data = data[team][year]['X']
|
| Y_data = data[team][year]['Y']
|
| print(f"Data for {team} in {year}:")
|
| print("Features (X):")
|
| print(X_data)
|
| print("\nLabel (Y):")
|
| print(Y_data)
|
| else:
|
| print(f"No data available for {team} in {year}.")
|
|
|
|
|
| def DepartData(data):
|
|
|
| all_X = []
|
| all_Y = []
|
| for team in data:
|
| for year in data[team]:
|
| all_X.append(data[team][year]['X'].values)
|
| all_Y.append(data[team][year]['Y'])
|
|
|
| all_X = pd.DataFrame(all_X)
|
| all_Y = pd.Series(all_Y)
|
|
|
| X_train, X_test, y_train, y_test = train_test_split(all_X, all_Y, test_size=0.2, random_state=42)
|
| print(X_train)
|
| print(X_test)
|
|
|
| svm_model = make_pipeline(StandardScaler(), SVC(kernel='linear', random_state=42))
|
|
|
|
|
|
|
| svm_model.fit(X_train, y_train)
|
|
|
| train_score = svm_model.score(X_train, y_train)
|
| test_score = svm_model.score(X_test, y_test)
|
| print(f"Training Set Accuracy: {train_score:.4f}")
|
| print(f"Test Set Accuracy: {test_score:.4f}")
|
|
|
| cv_scores = cross_val_score(svm_model, all_X, all_Y, cv=5)
|
| print(f"Cross-Validation Scores: {cv_scores}")
|
| print(f"Mean Cross-Validation Score: {cv_scores.mean():.4f}")
|
|
|
| return svm_model
|
|
|
| if __name__=="__main__":
|
| main()
|
|
|
|
|
|
|
|
|
|
|