From 0bdb5ddebdceb11b7576b44a5bd6abb418f16bfd Mon Sep 17 00:00:00 2001 From: YimingTang Date: Sun, 3 Nov 2024 00:00:13 +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 | 81 +++++++++++++++++++++++++++-------------------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/function.py b/function.py index b176385..f635722 100644 --- a/function.py +++ b/function.py @@ -1,55 +1,42 @@ -# function.py import numpy as np """ 实验说明: - 自行编写实现数据加载与预测病马死亡的对率回归算法。 - -注意事项: -- 在 function.py 中实现对率回归算法。 -- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 -- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。 - -测评环境: -- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz -- OS: Ubuntu 22.04.4 LTS -- Python: 3.10.12 -- numpy: 2.1.1 """ - -""" -请在这里填写学号和姓名,不填写即成绩无效。 -""" id = "202210423218" name = "唐一鸣" +def sigmoid(z): + return 1 / (1 + np.exp(-z)) -# 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): +def train_logreg(X, y, other_params=""): """ 对率回归训练函数。 Args: - X (numpy array): 特征数据。 - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 + - other_params (str): 其它参数,可选设置。 Returns: - numpy array: 训练得到的权重。 """ - m, n = X.shape # 样本数和特征数 - weights = np.zeros(n) # 初始化权重 - for _ in range(iterations): - # 计算当前模型的预测值 - z = np.dot(X, weights) - h = sigmoid(z) - # 计算损失函数的梯度 - gradient = np.dot(X.T, (h - y)) / m - # 更新权重 - weights -= learning_rate * gradient - return weights + m, n = X.shape + weights = np.zeros(n) + learning_rate = 0.01 + num_iterations = 1000 + for _ in range(num_iterations): + linear_model = np.dot(X, weights) + y_predicted = sigmoid(linear_model) + + # Gradient descent + gradient = np.dot(X.T, (y_predicted - y)) / m + weights -= learning_rate * gradient + + return weights def predict_logreg(inX, weights): """ @@ -62,24 +49,39 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - probability = sigmoid(np.dot(inX, weights)) - return 1 if probability >= 0.5 else 0 + prob = sigmoid(np.dot(inX, weights)) + return 1 if prob >= 0.5 else 0 -# 这里也写自己的代码实现 def load_data(filepath): """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + 从文件中加载数据,处理缺失值。 Args: - - directory (str): 数据文件路径。 + - filepath (str): 数据文件路径。 Returns: - np.array: 特征数据。 - np.array: 标签数据。 """ - data = np.loadtxt(filepath, delimiter=' ', dtype=float) - X = data[:, :-1] # 特征数据 - y = data[:, -1] # 标签数据 + with open(filepath, 'r') as f: + lines = f.readlines() + + data = [] + for line in lines: + # 替换缺失值 '?' 为 np.nan + row = line.strip().split() + row = [float(x) if x != '?' else np.nan for x in row] + data.append(row) + + data = np.array(data) + + # 处理缺失值:用均值替代缺失值 + data = np.where(np.isnan(data), np.nanmean(data, axis=0), data) + + # 特征为前n-1列,标签为最后一列 + X = data[:, :-1] + y = data[:, -1] + return X, y @@ -92,8 +94,9 @@ if __name__ == "__main__": X_test, y_test = load_data("./data/horse-colic.test") # 训练对率回归模型 - weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) + weights = train_logreg(X_train, y_train) # 测试单个数据 y_pred = predict_logreg(X_test[11], weights) print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") +