From 2a9bc6841469f5eddd7381fa7fa26068de682288 Mon Sep 17 00:00:00 2001 From: Frae19 <515745323@qq.com> Date: Thu, 31 Oct 2024 17:18:14 +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 | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/function.py b/function.py index cbd2f10..58b1316 100644 --- a/function.py +++ b/function.py @@ -90,7 +90,7 @@ def predict_logreg(inX, weights): def load_data(filepath): """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + 从文件中加载数据。 Args: - filepath (str): 数据文件路径。 @@ -100,17 +100,21 @@ def load_data(filepath): - np.array: 标签数据。 """ import numpy as np - import pandas as pd - # 读取数据,指定空格为分隔符,处理缺失值 '?' - data = pd.read_csv(filepath, delim_whitespace=True, header=None, na_values='?') + # 定义数据类型,将缺失值标记为 np.nan + def conv(value): + return np.nan if value == '?' else float(value) - # 丢弃包含缺失值的行 - data = data.dropna() + # 使用 genfromtxt 读取数据 + data = np.genfromtxt(filepath, delimiter=' ', dtype=float, converters=None, + missing_values='?', filling_values=np.nan, autostrip=True) - # 提取特征和标签 - X = data.iloc[:, :-1].values # 所有列,除最后一列 - y = data.iloc[:, -1].values # 最后一列为标签 + # 删除包含缺失值的行 + data = data[~np.isnan(data).any(axis=1)] + + # 特征和标签分开 + X = data[:, :-1] + y = data[:, -1] # 将标签转换为二分类1: 存活,0: 死亡或安乐死 y = np.where(y == 1, 0, 1) @@ -119,8 +123,6 @@ def load_data(filepath): if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 - # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") @@ -134,6 +136,16 @@ if __name__ == "__main__": y_pred = predict_logreg(X_test[C_11](), weights) print(f"预测结果: {y_pred}, 实际结果: {y_test[C_11]()}") + # 可选:计算测试集上的准确率 + correct = 0 + for i in range(len(X_test)): + y_pred = predict_logreg(X_test[i], weights) + if y_pred == y_test[i]: + correct += 1 + accuracy = correct / len(X_test) + print(f"模型在测试集上��准确率: {accuracy * 100:.2f}%") + + # 可选:计算测试集上的准确率 correct = 0 for i in range(len(X_test)):