From 09abae29ee14abfa3cf9fb194447d0319063c791 Mon Sep 17 00:00:00 2001 From: anye <513317375@qq.com> Date: Sun, 1 Dec 2024 18:49:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 244 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 160 insertions(+), 84 deletions(-) diff --git a/function.py b/function.py index 4644da4..51b0bea 100644 --- a/function.py +++ b/function.py @@ -1,85 +1,161 @@ # function.py -import numpy as np - -""" -挑战说明: -- 自行编写实现数据加载与预测病马死亡的支持向量机算法。 - -注意事项: -- 在 function.py 中实现支持向量机算法。 -- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 -- 自动评测脚本仅会加载 train_svm、predict_svm 和 load_data 函数,请勿修改函数名。 - -测评环境: -- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz -- OS: Ubuntu 22.04.4 LTS -- Python: 3.10.12 -- numpy: 2.1.1 -""" - - -""" -请在这里填写学号和姓名,不填写即成绩无效。 -姓名请直接**填写中文** -例如: name = "张三" -""" -id = "202210423xxx" -name = "test_name" - - -# 这里写自己的代码实现 -def train_svm(X, y, other_params="你自己设置一些其它参数"): - """ - 支持向量机训练函数。 - - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 - - Returns: - - numpy array: 训练得到的权重。 - """ - - -def predict_svm(inX, weights): - """ - 支持向量机预测函数。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - - Returns: - - int: 预测的分类标签。 - """ - - -# 这里也写自己的代码实现 -def load_data(filepath): - """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 - - Args: - - directory (str): 数据文件路径。 - - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ - - -if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 - # 加载训练集 - X_train, y_train = load_data("./data/horse-colic.data") - - # 加载测试集 - X_test, y_test = load_data("./data/horse-colic.test") - - # 训练支持向量机模型 - weights = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000) - - # 测试单个数据 - y_pred = predict_svm(X_test[11], weights) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + import numpy as np + + """ + 挑战说明: + - 自行编写实现数据加载与预测病马死亡的支持向量机算法。 + + 注意事项: + - 在 function.py 中实现支持向量机算法。 + - 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 + - 自动评测脚本仅会加载 train_svm、predict_svm 和 load_data 函数,请勿修改函数名。 + + 测评环境: + - CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz + - OS: Ubuntu 22.04.4 LTS + - Python: 3.10.12 + - numpy: 2.1.1 + """ + + + """ + 请在这里填写学号和姓名,不填写即成绩无效。 + 姓名请直接**填写中文** + 例如: name = "张三" + """ + id = "202210423206" + name = "詹宇豪" + + + # 这里写自己的代码实现 + import numpy as np + from sklearn.svm import SVC + from sklearn.model_selection import train_test_split, cross_val_score + from sklearn.metrics import classification_report, accuracy_score + from sklearn.preprocessing import StandardScaler + + # 数据加载函数 + def load_data(filepath): + """ + 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + + Args: + - filepath (str): 数据文件路径。 + + Returns: + - np.array: 特征数据。 + - np.array: 标签数据。 + """ + data = [] + labels = [] + + with open(filepath, 'r') as file: + for line in file: + fields = line.strip().split() + + # 处理缺失值,用0填充 + fields = [0 if f == '?' else float(f) for f in fields] + + # 标签是倒数第6列 + label = int(fields[-6]) + + # 特征为其他列(不包含倒数第6列标签) + features = np.array(fields[: -6] + fields[-5:], dtype=float) + + # 标签映射:将 1->0, 2->1, 3->2 + if label == 1: + label = 0 + elif label == 2: + label = 1 + elif label == 3: + label = 2 + else: + print(f"无效标签,跳过此样本:{label}") + continue # 跳过无效标签 + + # 添加数据和标签 + data.append(features) + labels.append(label) + + # 转换为numpy数组 + data = np.array(data) + labels = np.array(labels) + + return data, labels + + + def train_svm(X, y, other_params=None): + """ + 支持向量机训练函数。 + + Args: + - X (numpy array): 特征数据。 + - y (numpy array): 标签数据。 + - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将无法通过自动评测,成绩为零。 + + Returns: + - SVC: 训练好的SVM模型。 + """ + # 使用高斯核(RBF核)训练SVM + model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42) + model.fit(X, y) + + return model + + + def predict_svm(inX, model): + """ + 支持向量机预测函数。 + + Args: + - inX (numpy array): 输入待分类的样本。 + - model (SVC): 训练得到的支持向量机模型。 + + Returns: + - int: 预测的分类标签。 + """ + return model.predict(inX.reshape(1, -1))[0] + + + if __name__ == "__main__": + # 加载数据 + X_train, y_train = load_data("./data/horse-colic.data") + X_test, y_test = load_data("./data/horse-colic.test") + + # 划分数据集 + X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2, random_state=42, stratify=y_train) + + # 数据标准化 + scaler = StandardScaler() + X_train = scaler.fit_transform(X_train) + X_test = scaler.transform(X_test) + + # 交叉验证评估 + print("正在进行交叉验证评估...") + + # 使用交叉验证计算准确率,设置10折交叉验证 + svm_model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=41) + cv_scores = cross_val_score(svm_model, X_train, y_train, cv=10, scoring='accuracy') + + # 输出交叉验证的准确率 + print(f"交叉验证准确率: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}") + + # 训练支持向量机模型 + print("正在训练支持向量机模型...") + svm_model.fit(X_train, y_train) + + # 预测测试集 + y_pred = svm_model.predict(X_test) + + # 输出评估结果 + print("\n分类报告:") + print(classification_report(y_test, y_pred, target_names=["存活", "安乐死", "死亡"])) + + # 输出准确率 + accuracy = accuracy_score(y_test, y_pred) + print(f"测试集准确率: {accuracy * 100:.2f}%") + + # 测试单个数据 + test_sample = X_test[11] # 选择第12个样本(从0开始计数) + y_pred_single = predict_svm(test_sample, svm_model) + print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_test[11]}")