更新 function.py
Gitea Actions Test / Challenge-Actions (push) Failing after 1h11m53s

This commit is contained in:
2024-11-20 16:29:17 +08:00
parent e60dfb39cb
commit 848a3911a5
+33 -43
View File
@@ -1,42 +1,24 @@
id = "202210423230" id = "202210423230"
name = "尹家立" name = "尹家立"
# 这里写自己的代码实现 from sklearn.model_selection import GridSearchCV, train_test_split
import numpy as np
from sklearn.svm import SVC from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score from sklearn.metrics import classification_report, accuracy_score
from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import StandardScaler
import numpy as np
# 数据加载函数 # 数据加载函数保持不变
def load_data(filepath): def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = [] data = []
labels = [] labels = []
with open(filepath, 'r') as file: with open(filepath, 'r') as file:
for line in file: for line in file:
fields = line.strip().split() fields = line.strip().split()
# 处理缺失值,用0填充
fields = [0 if f == '?' else float(f) for f in fields] fields = [0 if f == '?' else float(f) for f in fields]
# 标签是倒数第6列
label = int(fields[-6]) label = int(fields[-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
if label == 1: if label == 1:
label = 0 label = 0
elif label == 2: elif label == 2:
@@ -44,39 +26,48 @@ def load_data(filepath):
elif label == 3: elif label == 3:
label = 2 label = 2
else: else:
print(f"无效标签,跳过此样本:{label}")
continue # 跳过无效标签 continue # 跳过无效标签
# 添加数据和标签
data.append(features) data.append(features)
labels.append(label) labels.append(label)
# 转换为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 # 参数网格
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42) param_grid = {
model.fit(X, y) 'C': [0.1, 1, 10, 100],
'gamma': ['scale', 0.01, 0.1, 1],
'kernel': ['rbf', 'linear'],
'class_weight': [None, 'balanced']
}
return model # 初始化SVM
svm = SVC(random_state=42)
# 网格搜索调参
grid_search = GridSearchCV(svm, param_grid, cv=5, scoring='accuracy', verbose=1, n_jobs=-1)
grid_search.fit(X, y)
# 输出最佳参数
print(f"最佳参数: {grid_search.best_params_}")
return grid_search.best_estimator_
# 单个样本预测函数保持不变
def predict_svm(inX, model): def predict_svm(inX, model):
""" """
支持向量机预测函数。 支持向量机预测函数。
@@ -90,36 +81,35 @@ def predict_svm(inX, model):
""" """
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, y = 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) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
# 数据标准化 # 数据标准化
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)
# 训练支持向量机模型 # 调优并训练SVM模型
print("正在训练支持向量机模型...") print("正在调优支持向量机模型...")
svm_model = train_svm(X_train, y_train) svm_model = train_svm(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]}")