generated from LufsX/Challenge-SVM
This commit is contained in:
+21
-22
@@ -30,7 +30,7 @@ name = "董秋"
|
||||
# 这里写自己的代码实现
|
||||
import numpy as np
|
||||
from sklearn.svm import SVC
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.model_selection import train_test_split, cross_val_score
|
||||
from sklearn.metrics import classification_report, accuracy_score
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
@@ -40,7 +40,7 @@ def load_data(filepath):
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件路径。
|
||||
- filepath (str): 数据文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
@@ -119,33 +119,32 @@ def predict_svm(inX, model):
|
||||
|
||||
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)
|
||||
X, y = load_data("./data/horse-colic.data")
|
||||
|
||||
# 数据标准化
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_test = scaler.transform(X_test)
|
||||
X = scaler.fit_transform(X)
|
||||
|
||||
# 进行交叉验证评估
|
||||
print("正在进行交叉验证评估...")
|
||||
|
||||
# 使用交叉验证计算准确率,设置10折交叉验证
|
||||
svm_model = SVC(kernel='rbf', C=1.0, gamma='scale', random_state=42)
|
||||
cv_scores = cross_val_score(svm_model, X, y, cv=10, scoring='accuracy')
|
||||
|
||||
# 输出交叉验证的评估结果
|
||||
print(f"交叉验证准确率: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
|
||||
|
||||
# 训练支持向量机模型
|
||||
print("正在训练支持向量机模型...")
|
||||
svm_model = train_svm(X_train, y_train)
|
||||
|
||||
# 预测测试集
|
||||
y_pred = svm_model.predict(X_test)
|
||||
svm_model.fit(X, y)
|
||||
|
||||
# 输出评估结果
|
||||
y_pred = svm_model.predict(X)
|
||||
|
||||
# 输出分类报告
|
||||
print("\n分类报告:")
|
||||
print(classification_report(y_test, y_pred, target_names=["存活", "安乐死", "死亡"]))
|
||||
print(classification_report(y, y_pred, target_names=["存活", "安乐死", "死亡"]))
|
||||
|
||||
# 输出准确率
|
||||
accuracy = accuracy_score(y_test, y_pred)
|
||||
print(f"测试集准确率: {accuracy * 100:.2f}%")
|
||||
|
||||
# 测试单个数据
|
||||
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]}")
|
||||
accuracy = accuracy_score(y, y_pred)
|
||||
print(f"模型准确率: {accuracy * 100:.2f}%")
|
||||
|
||||
Reference in New Issue
Block a user