From 56422eb0fda2985c8f534a640bd3c259f537b9e2 Mon Sep 17 00:00:00 2001 From: Frae19 <515745323@qq.com> Date: Thu, 31 Oct 2024 17:10:05 +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 | 79 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 9 deletions(-) diff --git a/function.py b/function.py index 409b1ac..cbd2f10 100644 --- a/function.py +++ b/function.py @@ -21,23 +21,47 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423629" +name = "Tanjunfeng" # 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): +def train_logreg(X, y, learning_rate=0.01, iterations=1000): """ 对率回归训练函数。 Args: - X (numpy array): 特征数据。 - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 + - learning_rate (float): 学习率,默认0.01。 + - iterations (int): 迭代次数,默认1000。 Returns: - numpy array: 训练得到的权重。 """ + import numpy as np + + # 获取样本数量和特征数量 + m, n = X.shape + + # 在 X 前添加一列 1,用于偏置项 + X = np.hstack((np.ones((m, 1)), X)) + + # 初始化权重 + weights = np.zeros(n + 1) + + # 开始迭代训练 + for _ in range(iterations): + # 计算线性组合 z + z = np.dot(X, weights) + # 通过 sigmoid 函数计算预测值 + h = 1 / (1 + np.exp(-z)) + # 计算梯度 + gradient = np.dot(X.T, (y - h)) + # 更新权重(使用梯度上升) + weights += learning_rate * gradient + + return weights def predict_logreg(inX, weights): @@ -51,24 +75,52 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ + import numpy as np + + # 在输入样本前添加 1,用于偏置项 + inX = np.insert(inX, 0, 1) + + # 计算线性组合 z + z = np.dot(inX, weights) + # 通过 sigmoid 函数计算预测值 + h = 1 / (1 + np.exp(-z)) + # 根据 0.5 阈值返回分类结果 + return int(h >= 0.5) -# 这里也写自己的代码实现 def load_data(filepath): """ 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 Args: - - directory (str): 数据文件路径。 + - filepath (str): 数据文件路径。 Returns: - np.array: 特征数据。 - np.array: 标签数据。 """ + import numpy as np + import pandas as pd + + # 读取数据,指定空格为分隔符,处理缺失值 '?' + data = pd.read_csv(filepath, delim_whitespace=True, header=None, na_values='?') + + # 丢弃包含缺失值的行 + data = data.dropna() + + # 提取特征和标签 + X = data.iloc[:, :-1].values # 所有列,除最后一列 + y = data.iloc[:, -1].values # 最后一列为标签 + + # 将标签转换为二分类1: 存活,0: 死亡或安乐死 + y = np.where(y == 1, 0, 1) + + return X, y if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改 + # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") @@ -76,8 +128,17 @@ 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, learning_rate=0.001, iterations=5000) # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + 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}%")