generated from LufsX/Challenge-SVM
This commit is contained in:
+97
-54
@@ -1,5 +1,8 @@
|
||||
import numpy as np
|
||||
|
||||
from sklearn.svm import SVC
|
||||
from sklearn.model_selection import train_test_split, KFold
|
||||
from sklearn.metrics import classification_report, accuracy_score
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
"""
|
||||
挑战说明:
|
||||
@@ -26,84 +29,124 @@ import numpy as np
|
||||
id = "202210423117"
|
||||
name = "程悦"
|
||||
|
||||
# 数据加载函数
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
# 支持向量机训练函数
|
||||
def train_svm(X, y, other_params="你自己设置一些其它参数"):
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
labels = []
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
fields = line.strip().split()
|
||||
# 处理缺失值,用0填充
|
||||
fields = [0 if f == '?' else float(f) for f in fields]
|
||||
# 标签是倒数第6列
|
||||
label = int(fields[-6])
|
||||
# 特征为其他列(不包含倒数第6列标签)
|
||||
features = np.array(fields[: -6] + fields[-5:], dtype=float)
|
||||
# 标签映射:将 1->0, 2->1, 3->2
|
||||
if label == 1:
|
||||
label = 0
|
||||
elif label == 2:
|
||||
label = 1
|
||||
elif label == 3:
|
||||
label = 2
|
||||
else:
|
||||
print(f"无效标签,跳过此样本:{label}")
|
||||
continue # 跳过无效标签
|
||||
# 添加数据和标签
|
||||
data.append(features)
|
||||
labels.append(label)
|
||||
# 转换为numpy数组
|
||||
data = np.array(data)
|
||||
labels = np.array(labels)
|
||||
return data, labels
|
||||
|
||||
|
||||
def train_svm(X, y, other_params=None):
|
||||
"""
|
||||
支持向量机训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将无法通过自动评测,成绩为零。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
- SVC: 训练好的SVM模型。
|
||||
"""
|
||||
n_samples, n_features = X.shape
|
||||
weights = np.zeros(n_features)
|
||||
bias = 0
|
||||
learning_rate = 0.001
|
||||
iterations = 1000
|
||||
|
||||
for _ in range(iterations):
|
||||
for i in range(n_samples):
|
||||
if y[i] * (np.dot(X[i], weights) + bias) <= 1:
|
||||
weights = weights - learning_rate * (weights - y[i] * X[i])
|
||||
bias = bias - learning_rate * y[i]
|
||||
else:
|
||||
weights = weights - learning_rate * weights
|
||||
|
||||
return weights
|
||||
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
||||
model.fit(X, y)
|
||||
return model
|
||||
|
||||
|
||||
# 支持向量机预测函数
|
||||
def predict_svm(inX, weights):
|
||||
def predict_svm(inX, model):
|
||||
"""
|
||||
支持向量机预测函数。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
- model (SVC): 训练得到的支持向量机模型。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
prediction = np.sign(np.dot(inX, weights))
|
||||
return prediction
|
||||
|
||||
|
||||
# 从文件中加载数据函数
|
||||
def load_data(filepath):
|
||||
data, labels = [], []
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f.readlines():
|
||||
line = line.strip().split()
|
||||
if len(line) >= 1 and line[-1].isdigit():
|
||||
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
|
||||
data.append(line_data)
|
||||
labels.append(int(line[-1]))
|
||||
|
||||
data = np.array(data)
|
||||
labels = np.array(labels)
|
||||
|
||||
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
||||
|
||||
|
||||
return data, labels
|
||||
return model.predict(inX.reshape(1, -1))[0]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
# 加载数据
|
||||
X_train, y_train = load_data("./horse-colic.data")
|
||||
X_test, y_test = load_data("./horse-colic.test")
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
# 划分数据集(这里划分出一部分作为最终测试集,剩下的用于交叉验证训练)
|
||||
X_full_train, X_final_test, y_full_train, y_final_test = train_test_split(X_train, y_train, test_size=0.2, random_state=42, stratify=y_train)
|
||||
|
||||
# 训练支持向量机模型
|
||||
weights = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||
# 数据标准化
|
||||
scaler = StandardScaler()
|
||||
X_full_train = scaler.fit_transform(X_full_train)
|
||||
X_final_test = scaler.transform(X_final_test)
|
||||
|
||||
# 定义要尝试的C值列表
|
||||
C_values = [0.1, 1, 10]
|
||||
best_accuracy = 0
|
||||
best_model = None
|
||||
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
||||
for C in C_values:
|
||||
avg_accuracy = 0
|
||||
for train_index, val_index in kf.split(X_full_train):
|
||||
X_train_fold, X_val_fold = X_full_train[train_index], X_full_train[val_index]
|
||||
y_train_fold, y_val_fold = y_full_train[train_index], y_full_train[val_index]
|
||||
model = SVC(kernel='rbf', C=C, gamma='scale', random_state=42)
|
||||
model.fit(X_train_fold, y_train_fold)
|
||||
y_pred_fold = model.predict(X_val_fold)
|
||||
accuracy_fold = accuracy_score(y_val_fold, y_pred_fold)
|
||||
avg_accuracy += accuracy_fold
|
||||
avg_accuracy /= 5
|
||||
if avg_accuracy > best_accuracy:
|
||||
best_accuracy = avg_accuracy
|
||||
best_model = model
|
||||
|
||||
# 使用在交叉验证中选出的最佳模型在最终测试集上进行评估
|
||||
y_pred = best_model.predict(X_final_test)
|
||||
|
||||
# 输出评估结果
|
||||
print("\n分类报告:")
|
||||
print(classification_report(y_final_test, y_pred, target_names=["存活", "安乐死", "死亡"]))
|
||||
|
||||
# 输出准确率
|
||||
accuracy = accuracy_score(y_final_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_final_test[11] # 选择第12个样本(从0开始计数)
|
||||
y_pred_single = predict_svm(test_sample, best_model)
|
||||
print(f"\n单个样本预测结果: {y_pred_single}, 实际结果: {y_final_test[11]}")
|
||||
Reference in New Issue
Block a user