generated from LufsX/Challenge-SVM
68 lines
2.0 KiB
Python
68 lines
2.0 KiB
Python
|
|
id = "202210423201"
|
|
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):
|
|
data = []
|
|
labels = []
|
|
|
|
with open(filepath, 'r') as file:
|
|
for line in file:
|
|
fields = line.strip().split()
|
|
fields = [0 if f == '?' else float(f) for f in fields]
|
|
|
|
label = int(fields[-6])
|
|
features = np.array(fields[:-6] + fields[-5:], dtype=float)
|
|
|
|
if label in [1, 2, 3]:
|
|
label = {1: 0, 2: 1, 3: 2}[label]
|
|
data.append(features)
|
|
labels.append(label)
|
|
else:
|
|
print(f"无效标签,跳过此样本:{label}")
|
|
|
|
return np.array(data), np.array(labels)
|
|
|
|
def train_svm(X, y):
|
|
"""
|
|
支持向量机训练函数。
|
|
"""
|
|
scaler = StandardScaler()
|
|
X_scaled = scaler.fit_transform(X)
|
|
|
|
model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
|
model.fit(X_scaled, y)
|
|
return model, scaler
|
|
|
|
def predict_svm(model, scaler, X):
|
|
X_scaled = scaler.transform(X)
|
|
return model.predict(X_scaled)
|
|
|
|
if __name__ == "__main__":
|
|
# 加载数据
|
|
X, y = load_data("./data/horse-colic.data")
|
|
|
|
# 分割数据集
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
|
|
# 训练SVM模型
|
|
svm_model, scaler = train_svm(X_train, y_train)
|
|
|
|
# 预测测试集
|
|
y_pred = predict_svm(svm_model, scaler, X_test)
|
|
|
|
# 评估模型
|
|
accuracy = accuracy_score(y_test, y_pred)
|
|
print(f"测试集准确率: {accuracy * 100:.2f}%")
|
|
|
|
# 测试单个数据
|
|
test_sample = X_test[11] # 选择第12个样本(从0开始计数)
|
|
y_pred_single = predict_svm(svm_model, scaler, test_sample.reshape(1, -1))
|
|
print(f"\n单个样本预测结果: {y_pred_single[0]}, 实际结果: {y_test[11]}") |