Download 2025MCM_ICM/ProblemC/SVMClassifier.py from edzee3000/GithubData: direct link, hf CLI and curl.
- Browser
- Download file 4.46 kB
-
https://huggingface.co/datasets/edzee3000/GithubData/resolve/main/2025MCM_ICM/ProblemC/SVMClassifier.py
- Command line
-
hf download hf://datasets/edzee3000/GithubData/2025MCM_ICM/ProblemC/SVMClassifier.py
-
curl -L -o SVMClassifier.py https://huggingface.co/datasets/edzee3000/GithubData/resolve/main/2025MCM_ICM/ProblemC/SVMClassifier.py
4.46 kB
| 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() | |
| # PrintData(data) | |
| 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'): | |
| # 获取国家名称(文件名去掉.csv) | |
| team_name = filename[:-4] | |
| file_path = os.path.join(dir_path, filename) | |
| # 读取CSV文件 | |
| df = pd.read_csv(file_path) | |
| # 设置Year为索引 | |
| df.set_index('Year', inplace=True) | |
| # 提取特征X(去除第一列和第五、第六列) | |
| X = df.drop(columns=['Gold', 'Total'], errors='ignore') | |
| # 构建目标Y(是否获得过奖牌) | |
| # Y = (df['Gold'] > 0) | (df['Total'] > 0) | |
| Y = (df['Total'][:partition] > 0).any() | |
| # 将数据存储到字典中 | |
| # data_dict[team_name] = {'X': X, 'Y': Y} | |
| 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']) # 提取标签数据 | |
| # 将特征数据和标签数据转换为适合SVM的格式 | |
| 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分类器 | |
| svm_model = make_pipeline(StandardScaler(), SVC(kernel='linear', random_state=42)) | |
| #kernel='linear' 含义:kernel 参数指定了 SVM 所使用的核函数,核函数的作用是将输入数据映射到高维空间,从而使数据在高维空间中变得线性可分。'linear' 表示使用线性核函数,即不进行非线性映射,直接在原始特征空间中寻找最优的分类超平面。线性核函数适用于数据本身就是线性可分或者近似线性可分的情况,计算速度相对较快,且模型的可解释性较强。 适用场景:当特征数量较多,且数据大致呈线性分布时,线性核函数往往能取得较好的效果。 | |
| #random_state=42 含义:random_state 参数用于设置随机数生成器的种子。在 SVM 训练过程中,有些步骤可能涉及到随机初始化(例如在求解优化问题时的初始点选择),设置 random_state 可以保证每次运行代码时得到相同的随机结果,从而使实验具有可重复性。这里将其设置为 42 是一种常见的做法,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}") | |
| # 将训练好的 svm_model 返回即可 | |
| return svm_model | |
| if __name__=="__main__": | |
| main() | |