generated from LufsX/Challenge-SVM
115 lines
3.1 KiB
Python
115 lines
3.1 KiB
Python
# 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)
|
|
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, 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
|
|
|
|
|
|
# 这里也写自己的代码实现
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
def load_data(data):
|
|
# 将数据转换为 DataFrame
|
|
df = pd.DataFrame(data)
|
|
|
|
# 清洗数据,替换 '?' 为 NaN
|
|
df.replace('?', np.nan, inplace=True)
|
|
|
|
# 尝试将数据转换为浮点数
|
|
df = df.apply(pd.to_numeric, errors='coerce')
|
|
|
|
return df
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# 以下代码可用于测试,可自行随意修改
|
|
# 加载训练集
|
|
X_train, y_train = load_data("./data/horse-colic.data")
|
|
|
|
# 加载测试集
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
|
|
# 训练支持向量机模型
|
|
weights, bias = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000)
|
|
|
|
# 测试单个数据
|
|
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}%") |