From c4372fb6005215579efe3ea3bb9116d1d12f685f Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Thu, 31 Oct 2024 15:14:45 +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 | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/function.py b/function.py index 0007b5b..e1768e0 100644 --- a/function.py +++ b/function.py @@ -4,6 +4,120 @@ import numpy as np """ 实验说明: - 自行编写实现数据加载与预测病马死亡的对率回归算法。 +# 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 = "202210423213" +name = "熊浩燃" + +def sigmoid(z): + return 1 / (1 + np.exp(-z)) + +def min_max_normalize(X): + """ 数据归一化:使用Min-Max Scaling """ + return (X - np.min(X, axis=0)) / (np.max(X, axis=0) - np.min(X, axis=0)) + +def train_logreg(X, y, learning_rate=0.001, iterations=2000, batch_size=32, lambda_=0.1): + """ + 对率回归训练函数,包含批量梯度下降和L2正则化。 + + Args: + - X (numpy array): 特征数据。 + - y (numpy array): 标签数据。 + - learning_rate (float): 学习率。 + - iterations (int): 迭代次数。 + - batch_size (int): 每次更新的样本数。 + - lambda_ (float): L2正则化项的系数。 + + Returns: + - numpy array: 训练得到的权重。 + """ + X = min_max_normalize(X) # 使用Min-Max归一化数据 + m, n = X.shape + weights = np.zeros(n) + + for _ in range(iterations): + # 确保 batch_size 不超过 m + effective_batch_size = min(batch_size, m) + + # 随机选择一个小批量 + indices = np.random.choice(m, effective_batch_size, replace=False) + X_batch = X[indices] + y_batch = y[indices] + + # 计算预测和梯度 + z = np.dot(X_batch, weights) + h = sigmoid(z) + gradient = np.dot(X_batch.T, (h - y_batch)) / effective_batch_size + lambda_ * weights + weights -= learning_rate * gradient + + return weights + +def predict_logreg(inX, weights): + """ + 对率回归预测函数。 + + Args: + - inX (numpy array): 输入待分类的样本。 + - weights (numpy array): 训练得到的权重。 + + Returns: + - int: 预测的分类标签。 + """ + probability = sigmoid(np.dot(inX, weights)) + return 1 if probability >= 0.5 else 0 + +def load_data(filepath): + """ + 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + + Args: + - filepath (str): 数据文件路径。 + + Returns: + - np.array: 特征数据。 + - np.array: 标签数据。 + """ + data = [] + labels = [] + with open(filepath, 'r') as file: + for line in file: + line_data = line.strip().split() + if '?' not in line_data: # 忽略缺失值的行 + data.append([float(x) for x in line_data[:-1]]) + labels.append(int(float(line_data[-1]))) + return np.array(data), np.array(labels) + +if __name__ == "__main__": + # 测试数据加载和模型训练预测 + X_train, y_train = load_data("./data/horse-colic.data") + X_test, y_test = load_data("./data/horse-colic.test") + + # 训练对率回归模型 + weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=2000, batch_size=32, lambda_=0.1) + + # 测试单个数据 + y_pred = predict_logreg(X_test[11], weights) + print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") 注意事项: - 在 function.py 中实现对率回归算法。