generated from LufsX/Challenge-SVM
This commit is contained in:
+117
-37
@@ -1,77 +1,157 @@
|
|||||||
|
# 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
|
||||||
|
"""
|
||||||
|
|
||||||
id = "202210423201"
|
id = "202210423201"
|
||||||
name = "陈瑞琪祥"
|
name = "陈瑞琪祥"
|
||||||
|
|
||||||
|
|
||||||
|
# 这里写自己的代码实现
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.model_selection import train_test_split
|
from sklearn.svm import SVC
|
||||||
from sklearn.metrics import accuracy_score
|
from sklearn.model_selection import train_test_split, cross_val_score
|
||||||
|
from sklearn.metrics import classification_report, accuracy_score
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
# 数据加载函数
|
# 数据加载函数
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
|
"""
|
||||||
|
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- filepath (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)
|
||||||
|
|
||||||
if label in [1, 2, 3]:
|
# 标签映射:将 1->0, 2->1, 3->2
|
||||||
label = {1: 0, 2: 1, 3: 2}[label]
|
if label == 1:
|
||||||
data.append(features)
|
label = 0
|
||||||
labels.append(label)
|
elif label == 2:
|
||||||
|
label = 1
|
||||||
|
elif label == 3:
|
||||||
|
label = 2
|
||||||
else:
|
else:
|
||||||
print(f"无效标签,跳过此样本:{label}")
|
print(f"无效标签,跳过此样本:{label}")
|
||||||
|
continue # 跳过无效标签
|
||||||
|
|
||||||
return np.array(data), np.array(labels)
|
# 添加数据和标签
|
||||||
|
data.append(features)
|
||||||
|
labels.append(label)
|
||||||
|
|
||||||
# 线性SVM训练函数
|
# 转换为numpy数组
|
||||||
def train_svm(X, y):
|
data = np.array(data)
|
||||||
n_samples, n_features = X.shape
|
labels = np.array(labels)
|
||||||
weights = np.zeros(n_features)
|
|
||||||
bias = 0
|
|
||||||
learning_rate = 0.01
|
|
||||||
iterations = 1000
|
|
||||||
|
|
||||||
for _ in range(iterations):
|
return data, labels
|
||||||
for idx, x_i in enumerate(X):
|
|
||||||
condition = y[idx] * (np.dot(x_i, weights) - bias) >= 1
|
|
||||||
if not condition:
|
|
||||||
weights -= learning_rate * (2 * weights - np.dot(x_i, y[idx]))
|
|
||||||
bias -= learning_rate * y[idx]
|
|
||||||
|
|
||||||
return weights, bias
|
|
||||||
|
|
||||||
# 预测函数
|
def train_svm(X, y, other_params=None):
|
||||||
def predict_svm(X, weights, bias):
|
"""
|
||||||
return np.sign(np.dot(X, weights) - bias)
|
支持向量机训练函数。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- X (numpy array): 特征数据。
|
||||||
|
- y (numpy array): 标签数据。
|
||||||
|
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将无法通过自动评测,成绩为零。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- SVC: 训练好的SVM模型。
|
||||||
|
"""
|
||||||
|
# 使用高斯核(RBF核)训练SVM
|
||||||
|
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
||||||
|
model.fit(X, y)
|
||||||
|
|
||||||
|
return model
|
||||||
|
|
||||||
|
|
||||||
|
def predict_svm(inX, model):
|
||||||
|
"""
|
||||||
|
支持向量机预测函数。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- inX (numpy array): 输入待分类的样本。
|
||||||
|
- model (SVC): 训练得到的支持向量机模型。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- int: 预测的分类标签。
|
||||||
|
"""
|
||||||
|
return model.predict(inX.reshape(1, -1))[0]
|
||||||
|
|
||||||
# 评估函数
|
|
||||||
def evaluate_svm(test_data, weights, bias):
|
|
||||||
predictions = [predict_svm(test_data[i].reshape(1, -1), weights, bias) for i in range(len(test_data))]
|
|
||||||
return predictions
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载数据
|
# 加载数据
|
||||||
X, y = 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_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
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)
|
||||||
|
|
||||||
# 训练SVM模型
|
# 数据标准化
|
||||||
weights, bias = train_svm(X_train, y_train)
|
scaler = StandardScaler()
|
||||||
|
X_train = scaler.fit_transform(X_train)
|
||||||
|
X_test = scaler.transform(X_test)
|
||||||
|
|
||||||
|
# 交叉验证评估
|
||||||
|
print("正在进行交叉验证评估...")
|
||||||
|
|
||||||
|
# 使用交叉验证计算准确率,设置10折交叉验证
|
||||||
|
svm_model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
||||||
|
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("正在训练支持向量机模型...")
|
||||||
|
svm_model.fit(X_train, y_train)
|
||||||
|
|
||||||
# 预测测试集
|
# 预测测试集
|
||||||
y_pred = evaluate_svm(X_test, weights, bias)
|
y_pred = svm_model.predict(X_test)
|
||||||
|
|
||||||
# 评估模型
|
# 输出评估结果
|
||||||
|
print("\n分类报告:")
|
||||||
|
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.reshape(1, -1), weights, bias)
|
y_pred_single = predict_svm(test_sample, svm_model)
|
||||||
print(f"\n单个样本预测结果: {y_pred_single[0]}, 实际结果: {y_test[11]}")
|
print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_test[11]}")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user