From b0969e36dfa15e343538fcc2d0817934e7af324c Mon Sep 17 00:00:00 2001 From: cy <939601402@qq.com> Date: Sat, 26 Oct 2024 12:36:12 +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 | 164 +++++++++++++++++++++++++++------------------------- 1 file changed, 85 insertions(+), 79 deletions(-) diff --git a/function.py b/function.py index dc03465..fc81a79 100644 --- a/function.py +++ b/function.py @@ -24,86 +24,92 @@ import numpy as np id = "202210423117" name = "程悦" -def sigmoid(z): - return 1.0 / (1 + np.exp(-z)) +def sigmoid(z): + return 1.0 / (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): 学习率。 + - iterations (int): 迭代次数。 + + Returns: + - numpy array: 训练得到的权重。 + """ + m, n = X.shape + weights = np.zeros(n) + for i 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 -# 这里写自己的代码实现 -def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=256): - """ - 对率回归训练函数。 - - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 - - Returns: - - numpy array: 训练得到的权重。 - """ - m, n = X.shape - weights = np.zeros(n) - for i 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 - -def predict_logreg(inX, weights): - """ - 对率回归预测函数。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - - Returns: - - int: 预测的分类标签。 - """ - z = np.dot(inX, weights) - h = sigmoid(z) - return 1 if h > 0.5 else 0 +def predict_logreg(inX, weights): + """ + 对率回归预测函数。 + + Args: + - inX (numpy array): 输入待分类的样本。 + - weights (numpy array): 训练得到的权重。 + + Returns: + - int: 预测的分类标签。 + """ + z = np.dot(inX, weights) + h = sigmoid(z) + return 1 if h > 0.5 else 0 # 这里也写自己的代码实现 -def load_data(filepath): - """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 +def load_data(filepath): + """ + 从文件中加载数据,处理缺失值,并修改指定的特征。 + + Args: + - filepath (str): 数据文件路径。 + + Returns: + - np.array: 特征数据。 + - np.array: 标签数据。 + """ + data = [] + labels = [] + with open(filepath, 'r') as f: + lines = f.readlines() + for line in lines: + line = line.strip().split() + if len(line) >= 1 and line[-1].isdigit(): + # 处理缺失值,用0填充 + line_data = [1 if i == 0 else (0 if x == '?' else float(x)) for i, x in enumerate(line[:-1])] + + # 修改特征23(索引为22,因为索引从0开始) + if int(line[22]) in [2, 3]: + line_data[22] = 0 # 将2和3合并为0(表示死亡) + else: + line_data[22] = 1 # 1表示存活 + + # 去掉特征3(索引为2)和特征24到28(索引为23到28) + line_data = line_data[:2] + line_data[3:23] + line_data[29:] + + data.append(line_data) + labels.append(int(line[-1])) + + return np.array(data), np.array(labels) - Args: - - directory (str): 数据文件路径。 - - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ - data = [] - labels = [] - with open(filepath, 'r') as f: - lines = f.readlines() - for line in lines: - line = line.strip().split() - if '?' not in line: - line_data = [1] + [0 if x == '?' else float(x) for x in [line[i] for i in range(len(line) - 1) if i not in [2, 23, 24, 25, 26, 27]]] - target = int(line[22]) - if target in [2, 3]: - target = 0 - else: - target = 1 - data.append(line_data) - labels.append(target) - 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.01, iterations=1000) - - # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") +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.01, iterations=1000) + + # 测试单个数据 + y_pred = predict_logreg(X_test[11], weights) + print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") \ No newline at end of file