diff --git a/function.py b/function.py index 4644da4..8cb28e1 100644 --- a/function.py +++ b/function.py @@ -3,12 +3,12 @@ import numpy as np """ 挑战说明: -- 自行编写实现数据加载与预测病马死亡的支持向量机算法。 +- 自行编写实现数据加载与预测病马死亡的支持向量机算法。 注意事项: - 在 function.py 中实现支持向量机算法。 - 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 -- 自动评测脚本仅会加载 train_svm、predict_svm 和 load_data 函数,请勿修改函数名。 +- 自动评测脚本仅会加载 train_svm、predict_svm 和 load_data 函数,请勿修改函数名。 测评环境: - CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz @@ -17,42 +17,64 @@ import numpy as np - numpy: 2.1.1 """ - """ 请在这里填写学号和姓名,不填写即成绩无效。 姓名请直接**填写中文** 例如: name = "张三" """ -id = "202210423xxx" -name = "test_name" +id = "202210423217" +name = "吴俊煯" # 这里写自己的代码实现 -def train_svm(X, y, other_params="你自己设置一些其它参数"): +def train_svm(X, y, learning_rate=0.01, iterations=1000): """ 支持向量机训练函数。 Args: - X (numpy array): 特征数据。 - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 + - learning_rate (float): 学习率。 + - iterations (int): 迭代次数。 Returns: - numpy array: 训练得到的权重。 """ + n_samples, n_features = X.shape + # 初始化权重和偏置 + weights = np.zeros(n_features) + bias = 0 + + # 训练过程 + for _ in range(iterations): + for idx, x_i in enumerate(X): + # 计算预测值 + linear_output = np.dot(x_i, weights) + bias + # 计算预测标签 + y_predicted = np.sign(linear_output) + + # 更新权重和偏置 + if y_predicted != y[idx]: + weights += learning_rate * (y[idx] * x_i) + bias += learning_rate * y[idx] + + return weights, bias -def predict_svm(inX, weights): +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 # 这里也写自己的代码实现 @@ -61,12 +83,19 @@ def load_data(filepath): 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 Args: - - directory (str): 数据文件路径。 + - filepath (str): 数据文件路径。 Returns: - np.array: 特征数据。 - np.array: 标签数据。 """ + data = np.loadtxt(filepath, delimiter=',', dtype=str) + X = data[:, :-1].astype(float) # 特征数据 + y = data[:, -1] # 标签数据 + + # 将标签转换为 -1 和 1 + y = np.where(y == '1', 1, -1) # 假设标签为 '1' 表示死亡,其他为存活 + return X, y if __name__ == "__main__": @@ -78,8 +107,13 @@ if __name__ == "__main__": X_test, y_test = load_data("./data/horse-colic.test") # 训练支持向量机模型 - weights = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000) + weights, bias = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000) # 测试单个数据 - y_pred = predict_svm(X_test[11], weights) + y_pred = predict_svm(X_test[11], weights, bias) print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + + # 计算准确率 + correct_predictions = sum(predict_svm(x, weights, bias) == y for x, y in zip(X_test, y_test)) + accuracy = correct_predictions / len(y_test) + print(f"测试集准确率: {accuracy * 100:.2f}%") \ No newline at end of file