generated from LufsX/Challenge-SVM
This commit is contained in:
+73
-35
@@ -28,7 +28,24 @@ name = "董秋"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
import numpy as np
|
||||
from sklearn.svm import SVC
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.metrics import classification_report, accuracy_score
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
# 数据加载函数
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
labels = []
|
||||
|
||||
@@ -39,11 +56,11 @@ def load_data(filepath):
|
||||
# 处理缺失值,用0填充
|
||||
fields = [0 if f == '?' else float(f) for f in fields]
|
||||
|
||||
# 特征是除最后一列外的所有列
|
||||
features = np.array(fields[:-1], dtype=float)
|
||||
# 标签是倒数第6列
|
||||
label = int(fields[-6])
|
||||
|
||||
# 标签是最后一列
|
||||
label = int(fields[-1])
|
||||
# 特征为其他列(不包含倒数第6列标签)
|
||||
features = np.array(fields[: -6] + fields[-5:], dtype=float)
|
||||
|
||||
# 标签映射:将 1->0, 2->1, 3->2
|
||||
if label == 1:
|
||||
@@ -61,53 +78,74 @@ def load_data(filepath):
|
||||
labels.append(label)
|
||||
|
||||
# 转换为numpy数组
|
||||
labels = np.array(labels)
|
||||
data = np.array(data)
|
||||
|
||||
# 检查标签的唯一值,确保只有 0, 1, 2
|
||||
unique_labels = np.unique(labels)
|
||||
|
||||
if len(unique_labels) != 3:
|
||||
print(f"错误:标签数据包含的类别不是3个,实际类别为:{unique_labels}")
|
||||
raise ValueError("标签数量不为3,请确保标签未合并!")
|
||||
labels = np.array(labels)
|
||||
|
||||
return data, labels
|
||||
|
||||
def train_svm(X, y, learning_rate=0.01, iterations=1000, regularization_strength=0.01):
|
||||
n_samples, n_features = X.shape
|
||||
n_classes = len(np.unique(y))
|
||||
weights = np.zeros((n_classes, n_features))
|
||||
|
||||
# 将标签转化为多类别(one-vs-rest)形式
|
||||
y_one_vs_rest = np.array([[1 if y[i] == c else -1 for c in range(n_classes)] for i in range(n_samples)])
|
||||
def train_svm(X, y, other_params=None):
|
||||
"""
|
||||
支持向量机训练函数。
|
||||
|
||||
for _ in range(iterations):
|
||||
# 计算预测值
|
||||
margins = y_one_vs_rest * (X @ weights.T)
|
||||
mask = margins < 1
|
||||
grad = -np.einsum('ij,ik->kj', y_one_vs_rest * mask, X) / n_samples
|
||||
weights -= learning_rate * (grad + regularization_strength * weights)
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将无法通过自动评测,成绩为零。
|
||||
|
||||
return weights
|
||||
Returns:
|
||||
- SVC: 训练好的SVM模型。
|
||||
"""
|
||||
# 使用高斯核(RBF核)训练SVM
|
||||
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
||||
model.fit(X, y)
|
||||
|
||||
def predict_svm(X, weights):
|
||||
scores = X @ weights.T
|
||||
return np.argmax(scores, axis=1)
|
||||
return model
|
||||
|
||||
|
||||
def predict_svm(inX, model):
|
||||
"""
|
||||
支持向量机预测函数。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- model (SVC): 训练得到的支持向量机模型。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
return model.predict(inX.reshape(1, -1))[0]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 加载训练集
|
||||
# 加载数据
|
||||
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_train, y_train, test_size=0.2, random_state=42, stratify=y_train)
|
||||
|
||||
# 数据标准化
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_test = scaler.transform(X_test)
|
||||
|
||||
# 训练支持向量机模型
|
||||
weights = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||
print("正在训练支持向量机模型...")
|
||||
svm_model = train_svm(X_train, y_train)
|
||||
|
||||
# 预测测试集
|
||||
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)
|
||||
print(f"测试集准确率: {accuracy * 100:.2f}%")
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_svm(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
test_sample = X_test[11] # 选择第12个样本(从0开始计数)
|
||||
y_pred_single = predict_svm(test_sample, svm_model)
|
||||
print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_test[11]}")
|
||||
|
||||
Reference in New Issue
Block a user