diff --git a/function.py b/function.py index 1a8bc95..03e806a 100644 --- a/function.py +++ b/function.py @@ -1,45 +1,14 @@ # 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 = "202210423217" name = "吴俊煯" # 这里写自己的代码实现 def train_svm(X, y, learning_rate=0.01, iterations=1000): - """ - 支持向量机训练函数。 - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - learning_rate (float): 学习率。 - - iterations (int): 迭代次数。 - - Returns: - - numpy array: 训练得到的权重。 - """ n_samples, n_features = X.shape # 初始化权重和偏置 weights = np.zeros(n_features) @@ -62,54 +31,28 @@ def train_svm(X, y, learning_rate=0.01, iterations=1000): def predict_svm(inX, weights, bias): - """ - 支持向量机预测函数。 - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - - bias (float): 训练得到的偏置。 - - Returns: - - int: 预测的分类标签。 - """ linear_output = np.dot(inX, weights) + bias return 1 if linear_output >= 0 else -1 # 这里也写自己的代码实现 def load_data(filepath): - """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 - Args: - - filepath (str): 数据文件路径。 - - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ - # 使用空格作为分隔符加载数据 - data = np.loadtxt(filepath, delimiter=' ', dtype=str, comments=None) + data = np.loadtxt(filepath, delimiter=',', dtype=str, comments=None) # 检查数据的维度 if data.ndim == 1: data = data.reshape(1, -1) # 如果数据是一维的,重塑为二维 # 清洗数据,去除无法转换的值 - data[data == '?'] = '0' # 将问号替换为0或其他合适的值 + data = np.where(data == '?', '0', data) # 将问号替换为0或其他合适的值 X = data[:, :-1].astype(float) # 特征数据 y = data[:, -1] # 标签数据 - # 将标签转换为 0, 1, 2 - y = np.where(y == '1', 1, y) # 假设 '1' 表示死亡 - y = np.where(y == '2', 2, y) # 假设 '2' 表示安乐死 - y = np.where(y == '0', 0, y) # 假设 '0' 表示存活 - - # 确保 y 是整数类型 - y = y.astype(int) # 将 y 转换为整数类型 - + # 将标签转换为 -1 和 1 + y = np.where(y == '1', 1, -1) # 假设标签为 '1' 表示死亡,其他为存活 return X, y