From 8d4d353ec2f58e7734add49d263365f4a38185bc Mon Sep 17 00:00:00 2001 From: 77 <3298722099@qq.com> Date: Fri, 27 Dec 2024 14:34:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/function.py b/function.py index aaff34e..edcfb86 100644 --- a/function.py +++ b/function.py @@ -9,17 +9,17 @@ def load_data(filepath): data = np.genfromtxt(filepath, delimiter=',', dtype=float, filling_values=np.nan) except Exception as e: print(f"数据加载错误,可能是由于数据格式不正确:{e}") - return None, None + return None # 检查数据是否为二维数组 if data is None or data.ndim != 2: print("数据不是二维数组,无法继续处理。") - return None, None + return None # 确保所有行都有相同数量的列 if data.shape[1] < 2: print("数据列数不正确,无法继续处理。") - return None, None + return None # 分离特征和标签 X = data[:, :-1] @@ -45,20 +45,32 @@ def train_svm(X, y, learning_rate=0.01, iterations=1000, regularization=1.0): def predict_svm(inX, weights, bias): return np.sign(np.dot(inX, weights) - bias) +def evaluate_svm(X_test, y_test, weights, bias): + if X_test is None or y_test is None: + print("测试数据加载失败,无法评估。") + return 0 + + correct = 0 + for i in range(len(X_test)): + if predict_svm(X_test[i], weights, bias) == y_test[i]: + correct += 1 + accuracy = correct / len(X_test) + return accuracy + if __name__ == "__main__": # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") - if X_train is None or y_train is None: + if X_train is None: print("训练数据加载失败。") else: # 加载测试集 X_test, y_test = load_data("./data/horse-colic.test") - if X_test is None or y_test is None: + if X_test is None: print("测试数据加载失败。") else: # 训练支持向量机模型 weights, bias = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000) - # 测试单个数据 - y_pred = predict_svm(X_test[11], weights, bias) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") \ No newline at end of file + # 评估模型 + accuracy = evaluate_svm(X_test, y_test, weights, bias) + print(f"模型准确率: {accuracy}") \ No newline at end of file