From ed33cc1fc28b47059bbf1707c3c8fe48562c3925 Mon Sep 17 00:00:00 2001 From: llll <2992513220@qq.com> Date: Thu, 31 Oct 2024 23:12:27 +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 | 102 ++++++++++++++++++++++++++-------------------------- 1 file changed, 52 insertions(+), 50 deletions(-) diff --git a/function.py b/function.py index eec828e..532df55 100644 --- a/function.py +++ b/function.py @@ -26,65 +26,22 @@ name = "李燕如" # 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): - """ - 对率回归训练函数。 - - Args: - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 - - Returns: - - numpy array: 训练得到的权重。 - """ -# 添加截距项 - X = np.c_[np.ones(X.shape[0]), X] - # 初始化权重 - weights = np.zeros(X.shape[1]) - # 定义损失函数 - def loss(w): - predictions = sigmoid(np.dot(X, w)) - return -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) - # 定义梯度函数 - def gradient(w): - predictions = sigmoid(np.dot(X, w)) - return np.dot(X.T, (predictions - y)) / len(y) - # 使用BFGS算法优化 - result = fmin_bfgs(loss, weights, fprime=gradient, maxiter=iterations) - return result - -def predict_logreg(inX, weights): - """ - 对率回归预测函数。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - - Returns: - - int: 预测的分类标签。 - """ -inX = np.c_[1, inX] # 添加截距项 - 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=',', skiprows=1) + data = np.loadtxt(filepath, delimiter=',', skiprows=1) X = data[:, :-1] y = data[:, -1] return X, y + def sigmoid(z): """ Sigmoid函数。 @@ -97,8 +54,53 @@ def sigmoid(z): """ return 1 / (1 + np.exp(-z)) +def train_logreg(X, y, other_params="你自己设置一些其它参数"): + """ + 对率回归训练函数。 + + Args: + - X (numpy array): 特征数据。 + - y (numpy array): 标签数据。 + - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值。 + + Returns: + - numpy array: 训练得到的权重。 + """ + # 添加截距项 + X = np.c_[np.ones(X.shape[0]), X] + # 初始化权重 + weights = np.zeros(X.shape[1]) + + # 定义损失函数 + def loss(w): + predictions = sigmoid(np.dot(X, w)) + return -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) + + # 定义梯度函数 + def gradient(w): + predictions = sigmoid(np.dot(X, w)) + return np.dot(X.T, (predictions - y)) / len(y) + + # 使用minimize函数优化 + result = minimize(loss, weights, method='BFGS', jac=gradient) + return result.x + +def predict_logreg(inX, weights): + """ + 对率回归预测函数。 + + Args: + - inX (numpy array): 输入待分类的样本。 + - weights (numpy array): 训练得到的权重。 + + Returns: + - int: 预测的分类标签。 + """ + inX = np.c_[1, inX] # 添加截距项 + prob = sigmoid(np.dot(inX, weights)) + return 1 if prob > 0.5 else 0 + if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") @@ -106,9 +108,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]}") + print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}"