更新 function.py
Gitea Actions Test / Challenge-Actions (push) Successful in 26s

This commit is contained in:
2024-12-01 18:53:11 +08:00
parent 09abae29ee
commit accff61c5f
+117 -121
View File
@@ -1,161 +1,157 @@
# function.py import numpy as np
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
""" """
挑战说明: 挑战说明:
- 自行编写实现数据加载与预测病马死亡的支持向量机算法。 - 自行编写实现数据加载与预测病马死亡的支持向量机算法。
注意事项: 注意事项:
- 在 function.py 中实现支持向量机算法。 - 在 function.py 中实现支持向量机算法。
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 - 可以自行导入其他库,需要在 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 - CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
- OS: Ubuntu 22.04.4 LTS - OS: Ubuntu 22.04.4 LTS
- Python: 3.10.12 - Python: 3.10.12
- numpy: 2.1.1 - numpy: 2.1.1
""" """
"""
请在这里填写学号和姓名,不填写即成绩无效。
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423206"
name = "詹宇豪"
""" # 这里写自己的代码实现
请在这里填写学号和姓名,不填写即成绩无效。
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423206"
name = "詹宇豪"
# 数据加载函数
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
# 这里写自己的代码实现 Args:
import numpy as np - filepath (str): 数据文件路径。
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
# 数据加载函数 Returns:
def load_data(filepath): - np.array: 特征数据。
""" - np.array: 标签数据。
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 """
data = []
labels = []
Args: with open(filepath, 'r') as file:
- filepath (str): 数据文件路径。 for line in file:
fields = line.strip().split()
Returns: # 处理缺失值,用0填充
- np.array: 特征数据。 fields = [0 if f == '?' else float(f) for f in fields]
- np.array: 标签数据。
"""
data = []
labels = []
with open(filepath, 'r') as file: # 标签是倒数第6列
for line in file: label = int(fields[-6])
fields = line.strip().split()
# 处理缺失值,用0填充
fields = [0 if f == '?' else float(f) for f in fields]
# 标签是倒数第6列
label = int(fields[-6])
# 特征为其他列(不包含倒数第6列标签) # 特征为其他列(不包含倒数第6列标签)
features = np.array(fields[: -6] + fields[-5:], dtype=float) features = np.array(fields[: -6] + fields[-5:], dtype=float)
# 标签映射:将 1->0, 2->1, 3->2 # 标签映射:将 1->0, 2->1, 3->2
if label == 1: if label == 1:
label = 0 label = 0
elif label == 2: elif label == 2:
label = 1 label = 1
elif label == 3: elif label == 3:
label = 2 label = 2
else: else:
print(f"无效标签,跳过此样本:{label}") print(f"无效标签,跳过此样本:{label}")
continue # 跳过无效标签 continue # 跳过无效标签
# 添加数据和标签 # 添加数据和标签
data.append(features) data.append(features)
labels.append(label) labels.append(label)
# 转换为numpy数组 # 转换为numpy数组
data = np.array(data) data = np.array(data)
labels = np.array(labels) labels = np.array(labels)
return data, labels return data, labels
def train_svm(X, y, other_params=None): def train_svm(X, y, other_params=None):
""" """
支持向量机训练函数。 支持向量机训练函数。
Args: Args:
- X (numpy array): 特征数据。 - X (numpy array): 特征数据。
- y (numpy array): 标签数据。 - y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将无法通过自动评测,成绩为零。 - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将无法通过自动评测,成绩为零。
Returns: Returns:
- SVC: 训练好的SVM模型。 - SVC: 训练好的SVM模型。
""" """
# 使用高斯核(RBF核)训练SVM # 使用高斯核(RBF核)训练SVM
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42) model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
model.fit(X, y) model.fit(X, y)
return model return model
def predict_svm(inX, model): def predict_svm(inX, model):
""" """
支持向量机预测函数。 支持向量机预测函数。
Args: Args:
- inX (numpy array): 输入待分类的样本。 - inX (numpy array): 输入待分类的样本。
- model (SVC): 训练得到的支持向量机模型。 - model (SVC): 训练得到的支持向量机模型。
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
return model.predict(inX.reshape(1, -1))[0] return model.predict(inX.reshape(1, -1))[0]
if __name__ == "__main__": if __name__ == "__main__":
# 加载数据 # 加载数据
X_train, y_train = load_data("./data/horse-colic.data") X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test") 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) 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() scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test) X_test = scaler.transform(X_test)
# 交叉验证评估 # 交叉验证评估
print("正在进行交叉验证评估...") print("正在进行交叉验证评估...")
# 使用交叉验证计算准确率,设置10折交叉验证 # 使用交叉验证计算准确率,设置10折交叉验证
svm_model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=41) 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') 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(f"交叉验证准确率: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
# 训练支持向量机模型 # 训练支持向量机模型
print("正在训练支持向量机模型...") print("正在训练支持向量机模型...")
svm_model.fit(X_train, y_train) svm_model.fit(X_train, y_train)
# 预测测试集 # 预测测试集
y_pred = svm_model.predict(X_test) y_pred = svm_model.predict(X_test)
# 输出评估结果 # 输出评估结果
print("\n分类报告:") print("\n分类报告:")
print(classification_report(y_test, y_pred, target_names=["存活", "安乐死", "死亡"])) print(classification_report(y_test, y_pred, target_names=["存活", "安乐死", "死亡"]))
# 输出准确率 # 输出准确率
accuracy = accuracy_score(y_test, y_pred) accuracy = accuracy_score(y_test, y_pred)
print(f"测试集准确率: {accuracy * 100:.2f}%") print(f"测试集准确率: {accuracy * 100:.2f}%")
# 测试单个数据 # 测试单个数据
test_sample = X_test[11] # 选择第12个样本(从0开始计数) test_sample = X_test[11] # 选择第12个样本(从0开始计数)
y_pred_single = predict_svm(test_sample, svm_model) y_pred_single = predict_svm(test_sample, svm_model)
print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_test[11]}") print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_test[11]}")