From abe61e5cdc0ae6462776060cee1fa1c69ab19a52 Mon Sep 17 00:00:00 2001 From: 77 <3298722099@qq.com> Date: Sat, 28 Dec 2024 12:07:28 +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 | 168 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 124 insertions(+), 44 deletions(-) diff --git a/function.py b/function.py index a7acbee..a684ec8 100644 --- a/function.py +++ b/function.py @@ -1,77 +1,157 @@ +# 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 +""" id = "202210423201" name = "陈瑞琪祥" + + +# 这里写自己的代码实现 import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.metrics import accuracy_score +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]) - features = np.array(fields[:-6] + fields[-5:], dtype=float) - if label in [1, 2, 3]: - label = {1: 0, 2: 1, 3: 2}[label] - data.append(features) - labels.append(label) + # 特征为其他列(不包含倒数第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) - return np.array(data), np.array(labels) - -# 线性SVM训练函数 -def train_svm(X, y): - n_samples, n_features = X.shape - weights = np.zeros(n_features) - bias = 0 - learning_rate = 0.01 - iterations = 1000 + # 转换为numpy数组 + data = np.array(data) + labels = np.array(labels) - for _ in range(iterations): - for idx, x_i in enumerate(X): - condition = y[idx] * (np.dot(x_i, weights) - bias) >= 1 - if not condition: - weights -= learning_rate * (2 * weights - np.dot(x_i, y[idx])) - bias -= learning_rate * y[idx] + 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 weights, bias + return model -# 预测函数 -def predict_svm(X, weights, bias): - return np.sign(np.dot(X, weights) - bias) -# 评估函数 -def evaluate_svm(test_data, weights, bias): - predictions = [predict_svm(test_data[i].reshape(1, -1), weights, bias) for i in range(len(test_data))] - return predictions +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, y = load_data("./data/horse-colic.data") - - # 分割数据集 - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) - - # 训练SVM模型 - weights, bias = train_svm(X_train, y_train) - + 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=42) + 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 = evaluate_svm(X_test, weights, bias) - - # 评估模型 + 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.reshape(1, -1), weights, bias) - print(f"\n单个样本预测结果: {y_pred_single[0]}, 实际结果: {y_test[11]}") + y_pred_single = predict_svm(test_sample, svm_model) + print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_test[11]}")