From 9b0d573f0cadc3abd7e4d8bbaff428847df2d8ac Mon Sep 17 00:00:00 2001 From: Dengddd <3149942468@qq.com> Date: Thu, 31 Oct 2024 14:35:31 +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 | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/function.py b/function.py index 27ecb63..836b618 100644 --- a/function.py +++ b/function.py @@ -33,28 +33,13 @@ def sigmoid(z): return 1 / (1 + np.exp(-z)) def train_logreg(X, y, learning_rate=0.01, iterations=1000): - """ - 对率回归训练函数。 - - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - learning_rate (float): 学习率,默认值为0.01。 - - iterations (int): 迭代次数,默认值为1000。 - - Returns: - - weights (numpy array): 训练得到的权重。 - """ - # 初始化权重 + """对率回归训练函数。""" weights = np.zeros(X.shape[1]) - # 训练模型 for _ in range(iterations): z = np.dot(X, weights) predictions = sigmoid(z) - # 计算梯度 gradient = np.dot(X.T, (predictions - y)) / y.size - # 更新权重 weights -= learning_rate * gradient return weights @@ -82,25 +67,41 @@ def load_data(filepath): for i in range(len(data)): if len(data[i]) < max_columns: data[i].extend(['nan'] * (max_columns - len(data[i]))) - + # 转换成numpy数组,处理缺失值 data_array = np.array(data, dtype=float) data_array[np.isnan(data_array)] = np.nanmean(data_array, axis=0) - + return data_array[:, :-1], data_array[:, -1] -# 主逻辑 +def preprocess_data(X, y): + """数据预处理,合并特征23的值,并删除特征3和特征24~28。""" + # 合并特征23的值:将2(死亡)和3(安乐死)合并为0(死亡) + y = np.where(y == 2, 0, y) # 将值2替换为0 + y = np.where(y == 3, 0, y) # 将值3替换为0 + + # 删除特征3和特征24~28(假设特征索引从0开始) + X = np.delete(X, [2] + list(range(23, 28)), axis=1) + + return X, y + if __name__ == "__main__": # 加载数据 X, y = load_data("./data/horse-colic.data") + # 数据预处理 + X, y = preprocess_data(X, y) + # 训练模型 weights = train_logreg(X, y) - # 加载测试数据并预测 + # 加载测试数据并进行预处理 X_test, y_test = load_data("./data/horse-colic.test") + X_test, y_test = preprocess_data(X_test, y_test) + + # 预测 predictions = predict_logreg(X_test, weights) # 打印预测结果和实际结果 - for i in range(min(10, len(y_test))): # 打印前10个结果或全部结果,取决于测试数据量 + for i in range(min(10, len(y_test))): print(f"预测结果: {predictions[i]}, 实际结果: {y_test[i]}")